I have a VirtualBox VM running Ubuntu 14.04.3 that I would like to
- use as a Gateway router.
- connect to an OpenVPN server from this VM, and have all forwarding to the internet via VPN
- connect to local machines directly (not over VPN)
I followed instructions from here to setup the forwarding, which worked fine. My iptable rules (in a up.sh file) are
sudo iptables -A FORWARD -o tun0 -i eth0 -s 192.168.2.0/24 -m conntrack --ctstate NEW -j ACCEPT sudo iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A POSTROUTING -t nat -j MASQUERADE
The first rule is the one I added to allow forwarding to local resources.
I have a similar down.sh file to tear down the forwarding (or so, I hoped)
sudo iptables -D POSTROUTING -t nat -j MASQUERADE sudo iptables -D FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -D FORWARD -o tun0 -i eth0 -s 192.168.2.0/24 -m conntrack --ctstate NEW -j ACCEPT
I also executed the following command to enable forwarding
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
In my openvpn config.conf file, I have the scripts set to run via the following commands
script-security 2 up /etc/openvpn/up.sh down /etc/openvpn/down.sh
On VM startup, the up script is run and traffic is forwarded over the VPN (although the first few packets seem to be sent over the regular connection). To test the down script, I then do,
sudo killall openvpn
It looks like the script is run successfully, as all my iptable rules are removed. However, traffic is now forwarded over my regular internet connection (eth0).
How can I get the traffic forwarding to stop if VPN disconnects or is no longer operational? Ideally, I would like access to local resources at all times and the internet only via VPN (from my client machines).