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.

Requirements: - You are using Network Manager - You already have a VPN configured (and both the VPN and the saved password if any is saved for/shared with all users on the system) - You forget to activate it yourself and want to automatically connect on certain networks

Solution: Add this file to /etc/NetworkManager/dispatcher.d (Debian location, name might be slightly different on other systems):

#!/bin/sh
WHITELIST_NETWORKS="myhomenetwork|workwifi|anotherworkwifithatItrust"
VPN_CONNECTION="nameofyourVPN"
case "$2" in
    up|connectivity-change)
        # First test if we're on a bad network
        if nmcli connection show --active | grep -v -E "${WHITELIST_NETWORKS}" | grep -q wifi
        then
            # Then check if the VPN is already active or not
            if ! nmcli connection show --active | grep "${VPN_CONNECTION}" | grep -q -E "vpn|wireguard"
            then
                        # Then check if the connection is fully up (captive portal check)
                        if [ "${CONNECTIVITY_STATE-FULL}" = "FULL" ] ; then
                                    logger "$0: Starting VPN. called $1 with action \`$2'" 1>&2
                                    sleep 5
                                    nmcli con up "${VPN_CONNECTION}"
                                    sleep 2
                        fi
            fi
        fi
        ;;
    *)
        logger "$0: doing nothing. called $1 with action \`$2'" 1>&2
        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.

Tags: