about summary refs log tree commit diff
path: root/modules/nm-mullvad/default.nix
blob: d948f12a530b67c45f6551dedbca8169f5b54f31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
{ config, pkgs, lib, ... }:

# WARN(DEPRECATED): This module is deprecated and is superseded by tailscale.

let
  cfg = config.networking.networkmanager.nm-mullvad;

  template = { id, uuid, pubKey, endpoint }:
    ''
      [connection]
      id=${id}
      uuid=${uuid}
      type=wireguard
      ${lib.optionalString (!cfg.autoConnect.enable || cfg.autoConnect.profile != id) "autoconnect=false"}
      interface-name=${id}

      [wireguard]
      ${lib.optionalString (cfg.listenPort != null) "listen-port=${toString cfg.listenPort}"}
      private-key=${if cfg.privateKey != null then cfg.privateKey else "@PRIVKEY@"}

      [wireguard-peer.${pubKey}]
      endpoint=${endpoint}:51820
      allowed-ips=0.0.0.0/0;::/0;

      [ipv4]
      address1=${if cfg.ipv4Address != null then cfg.ipv4Address else "@IPV4ADDRESS@"}
      dns=10.64.0.1
      dns-search=~;
      method=manual

      [ipv6]
      addr-gen-mode=default
      address1=${if cfg.ipv6Address != null then cfg.ipv6Address else "@IPV6ADDRESS@"}
      method=manual

      [proxy]
    '';

  serversList = import ./mullvad-servers-list.nix;

  allServerIds = builtins.map (x: x.id) serversList;

  availableServersList = builtins.filter (x: lib.elem x.id cfg.availableServers) serversList;

  serverEntryToConnFilename = serverEntry:
    "NetworkManager/system-connections/${serverEntry.id}.nmconnection";

  serverEntryToConnFile = serverEntry:
    {
      "${serverEntryToConnFilename serverEntry}" = {
        text = template
          {
            inherit (serverEntry) id uuid pubKey endpoint;
          };
        mode = "0600";
      };
    };

  connFiles = lib.fold (x: acc: lib.recursiveUpdate (serverEntryToConnFile x) acc) { } availableServersList;

in
{
  options.networking.networkmanager.nm-mullvad = {
    enable = lib.mkEnableOption "Mullvad VPN profile for NetworkManager";

    listenPort = lib.mkOption {
      type = lib.types.nullOr lib.types.number;
      default = null;

      description = ''
        Set the port to listen on. Useful if you have a firewall active.
      '';
    };

    openFirewall = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Whether to open firewall for given `listenPort`.
      '';
    };

    autoConnect = {
      enable = lib.mkEnableOption "autoconnect for `autoConnect.profile`";

      profile = lib.mkOption {
        type = lib.types.nullOr lib.types.str;
        default = null;
        description = ''
          ID of the profile to autoconnect to.
        '';
      };
    };

    privateKey = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        WireGuard private key to use for authenticating with Mullvad.
      '';
    };

    privateKeyPath = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        Path for the file containing WireGuard private key to use for
        authenticating with Mullvad.
      '';
    };

    ipv4Address = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        IPv4 address to assign to the WireGuard interface.
        This should include the CIDR notation, e.g.) `10.64.0.1/32`
      '';
    };

    ipv4AddressPath = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        Path for the file containing the IPv4 address to assign to the
        WireGuard interface.
        This should include the CIDR notation, e.g.) `10.64.0.1/32`
      '';
    };

    ipv6Address = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        IPv6 address to assign to the wireguard interface.
        This should include the CIDR notation, e.g.) `fc00:bbbb:bbbb:bb01::1/128`
      '';
    };

    ipv6AddressPath = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = ''
        Path for the file containing the IPv6 address to assign to the
        WireGuard interface.
        This should include the CIDR notation, e.g.) `fc00:bbbb:bbbb:bb01::1/128`
      '';
    };

    availableServers = lib.mkOption
      {
        type = lib.types.listOf lib.types.str;
        default = allServerIds;
        description = ''
          List of servers that will be made available.
          Defaults to all servers, which might introduce clutter.
        '';
      };
  };

  config = lib.mkIf cfg.enable {
    assertions = [
      {
        assertion = cfg.openFirewall == true -> cfg.listenPort != null;
        message = ''
          A custom `listenPort` must be given when `openFirewall` is set.
        '';
      }
      {
        assertion = cfg.autoConnect.enable == true -> cfg.autoConnect.profile != null;
        message = ''
          Profile to use for autoconnect must be set when enabling autoconnect.
        '';
      }
      {
        assertion = cfg.privateKey != null || cfg.privateKeyPath != null;
        message = ''
          Either `privateKey` or `privateKeyPath` must be set.
        '';
      }
      {
        assertion = cfg.ipv4Address != null || cfg.ipv4AddressPath != null;
        message = ''
          Either `ipv4Address` or `ipv4AddressPath` must be set.
        '';
      }
      {
        assertion = cfg.ipv6Address != null || cfg.ipv6AddressPath != null;
        message = ''
          Either `ipv6Address` or `ipv6AddressPath` must be set.
        '';
      }
    ];

    environment.etc = connFiles;

    system.activationScripts.nm-mullvad-substitutePrivateKey = lib.mkIf (cfg.privateKeyPath != null) (lib.stringAfter [ "etc" "specialfs" "var" ]
        ''
        if [ -f "${cfg.privateKeyPath}" ]; then
          ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<6>loading networking.networkmanager.nm-mullvad.privateKeyPath from ${cfg.privateKeyPath}"
          ${lib.concatMapStringsSep "\n"
            (f: "${pkgs.gnused}/bin/sed -ie \"s_@PRIVKEY@_$(< ${cfg.privateKeyPath})_\" ${f}")
            (builtins.map (s: "/etc/${serverEntryToConnFilename s}") availableServersList)}
        else
            warning_msg="WARNING: networking.networkmanager.nm-mullvad.privateKeyPath (${cfg.privateKeyPath}) does not exist."
            echo "$warning_msg"
            ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<4>$warning_msg"
        fi
      '');

    system.activationScripts.nm-mullvad-substituteIpv4Address = lib.mkIf (cfg.ipv4AddressPath != null) (lib.stringAfter [ "etc" "specialfs" "var" ]
        ''
        if [ -f "${cfg.ipv4AddressPath}" ]; then
          ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<6>loading networking.networkmanager.nm-mullvad.ipv4AddressPath from ${cfg.ipv4AddressPath}"
          ${lib.concatMapStringsSep "\n"
            (f: "${pkgs.gnused}/bin/sed -ie \"s!@IPV4ADDRESS@!$(< ${cfg.ipv4AddressPath})!\" ${f}")
            (builtins.map (s: "/etc/${serverEntryToConnFilename s}") availableServersList)}
        else
            warning_msg="WARNING: networking.networkmanager.nm-mullvad.ipv4AddressPath (${cfg.ipv4AddressPath}) does not exist."
            echo "$warning_msg"
            ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<4>$warning_msg"
        fi
      '');

    system.activationScripts.nm-mullvad-substituteIpv6Address = lib.mkIf (cfg.ipv6AddressPath != null) (lib.stringAfter [ "etc" "specialfs" "var" ]
        ''
        if [ -f "${cfg.ipv6AddressPath}" ]; then
          ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<6>loading networking.networkmanager.nm-mullvad.ipv6AddressPath from ${cfg.ipv6AddressPath}"
          ${lib.concatMapStringsSep "\n"
            (f: "${pkgs.gnused}/bin/sed -ie \"s!@IPV6ADDRESS@!$(< ${cfg.ipv6AddressPath})!\" ${f}")
            (builtins.map (s: "/etc/${serverEntryToConnFilename s}") availableServersList)}
        else
            warning_msg="WARNING: networking.networkmanager.nm-mullvad.ipv6AddressPath (${cfg.ipv6AddressPath}) does not exist."
            echo "$warning_msg"
            ${pkgs.systemd}/bin/systemd-cat -t nixos echo "<4>$warning_msg"
        fi
      '');

    networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall [ cfg.listenPort ];
    networking.firewall.logReversePathDrops = lib.mkIf cfg.openFirewall true;
    networking.firewall.extraCommands = lib.mkIf cfg.openFirewall ''
     ip46tables -t mangle -I nixos-fw-rpfilter -p udp -m udp --sport ${toString cfg.listenPort} -j RETURN
     ip46tables -t mangle -I nixos-fw-rpfilter -p udp -m udp --dport ${toString cfg.listenPort} -j RETURN
    '';
    networking.firewall.extraStopCommands = lib.mkIf cfg.openFirewall ''
     ip46tables -t mangle -D nixos-fw-rpfilter -p udp -m udp --sport ${toString cfg.listenPort} -j RETURN || true
     ip46tables -t mangle -D nixos-fw-rpfilter -p udp -m udp --dport ${toString cfg.listenPort} -j RETURN || true
    '';
  };
}