Network Manager Auto VPN on wireless

You can not trust other people's wifi! Especially hotel, airport, restaurant and conference wifi networks are dangerous places. So, the general advice is to enable a VPN when using those networks. But if you are like me, you will also forget to enable it when you connect.

  • You are using Network Manager
  • You already have a VPN configured
  • You forget to activate it yourself and want to automatically connect on certain blacklisted/non-whitelisted networks

Solution: Add this file to /etc/network-manager/dispatcher.d (Debian location, name might be slightly different):

#!/bin/sh
WHITELIST_NETWORKS="myhomenetwork|workwifi|anotherworkwifithatItrust"
VPN_CONNECTION="nameofyourVPN"
case "$2" in
    up)
        if nmcli connection show --active | grep -v -E "${WHITELIST_NETWORKS}" | grep -q wifi
        then
            if ! nmcli connection show --active | grep "${VPN_CONNECTION}" | grep -q vpn
        then
                nmcli con up "${VPN_CONNECTION}"
                sleep 2
            fi
        fi
        ;;
    *)
        exit 0
        ;;
esac

When you connect to wifi, it will automatically connect to your VPN CONNECTION, unless it is connected to a whitelisted wifi. Remember to make it executable. It is a script.

This article is my 6th oldest. It is 171 words long