Allowing network connections in Linux with active VPN only (kill switch)

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 (i.e. kill switch). 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 1.2.3.4 -j ACCEPT sudo iptables -A ALLOWVPN -d 5.6.7.8 -j ACCEPT # block all disallowed connections sudo iptables -A BLOCKALL -j DROP

Unblock:

sudo iptables -D OUTPUT -j BLOCKALL

Block again:

sudo iptables -A OUTPUT -j BLOCKALL

Display all iptables rules:

sudo iptables-save

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.