123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- #! /bin/bash
- usage() {
- printf "Usage: %s [-i <interface>] [-n <network number>] [-t <namespace suffix>] (up|start|stop|down)\n" "$0"
- }
- # set defaults
- iface=eth0
- namespace=ns-vpn
- n=1
- # source local config
- conf=/etc/ns-vpn.sh
- [[ -f "$conf" ]] && . "$conf"
- while getopts i:n:t:h opt; do
- case $opt in
- i)
- iface=$OPTARG
- ;;
- n)
- n=$OPTARG
- ;;
- t)
- namespace=ns-vpn-$OPTARG
- ;;
- h)
- usage
- exit
- ;;
- ?)
- 2>&1 usage
- exit 1
- ;;
- esac
- done
- net=192.168.$n
- shift "$(( OPTIND - 1 ))"
- if [[ "$#" -lt 1 ]]; then
- 2>&1 usage
- exit 1
- fi
- create_namespace() {
- gw=$1.1
- ip=$1.2
- ns=$2
- veth0=${ns}-0
- veth1=${ns}-1
- mkdir -p /etc/netns/$ns
- cp /etc/resolv.conf /etc/netns/$ns/
- /usr/bin/ip -b - << EOF
- link add $veth0 type veth peer name $veth1
- addr add $gw peer $ip dev $veth0
- link set dev $veth0 up
- netns add $ns
- link set $veth1 netns $ns
- netns exec $ns ip link set dev lo up
- netns exec $ns ip addr add $ip/24 dev $veth1
- netns exec $ns ip link set up dev $veth1
- netns exec $ns ip route add default via $gw dev $veth1
- netns exec $ns ip addr add $ip peer $gw dev $veth1
- netns exec $ns ip link set $veth1 up
- netns exec $ns ip route add 192.168.0.0/24 via $gw dev $veth1
- EOF
- }
- destroy_namespace() {
- sn=$1.0/24
- gw=$1.1
- ip=$1.2
- ns=$2
- veth1=${ns}-1
- /usr/bin/ip -b - << EOF
- netns exec $ns ip route del 192.168.0.0/24 via $gw
- netns exec $ns ip route del $sn
- netns exec $ns ip route del default via $gw
- netns exec $ns ip route del $gw
- netns exec $ns ip addr del $ip/32 peer $gw dev $veth1
- netns exec $ns ip link del $veth1
- netns del $ns
- EOF
- }
- iptables_rules=(
- "FORWARD -i ${namespace}-0 -o $iface -j ACCEPT"
- "FORWARD -i $iface -o ${namespace}-0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"
- )
- iptables_nat_rules=(
- "POSTROUTING -s $net.2/32 -o $iface -j MASQUERADE"
- )
- case "$*" in
- up|start)
- create_namespace $net $namespace
- for rule in "${iptables_nat_rules[@]}"; do
- iptables -t nat -A $rule
- done
- for rule in "${iptables_rules[@]}"; do
- iptables -A $rule
- done
- ;;
- down|stop)
- for rule in "${iptables_rules[@]}"; do
- iptables -D $rule
- done
- for rule in "${iptables_nat_rules[@]}"; do
- iptables -t nat -D $rule
- done
- destroy_namespace $net $namespace
- ;;
- ?)
- 2>&1 usage
- exit 1
- esac
|