Adding a VPN “KillSwitch” to NetworkManager

I use a VPN connection most days, and leave it unattended. Sometimes, however, it is not as stable as I would like it to be, and it disconnects, for instance because of wireless network problems. The wireless connection is brought up again, but the VPN connection stays down, causing potentially sensible data to be exchanged through an insecure channel. Bad.

How can we solve this?

In jargon, a mechanism that disconnects you from the Internet when your VPN connection disconnects, is called a “VPN Kill Switch”. There is a simple way to add one to NetworkManager, thankfully, via a dispatcher script. These scripts will be automatically called when a connection goes up or down.

You can save the following in /etc/NetworkManager/dispatcher.d/99vpnkillswitch, and give it 0755 permissions (it must be owned by root):

#!/bin/sh

IFFILE=/var/run/vpnkillswitch.iface

interface=$1 status=$2
case $status in
    vpn-up)
        # Get the physical device associated with the VPN connection
        nmcli -f type,device c | awk '$1~/^vpn$/ && $2~/[^\-][^\-]/ { print $2; }' > "${IFFILE}"
    ;;
    vpn-down)
        xargs -n 1 -a "${IFFILE}" nmcli device disconnect
    ;;
esac

You’re good to go! Try stopping your VPN interface, and your associated physical interface should be brought down too.

Advertisements

2 Responses to Adding a VPN “KillSwitch” to NetworkManager

  1. wilson says:

    Looks like a simple script. I’m unsure about the device part. So type would be eth0(if thats my hardwire) and device being the mac address of eth0?
    Maybe give a couple of examples to make it easier for us greenhorns. Thanks.

    • tchernobog says:

      Hello Wilson,

      “nmcli -f type,device c” returns a list of connection types (such as ethernet, wireless, or vpn) along with their associated physical device (such as eth0, wlan0, etc.).

      In our case, when the connection goes up, we look for all lines where the first column equals “vpn”, and where the device different from “–” (which, being set, means the vpn connection is at the moment active).

      We write this value to a temporary file, so that when the connection goes down, we remember the interface it was associated with, and bring it down too.

      Cheers,
      Matteo

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: