summaryrefslogtreecommitdiff
path: root/modules/services/wg-quick.nix
blob: 1e0b86519b8997eeec89fc0164a6b32e94af38b2 (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
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.networking.wg-quick;

  peerOpts = { ... }: {
    options = {
      allowedIPs = mkOption {
        type = types.listOf types.str;
        default = [ ];
        description = lib.mdDoc "List of IP addresses associated with this peer.";
      };

      endpoint = mkOption {
        type = types.nullOr types.str;
        default = null;
        description = lib.mdDoc "IP and port to connect to this peer at.";
      };

      persistentKeepalive = mkOption {
        type = types.nullOr types.int;
        default = null;
        description = lib.mdDoc "Interval in seconds to send keepalive packets";
      };

      presharedKeyFile = mkOption {
        type = types.nullOr types.str;
        default = null;
        description =
          lib.mdDoc "Optional, path to file containing the pre-shared key for this peer.";
      };

      publicKey = mkOption {
        default = null;
        type = types.str;
        description = lib.mdDoc "The public key for this peer.";
      };
    };
  };

  interfaceOpts = { ... }: {
    options = {
      address = mkOption {
        type = types.nullOr (types.listOf types.str);
        default = [ ];
        description = lib.mdDoc "List of IP addresses for this interface.";
      };

      autostart = mkOption {
        type = types.bool;
        default = true;
        description =
          lib.mdDoc "Whether to bring up this interface automatically during boot.";
      };

      dns = mkOption {
        type = types.listOf types.str;
        default = [ ];
        description = lib.mdDoc "List of DNS servers for this interface.";
      };

      listenPort = mkOption {
        type = types.nullOr types.int;
        default = null;
        description = lib.mdDoc "Port to listen on, randomly selected if not specified.";
      };

      mtu = mkOption {
        type = types.nullOr types.int;
        default = null;
        description =
          lib.mdDoc "MTU to set for this interface, automatically set if not specified";
      };

      peers = mkOption {
        type = types.listOf (types.submodule peerOpts);
        default = [ ];
        description = lib.mdDoc "List of peers associated with this interface.";
      };

      preDown = mkOption {
        type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
        default = "";
        description = lib.mdDoc "List of commadns to run before interface shutdown.";
      };

      preUp = mkOption {
        type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
        default = "";
        description = lib.mdDoc "List of commands to run before interface setup.";
      };

      postDown = mkOption {
        type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
        default = "";
        description = lib.mdDoc "List of commands to run after interface shutdown";
      };

      postUp = mkOption {
        type = with types; coercedTo (listOf str) (concatStringsSep "\n") lines;
        default = "";
        description = lib.mdDoc "List of commands to run after interface setup.";
      };

      privateKeyFile = mkOption {
        type = types.str;
        default = null;
        description = lib.mdDoc "Path to file containing this interface's private key.";
      };

      table = mkOption {
        type = types.nullOr types.str;
        default = null;
        description = lib.mdDoc ''
          Controls the routing table to which routes are added. There are two
          special values: `off` disables the creation of routes altogether,
          and `auto` (the default) adds routes to the default table and
          enables special handling of default routes.
        '';
      };
    };
  };

  generateInterfaceScript = name: text:
    ((pkgs.writeShellScriptBin name text) + "/bin/${name}");

  generatePostUpPSKText = name: interfaceOpt:
    map (peer:
      optionalString (peer.presharedKeyFile != null) ''
        wg set $(cat /var/run/wireguard/${name}.name) peer ${peer.publicKey} preshared-key ${peer.presharedKeyFile}
      '') interfaceOpt.peers;

  generatePostUpText = name: interfaceOpt:
    (optionalString (interfaceOpt.privateKeyFile != null) ''
      wg set $(cat /var/run/wireguard/${name}.name) private-key ${interfaceOpt.privateKeyFile}
    '') + (concatStrings (generatePostUpPSKText name interfaceOpt))
    + interfaceOpt.postUp;

  generateInterfacePostUp = name: interfaceOpt:
    generateInterfaceScript "postUp.sh" (generatePostUpText name interfaceOpt);

  generateInterfaceConfig = name: interfaceOpt:
    ''
      [Interface]
    '' + optionalString (interfaceOpt.address != [ ]) (''
      Address = ${concatStringsSep "," interfaceOpt.address}
    '') + optionalString (interfaceOpt.dns != [ ]) ''
      DNS = ${concatStringsSep "," interfaceOpt.dns}
    '' + optionalString (interfaceOpt.listenPort != null) ''
      ListenPort = ${toString interfaceOpt.listenPort}
    '' + optionalString (interfaceOpt.mtu != null) ''
      MTU = ${toString interfaceOpt.mtu}
    '' + optionalString (interfaceOpt.preUp != "") ''
      PreUp = ${generateInterfaceScript "preUp.sh" interfaceOpt.preUp}
    '' + optionalString (interfaceOpt.preDown != "") ''
      PreDown = ${generateInterfaceScript "preDown.sh" interfaceOpt.preDown}
    '' + optionalString
    (interfaceOpt.privateKeyFile != null || interfaceOpt.postUp != "") ''
      PostUp = ${generateInterfacePostUp name interfaceOpt}
    '' + optionalString (interfaceOpt.postDown != "") ''
      PostDown = ${generateInterfaceScript "postDown.sh" interfaceOpt.postDown}
    '' + optionalString (interfaceOpt.table != null) ''
      Table = ${interfaceOpt.table}
    '' + optionalString (interfaceOpt.peers != [ ]) "\n"
    + concatStringsSep "\n" (map generatePeerConfig interfaceOpt.peers);

  generatePeerConfig = peerOpt:
    ''
      [Peer]
      PublicKey = ${peerOpt.publicKey}
    '' + optionalString (peerOpt.allowedIPs != [ ]) ''
      AllowedIPs = ${concatStringsSep "," peerOpt.allowedIPs}
    '' + optionalString (peerOpt.endpoint != null) ''
      Endpoint = ${peerOpt.endpoint}
    '' + optionalString (peerOpt.persistentKeepalive != null) ''
      PersistentKeepalive = ${toString peerOpt.persistentKeepalive}
    '';

  generateInterfaceAttrs = name: interfaceOpt:
    nameValuePair "wireguard/${name}.conf" {
      enable = true;
      text = generateInterfaceConfig name interfaceOpt;
    };

  generateLaunchDaemonAttrs = name: interfaceOpt:
    nameValuePair "wg-quick-${name}" {
      serviceConfig = {
        EnvironmentVariables = {
          PATH =
            "${pkgs.wireguard-tools}/bin:${pkgs.wireguard-go}/bin:${config.environment.systemPath}";
        };
        KeepAlive = {
          NetworkState = true;
          SuccessfulExit = true;
        };
        ProgramArguments =
          [ "${pkgs.wireguard-tools}/bin/wg-quick" "up" "${name}" ];
        RunAtLoad = true;
        StandardErrorPath = "${cfg.logDir}/wg-quick-${name}.log";
        StandardOutPath = "${cfg.logDir}/wg-quick-${name}.log";
      };
    };
in {
  options = {
    networking.wg-quick = {
      interfaces = mkOption {
        type = types.attrsOf (types.submodule interfaceOpts);
        default = { };
        description = lib.mdDoc "Set of wg-quick interfaces.";
      };

      logDir = mkOption {
        type = types.str;
        default = "/var/log";
        description = lib.mdDoc "Directory to save wg-quick logs to.";
      };
    };
  };

  config = mkIf (cfg.interfaces != { }) {
    launchd.daemons = mapAttrs' generateLaunchDaemonAttrs
      (filterAttrs (name: interfaceOpt: interfaceOpt.autostart)
        config.networking.wg-quick.interfaces);

    environment.etc =
      mapAttrs' generateInterfaceAttrs config.networking.wg-quick.interfaces;

    environment.systemPackages = [ pkgs.wireguard-go pkgs.wireguard-tools ];
  };
}