summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/networking/wireguard-networkd.nix
blob: 7afcba2329890cc0aa7cb334a5b24b99516f61a0 (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
{
  config,
  lib,
  pkgs,
  ...
}:

let
  inherit (lib) types;
  inherit (lib.attrsets)
    filterAttrs
    mapAttrs'
    mapAttrsToList
    nameValuePair
    ;
  inherit (lib.lists)
    concatMap
    concatLists
    filter
    flatten
    ;
  inherit (lib.modules) mkIf;
  inherit (lib.options) literalExpression mkOption;
  inherit (lib.strings) hasInfix replaceStrings;
  inherit (lib.trivial) flip pipe;

  removeNulls = filterAttrs (_: v: v != null);

  escapeCredentialName = input: replaceStrings [ "\\" ] [ "_" ] input;

  fwMarkFromHexOrNum =
    fwMark:
    if (lib.hasPrefix "0x" fwMark) then lib.fromHexString fwMark else (fromTOML "v=${fwMark}").v;

  privateKeyCredential = interfaceName: escapeCredentialName "wireguard-${interfaceName}-private-key";
  presharedKeyCredential =
    interfaceName: peer: escapeCredentialName "wireguard-${interfaceName}-${peer.name}-preshared-key";

  interfaceCredentials =
    interfaceName: interface:
    [ "${privateKeyCredential interfaceName}:${interface.privateKeyFile}" ]
    ++ pipe interface.peers [
      (filter (peer: peer.presharedKeyFile != null))
      (map (peer: "${presharedKeyCredential interfaceName peer}:${peer.presharedKeyFile}"))
    ];

  generateNetdev =
    name: interface:
    nameValuePair "40-${name}" {
      netdevConfig = removeNulls {
        Kind = "wireguard";
        Name = name;
        MTUBytes = interface.mtu;
      };
      wireguardConfig = removeNulls {
        PrivateKey = "@${privateKeyCredential name}";
        ListenPort = interface.listenPort;
        FirewallMark = if interface.fwMark == null then null else (fwMarkFromHexOrNum interface.fwMark);
        RouteTable = if interface.allowedIPsAsRoutes then interface.table else null;
        RouteMetric = interface.metric;
      };
      wireguardPeers = map (generateWireguardPeer name) interface.peers;
    };

  generateWireguardPeer =
    interfaceName: peer:
    removeNulls {
      PublicKey = peer.publicKey;
      PresharedKey =
        if peer.presharedKeyFile == null then null else "@${presharedKeyCredential interfaceName peer}";
      AllowedIPs = peer.allowedIPs;
      Endpoint = peer.endpoint;
      PersistentKeepalive = peer.persistentKeepalive;
    };

  generateNetwork =
    name: interface:
    nameValuePair "40-${name}" {
      matchConfig.Name = name;
      address = interface.ips;
    };

  cfg = config.networking.wireguard;

  refreshEnabledInterfaces = filterAttrs (
    name: interface: interface.dynamicEndpointRefreshSeconds != 0
  ) cfg.interfaces;

  generateRefreshTimer =
    name: interface:
    nameValuePair "wireguard-dynamic-refresh-${name}" {
      partOf = [ "wireguard-dynamic-refresh-${name}.service" ];
      wantedBy = [ "timers.target" ];
      description = "Wireguard dynamic endpoint refresh (${name}) timer";
      timerConfig.OnBootSec = interface.dynamicEndpointRefreshSeconds;
      timerConfig.OnUnitInactiveSec = interface.dynamicEndpointRefreshSeconds;
    };

  generateRefreshService =
    name: interface:
    nameValuePair "wireguard-dynamic-refresh-${name}" {
      description = "Wireguard dynamic endpoint refresh (${name})";
      after = [ "network-online.target" ];
      wants = [ "network-online.target" ];
      path = with pkgs; [
        iproute2
        systemd
      ];
      # networkd doesn't automatically refresh peer endpoints.
      # See: https://github.com/systemd/systemd/issues/9911
      script = ''
        touch /etc/systemd/network/40-${name}.netdev
        networkctl reload
      '';
    };

  # netdev config must be a real file (not a symlink to a store file)
  # so the refresh service can 'touch' it.
  generateRefreshNetdevMode =
    name: interface:
    nameValuePair "systemd/network/40-${name}.netdev" {
      mode = "0444";
    };

in
{
  meta.maintainers = [ lib.maintainers.majiir ];

  options.networking.wireguard = {
    useNetworkd = mkOption {
      default = config.networking.useNetworkd;
      defaultText = literalExpression "config.networking.useNetworkd";
      type = types.bool;
      description = ''
        Whether to use networkd as the network configuration backend for
        Wireguard instead of the legacy script-based system.

        ::: {.warning}
        Some options have slightly different behavior with the networkd and
        script-based backends. Check the documentation for each Wireguard
        option you use before enabling this option.
        :::
      '';
    };
  };

  config = mkIf (cfg.enable && cfg.useNetworkd) {

    # TODO: Some of these options may be possible to support in networkd.
    #
    # privateKey and presharedKey are trivial to support, but we deliberately
    # don't in order to discourage putting secrets in the /nix store.
    #
    # generatePrivateKeyFile can be supported if we can order a service before
    # networkd configures interfaces. There is also a systemd feature request
    # for key generation: https://github.com/systemd/systemd/issues/14282
    #
    # preSetup, postSetup, preShutdown and postShutdown may be possible, but
    # networkd is not likely to support script hooks like this directly. See:
    # https://github.com/systemd/systemd/issues/11629
    #
    # socketNamespace and interfaceNamespace can be implemented once networkd
    # supports setting a netdev's namespace. See:
    # https://github.com/systemd/systemd/issues/11103
    # https://github.com/systemd/systemd/pull/14915

    assertions = concatLists (
      flip mapAttrsToList cfg.interfaces (
        name: interface:
        [
          # Interface assertions
          {
            assertion = interface.privateKey == null;
            message = "networking.wireguard.interfaces.${name}.privateKey cannot be used with networkd. Use privateKeyFile instead.";
          }
          {
            assertion = !interface.generatePrivateKeyFile;
            message = "networking.wireguard.interfaces.${name}.generatePrivateKeyFile cannot be used with networkd.";
          }
          {
            assertion = interface.preSetup == "";
            message = "networking.wireguard.interfaces.${name}.preSetup cannot be used with networkd.";
          }
          {
            assertion = interface.postSetup == "";
            message = "networking.wireguard.interfaces.${name}.postSetup cannot be used with networkd.";
          }
          {
            assertion = interface.preShutdown == "";
            message = "networking.wireguard.interfaces.${name}.preShutdown cannot be used with networkd.";
          }
          {
            assertion = interface.postShutdown == "";
            message = "networking.wireguard.interfaces.${name}.postShutdown cannot be used with networkd.";
          }
          {
            assertion = interface.socketNamespace == null;
            message = "networking.wireguard.interfaces.${name}.socketNamespace cannot be used with networkd.";
          }
          {
            assertion = interface.interfaceNamespace == null;
            message = "networking.wireguard.interfaces.${name}.interfaceNamespace cannot be used with networkd.";
          }
          {
            assertion = interface.type == "wireguard";
            message = "networking.wireguard.interfaces.${name}.type value must be \"wireguard\" when used with networkd.";
          }
        ]
        ++ flip concatMap interface.ips (ip: [
          # IP assertions
          {
            assertion = hasInfix "/" ip;
            message = "networking.wireguard.interfaces.${name}.ips value \"${ip}\" requires a subnet (e.g. 192.0.2.1/32) with networkd.";
          }
        ])
        ++ flip concatMap interface.peers (peer: [
          # Peer assertions
          {
            assertion = peer.presharedKey == null;
            message = "networking.wireguard.interfaces.${name}.peers[].presharedKey cannot be used with networkd. Use presharedKeyFile instead.";
          }
          {
            assertion = peer.dynamicEndpointRefreshSeconds == null;
            message = "networking.wireguard.interfaces.${name}.peers[].dynamicEndpointRefreshSeconds cannot be used with networkd. Use networking.wireguard.interfaces.${name}.dynamicEndpointRefreshSeconds instead.";
          }
          {
            assertion = peer.dynamicEndpointRefreshRestartSeconds == null;
            message = "networking.wireguard.interfaces.${name}.peers[].dynamicEndpointRefreshRestartSeconds cannot be used with networkd.";
          }
        ])
      )
    );

    systemd.network = {
      enable = true;
      netdevs = mapAttrs' generateNetdev cfg.interfaces;
      networks = mapAttrs' generateNetwork cfg.interfaces;
    };

    environment.etc = mapAttrs' generateRefreshNetdevMode refreshEnabledInterfaces;
    systemd.timers = mapAttrs' generateRefreshTimer refreshEnabledInterfaces;
    systemd.services = (mapAttrs' generateRefreshService refreshEnabledInterfaces) // {
      systemd-networkd.serviceConfig.LoadCredential = flatten (
        mapAttrsToList interfaceCredentials cfg.interfaces
      );
    };
  };
}