Created
May 16, 2018 21:14
-
-
Save pawelszydlo/1769ced8eb773502e1f3bb9fdade5434 to your computer and use it in GitHub Desktop.
Create a network namespace that is connected through a VPN
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/bash | |
if ip netns list | grep "vpnspace" > /dev/null; then | |
echo "Namespace already exists." | |
exit 1 | |
fi | |
# IP address of your external interface | |
INTERNET_IP=192.168.0.101 | |
# VPN configuration | |
VPN_CONFIG=/etc/openvpn/pia.conf | |
# IPs for the veths. Those should be from the same range. | |
VETH0_IP=172.16.0.1 | |
VETH1_IP=172.16.0.2 | |
VETH_BITS=12 | |
# Create the namespace called "vpnspace" | |
echo "Creating namespace..." | |
ip netns add vpnspace | |
# Bring up the loopback inside the namespace | |
ip netns exec vpnspace ip addr add 127.0.0.1/8 dev lo | |
ip netns exec vpnspace ip link set dev lo up | |
# Create linked, virtual interfaces | |
echo "Creating linked veth..." | |
ip link add veth0 type veth peer name veth1 | |
# Move one linked eth to the namespace | |
ip link set veth1 netns vpnspace | |
# Assign an IP address to the veth that will stay in global namespace and bring it up | |
ip addr add $VETH0_IP/$VETH_BITS dev veth0 | |
ip link set dev veth0 up | |
# Do the same for the veth inside the namespace | |
ip netns exec vpnspace ip addr add $VETH1_IP/$VETH_BITS dev veth1 | |
ip netns exec vpnspace ip link set dev veth1 up | |
# Set routing from namespace to general | |
echo "Setting routing..." | |
ip netns exec vpnspace ip route add default via $VETH0_IP dev veth1 | |
# Set up SNAT to handle packets coming from namespace | |
#iptables -D INPUT \! -i veth0 -s $VETH0_IP/28 -j DROP | |
#iptables -t nat -D POSTROUTING -s $VETH0_IP/28 -o eth0 -j MASQUERADE | |
iptables -t nat -A POSTROUTING -s $VETH0_IP/$VETH_BITS -o eth0 -j SNAT --to-source $INTERNET_IP | |
# Enable forwarding | |
sysctl -q net.ipv4.ip_forward=1 | |
# Configure DNS | |
#mkdir -p /etc/netns/vpnspace | |
#echo 'nameserver 8.8.8.8' > /etc/netns/vpnspace/resolv.conf | |
# Start the VPN | |
echo "Starting OpenVPN inside namespace..." | |
ip netns exec vpnspace openvpn --daemon --config "$VPN_CONFIG" | |
echo "Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment