pierwszy sprint
[0tDNS.git] / vpn_wrapper.sh
blobb4b9350cc4665286e51aa7a0c5b6817e01aa9b5e
1 #!/bin/sh
3 OPENVPN_CONFIG="$1"
4 # rest of args is the command to run in network namespace
5 shift
7 # just in case something causes more instances of this script
8 # to run simultaneously, we timestamp some names
9 SECONDS=`date '+%s'`
11 HELPER_SCRIPT=/var/lib/0tdns/helper_script$SECONDS.sh
12 NAMESPACE_NAME=0tdns$SECONDS
14 # we create another script as a way of passing variables
15 # to netns-script
16 cat > $HELPER_SCRIPT <<EOF
17 #!/bin/sh
19 export NAMESPACE_NAME=$NAMESPACE_NAME
20 export WRAPPER_PID=$$
22 /var/lib/0tdns/netns-script "\$@"
23 EOF
25 chmod u+x $HELPER_SCRIPT
27 # in case we want some process in the namespace to be able
28 # to resolve domain names via libc we put some random public
29 # dns in namespace sepcific's resolv.conf;
30 # note, that while libunbound we're using will probably have
31 # dns addresses provided by us, it is still possible to pass
32 # a domain name as forwarder address to unbound, in which case
33 # it will try to resolve it first using libc
34 mkdir -p /etc/netns/$NAMESPACE_NAME/
35 echo nameserver 23.253.163.53 > /etc/netns/$NAMESPACE_NAME/resolv.conf
37 # starts openvpn with our just-created helper script, which calls
38 # the netns-script, which creates tun inside network namespace
39 # of name $NAMESPACE_NAME
40 # we could consider using --daemon option instead of &
41 openvpn --ifconfig-noexec --route-noexec --up $HELPER_SCRIPT \
42 --route-up $HELPER_SCRIPT --down $HELPER_SCRIPT \
43 --config "$OPENVPN_CONFIG" --script-security 2 &
45 OPENVPN_PID=$!
47 # waiting for signal from our netns script
48 # https://stackoverflow.com/questions/9052847/implementing-infinite-wait-in-shell-scripting
49 trap true usr1
51 # wait on openvpn process;
52 # if we get a signal - wait will terminate;
53 # if openvpn process dies - wait will also terminate
54 wait $OPENVPN_PID
56 # TODO check which of 2 above mention situations occured and
57 # return from script with error code if openvpn process died
59 # run the provided command inside newly created namespace
60 # under '0tdns' user;
61 sudo ip netns exec $NAMESPACE_NAME sudo -u 0tdns "$@"
63 # close the connection
64 kill $OPENVPN_PID
65 wait $OPENVPN_PID
67 # we no longer need those
68 rm -r $HELPER_SCRIPT /etc/netns/$NAMESPACE_NAME/