Created
April 19, 2016 08:29
-
-
Save satanasov/fbcc828043dbdb75a15fc76848b85c35 to your computer and use it in GitHub Desktop.
netns Script for simplifying usage of netns and VPN ... have fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
IFACE="usb0" | |
NETNSNAME="anavarovpn" | |
OVPNCONF="/some/path/to/file.ovpn" | |
USER="user" | |
if [[ $UID != 0 ]]; then | |
echo "This must be run as root." | |
exit 1 | |
fi | |
function iface_up() { | |
ip netns add $NETNSNAME | |
ip netns exec $NETNSNAME ip addr add 127.0.0.1/8 dev lo | |
ip netns exec $NETNSNAME ip link set lo up | |
ip link add vpn0 type veth peer name vpn1 | |
ip link set vpn0 up | |
ip link set vpn1 netns $NETNSNAME up | |
ip addr add 10.200.200.1/24 dev vpn0 | |
ip netns exec $NETNSNAME ip addr add 10.200.200.2/24 dev vpn1 | |
ip netns exec $NETNSNAME ip route add default via 10.200.200.1 dev vpn1 | |
iptables -A INPUT \! -i vpn0 -s 10.200.200.0/24 -j DROP | |
iptables -t nat -A POSTROUTING -s 10.200.200.0/24 -o $IFACE -j MASQUERADE | |
sysctl -q net.ipv4.ip_forward=1 | |
mkdir -p /etc/netns/$NETNSNAME | |
echo 'nameserver 8.8.8.8' > /etc/netns/$NETNSNAME/resolv.conf | |
ip netns exec $NETNSNAME fping -q www.google.com | |
} | |
function iface_down() { | |
#Kill processes that are in this netns | |
ip netns pids $NETNSNAME | xargs -rd'\n' kill | |
rm -rf /etc/netns/$NETNSNAME | |
sysctl -q net.ipv4.ip_forward=0 | |
iptables -D INPUT \! -i vpn0 -s 10.200.200.0/24 -j DROP | |
iptables -t nat -D POSTROUTING -s 10.200.200.0/24 -o $IFACE -j MASQUERADE | |
ip netns delete $NETNSNAME | |
} | |
function start_vpn() { | |
ip netns exec $NETNSNAME openvpn --config $OVPNCONF & | |
while ! ip netns exec $NETNSNAME ip a show dev tun0 up; do | |
sleep .5 | |
done | |
} | |
function stop_vpn() { | |
killall openvpn | |
while ip netns exec $NETNSNAME ip a show dev tun0 up; do | |
sleep .5 | |
done | |
} | |
function run() { | |
shift | |
echo "$@" | |
ip netns exec $NETNSNAME sudo -u $USER "$@" | |
} | |
case "$1" in | |
up) | |
iface_up | |
start_vpn ;; | |
down) | |
stop_vpn | |
iface_down ;; | |
run) | |
run "$@" ;; | |
start_vpn) | |
start_vpn ;; | |
stop_vpn) | |
stop_vpn ;; | |
*) | |
echo "Syntax: $0 up|down|run|start_vpn|stop_vpn" | |
exit 1 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment