Block internet if vpn connection drops

Solution 1:

Try something like this

You wish to change ufw rules based on interface status.

Nice place for this kind of action is in /etc/network/if-down.d/ and /etc/network/if-up.d/

You can in this folder put some script and make action. For example put this script in /etc/network/if-down.d/ to change ufw rules every time when tun0go down.

Make script called script with execute permissions 755

sudo nano /etc/network/if-down.d/script

Script is

# Check interface
[ "$IFACE" != "tun0" ] || exit 0
# Do something
sudo ufw default deny outgoing
sudo ufw allow out to xxx.xxx.xxx.xxx

Change permision of script

chmod 755 /etc/network/if-down.d/script

In script xxx.xxx.xxx.xxx represent ip of your vpn server

When vpn reconnect you need again to change ufw rules. Make one more script aka script2

sudo nano /etc/network/if-up.d/script2

Script is something like this

# Check interface
[ "$IFACE" != "tun0" ] || exit 0
# Do something
sudo ufw default allow outgoing
#also you can add more ufw rules ...
sudo ufw ....

Change permision of script

chmod 755 /etc/network/if-up.d/script2

First script will if tun0 go down make default outgoing police to deny but will allow access to vpn server. Second script will change default outgoing police to allow

Solution 2:

You can do that just by using the ufw GUI:

  • Configure ufw to globally deny outgoing traffic (just like you did)
  • Add the following two rules, given that eth0 is your public interface, tun0 is the interface created by the VPN and xxx.xxx.68.138 is your VPN IP:
    1. Allow to connect to the VPN IP through the public interface: add a rule with Policy=Allow, Direction=Out, Interface=eth0 and To=xxx.xxx.68.138
    2. Allow everything through the VPN interface: add a rule with Policy=Allow, Direction=Out, Interface=tun0 and To=0.0.0.0/0

That's all!

You almost did it, you just forgotten to allow outgoing traffic through the VPN, because globally denying outgoing traffic applies on all interfaces, including the one created by the VPN.

By the way, I suggest you to globally deny incoming traffic, this will prevent an evil person or a bot running on your network to hack into your computer by exploiting a bug or a misconfiguration of a running network service (by default, Ubuntu runs some network services listening on all interfaces, not only the local).