Last active
July 31, 2017 19:02
-
-
Save kotfic/00db800fd27cefae842d44305a4ad482 to your computer and use it in GitHub Desktop.
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
#!/bin/sh | |
# | |
# | |
# this is a fork of schnouki's script, see original blog post | |
# https://schnouki.net/posts/2014/12/12/openvpn-for-a-single-application-on-linux/ | |
# | |
# original script can be found here | |
# https://gist.github.com/Schnouki/fd171bcb2d8c556e8fdf | |
NS_NAME=kitware | |
NS_EXEC="ip netns exec $NS_NAME" | |
# exit on unbound variable | |
set -u | |
# exit on error | |
set -e | |
set -o pipefail | |
# trace option | |
#set -x | |
if [ $USER != "root" ]; then | |
echo "This must be run as root." | |
exit 1 | |
fi | |
start_vpn() { | |
echo "Add network interface" | |
# Create the network namespace | |
ip netns add $NS_NAME | |
# Start the loopback interface in the namespace | |
$NS_EXEC ip addr add 127.0.0.1/8 dev lo | |
$NS_EXEC ip link set lo up | |
# Create virtual network interfaces that will let OpenVPN (in the | |
# namespace) access the real network, and configure the interface in the | |
# namespace (vpn1) to use the interface out of the namespace (vpn0) as its | |
# default gateway | |
ip link add vpn0 type veth peer name vpn1 | |
ip link set vpn0 up | |
ip link set vpn1 netns $NS_NAME up | |
ip addr add 10.0.0.1/24 dev vpn0 | |
$NS_EXEC ip addr add 10.0.0.2/24 dev vpn1 | |
$NS_EXEC ip link set dev vpn1 mtu 1492 | |
$NS_EXEC ip route add default via 10.0.0.1 dev vpn1 | |
sysctl -q net.ipv4.ip_forward=1 | |
# Configure the nameserver to use inside the namespace | |
mkdir -p /etc/netns/$NS_NAME | |
cat >/etc/netns/$NS_NAME/resolv.conf <<EOF || exit 1 | |
nameserver 8.8.8.8 | |
nameserver 8.8.4.4 | |
EOF | |
# IPv4 NAT | |
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -d 0.0.0.0/0 -j MASQUERADE | |
# we should have full network access in the namespace | |
$NS_EXEC ping -c 3 www.google.com | |
# start OpenVPN in the namespace | |
echo "Starting VPN" | |
cd /etc/openvpn | |
# TODO create openvpn configuration in /etc/openvpn/$NS_NAME.conf | |
$NS_EXEC openvpn --config /etc/openvpn/client/$NS_NAME.conf | |
} | |
stop_vpn() { | |
echo "Stopping VPN" | |
ip netns pids $NS_NAME | xargs -rd'\n' kill | |
# TODO wait for terminate | |
# clear NAT | |
iptables -t nat -D POSTROUTING -s 10.0.0.0/24 -d 0.0.0.0/0 -j MASQUERADE | |
echo "Delete network interface" | |
rm -rf /etc/netns/$NS_NAME | |
ip netns delete $NS_NAME | |
ip link delete vpn0 | |
} | |
case "$1" in | |
start) | |
start_vpn | |
;; | |
stop) | |
stop_vpn | |
;; | |
*) | |
echo "Usage: $0 {start|stop}" | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment