Automatize VPN connection for a set of predefined SSIDs

Posted on April 8, 2024

It is often a good security practice to automize the process to connect to a VPN and encrypt your traffic at least to your local network provider.

Following is my Nix expression to have a file ~/.insecure_wifi_list, which is a \n separated list of insecure SSIDs. Then the NetworkManager Dispatcher script will connect to the vpn when you use a network and the SSID is in the list.

  networking = {
  networkmanager = {
    enable = true;
    dispatcherScripts = [
      {
        type = "pre-up";
        source = pkgs.writeText "preUpHook" ''
          SSID=$(/run/current-system/sw/bin/iwgetid -r)

          while read line; do
              if [ "$SSID" == "$line" ]; then
                  /run/current-system/sw/bin/mullvad connect
                  break
              fi
          done < /home/<user>/.insecure_wifi_list
        '';
      }

      {
        source = pkgs.writeText "downHook" ''
          INTERFACE=$1
          ACTION=$2

          SSID=$(/run/current-system/sw/bin/iwgetid -r)

          if [ "$ACTION" == "down" ]; then
              while read line; do
                  if [ "$SSID" == "$line" ]; then
                      /run/current-system/sw/bin/mullvad disconnect
                      break
                  fi
              done < /home/<user>/.insecure_wifi_list
          fi
        '';
      }

    ];
  };
};