add license
[0tDNS.git] / src / netns-script
blob054dc2a815b9203f4ccb144462d2d8a55fcc8613
1 #!/bin/sh
3 # adapted from
4 # https://unix.stackexchange.com/questions/149293/feed-all-traffic-through-openvpn-for-a-specific-network-namespace-only
6 # vpn_wrapper.sh passes the following variables through openvpn's
7 # --setenv option:
8 # NAMESPACE_NAME
9 # WRAPPER_PID
10 # VETH_HOST0
11 # VETH_HOST1
12 # ROUTE_THROUGH_VETH
13 # PHYSICAL_IP
15 # tag veth names so that they are uniqie between instances of this script
16 VETH0=v0tdns${WRAPPER_PID}_0
17 VETH1=v0tdns${WRAPPER_PID}_1
19 case $script_type in
20 up)
21 ip netns add $NAMESPACE_NAME
22 ip netns exec $NAMESPACE_NAME ip link set dev lo up
23 ip link set dev "$1" up netns $NAMESPACE_NAME mtu "$2"
24 ip netns exec $NAMESPACE_NAME ip addr add dev "$1" \
25 "$4/${ifconfig_netmask:-30}" \
26 ${ifconfig_broadcast:+broadcast "$ifconfig_broadcast"}
27 if [ -n "$ifconfig_ipv6_local" ]; then
28 ip netns exec $NAMESPACE_NAME ip addr add dev "$1" \
29 "$ifconfig_ipv6_local"/112
32 # the following is done to enable some connections to bypass vpn
33 VETH0=v0tdns${WRAPPER_PID}_0
34 VETH1=v0tdns${WRAPPER_PID}_1
35 ip link add $VETH0 type veth peer name $VETH1
36 ip link set $VETH1 netns $NAMESPACE_NAME
37 ip addr add $VETH_HOST0/30 dev $VETH0
38 ip netns exec $NAMESPACE_NAME ip addr add $VETH_HOST1/30 dev $VETH1
39 ip link set $VETH0 up
40 ip netns exec $NAMESPACE_NAME ip link set $VETH1 up
42 route-up)
43 # user is responsible for enabling routing from physical
44 # interface to veth devices, we're enabling the reverse way
45 echo 1 > /proc/sys/net/ipv4/conf/$VETH0/forwarding
47 ip netns exec $NAMESPACE_NAME ip route add default \
48 via "$ifconfig_remote"
50 if [ -n "$ifconfig_ipv6_remote" ]; then
51 ip netns exec $NAMESPACE_NAME ip route add default via \
52 "$ifconfig_ipv6_remote"
55 # here go routes for bypassing vpn
56 for ADDRESS in $ROUTE_THROUGH_VETH; do
57 ip netns exec $NAMESPACE_NAME ip route add $ADDRESS via $VETH_HOST0
58 iptables -t nat -A POSTROUTING -s $VETH_HOST1/32 \
59 -j SNAT --to-source $PHYSICAL_IP
60 done
63 # notify our sh process, that openvpn finished initializing
64 kill -usr1 $WRAPPER_PID
66 down)
67 for ADDRESS in $ROUTE_THROUGH_VETH; do
68 iptables -t nat -D POSTROUTING -s $VETH_HOST1/32 \
69 -j SNAT --to-source $PHYSICAL_IP
70 done
72 ip netns delete $NAMESPACE_NAME
74 esac