Allowing network connections in Linux with active VPN only
There is a risk of data leakage through the default network connection that may occur while reconnecting to VPN servers or before a VPN connection is established. Therefore, it is necessary to allow accessing the network only when the VPN is up. This can be implemented with iptables.
# create chains for iptables sudo iptables -N ALLOWVPN sudo iptables -N BLOCKALL # allow access for the interfaces loopback, tun, and tap sudo iptables -A OUTPUT -o tun+ -j ACCEPT; sudo iptables -A OUTPUT -o tap+ -j ACCEPT; sudo iptables -A OUTPUT -o lo+ -j ACCEPT; # route outgoing data via our created chains sudo iptables -A OUTPUT -j ALLOWVPN; sudo iptables -A OUTPUT -j BLOCKALL; # allow connections to certain IP addresses with no active VPN sudo iptables -A ALLOWVPN -d 22.214.171.124 -j ACCEPT sudo iptables -A ALLOWVPN -d 126.96.36.199 -j ACCEPT # block all disallowed connections sudo iptables -A BLOCKALL -j DROP
sudo iptables -D OUTPUT -j BLOCKALL
sudo iptables -A OUTPUT -j BLOCKALL
Display all iptables rules:
To block traffic when using the box as gateway, apply these rules to both OUTPUT and FORWARD.
If you need a simple out-of-the-box solution, in the guide Enabling VPN-only access in Linux to the Net with NetBlocker we provide a script that eases up these manipulations.