about summary refs log tree commit diff
path: root/modules/wireguard.nix
blob: 513894625246478b0cc35a3d78b610ffc1538b76 (plain) (blame)
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
{
  config,
  inputs,
  lib,
  pkgs,
  this,
  ...
}:
with lib;
let
  cfg = config.nixfiles.modules.wireguard;

  DNSSetup =
    let
      resolvectl = "${config.systemd.package}/bin/resolvectl";
    in
    ''
      ${resolvectl} dns ${cfg.interface} ${cfg.server.ipv6.address} ${cfg.server.ipv4.address}
      ${resolvectl} domain ${cfg.interface} local ${my.domain.shire}
      ${resolvectl} dnssec ${cfg.interface} no
      ${resolvectl} dnsovertls ${cfg.interface} no
    '';

  extraOptions = {
    jc = 228;
    jmin = 42;
    jmax = 420;
    s1 = 69;
    s2 = 96;
  };
in
{
  disabledModules = [
    "services/networking/wg-quick.nix"
    "services/networking/wireguard.nix"
  ];
  imports = [
    "${inputs.nixpkgs-amneziawg}/nixos/modules/services/networking/wg-quick.nix"
    "${inputs.nixpkgs-amneziawg}/nixos/modules/services/networking/wireguard.nix"
  ];

  options.nixfiles.modules.wireguard = {
    client = {
      enable = mkEnableOption "WireGuard client";

      enableTrafficRouting = mkOption {
        description = "Whether to enable traffic routing through the sever.";
        type = with types; bool;
        default = !this.isHeadless;
      };
    };

    server = {
      enable = mkEnableOption "WireGuard server";

      ipv4.address = mkOption {
        description = "IPv4 address to bind to.";
        type = with types; str;
        default = my.configurations.manwe.wireguard.ipv4.address;
      };

      ipv6.address = mkOption {
        description = "IPv4 address to bind to.";
        type = with types; str;
        default = my.configurations.manwe.wireguard.ipv6.address;
      };

      address = mkOption {
        description = "Endpoint address to use";
        type = with types; str;
        default = my.configurations.manwe.ipv4.address;
      };

      port = mkOption {
        description = "Endpoint port to use.";
        type = with types; int;
        default = 6969;
      };

      publicKey = mkOption {
        description = "Server's public key.";
        type = with types; str;
        default = my.configurations.manwe.wireguard.publicKey;
      };

      peers = mkOption {
        description = "List of peers.";
        type = with types; listOf attrs;
        default =
          mapAttrsToList
            (
              _: attr: with attr; {
                inherit (wireguard) publicKey;
                allowedIPs = with wireguard; [
                  "${ipv6.address}/128"
                  "${ipv4.address}/32"
                ];
              }
            )
            (
              filterAttrs (_: attr: attr.hostname != this.hostname && hasAttr "wireguard" attr) my.configurations
            );
      };
    };

    interface = mkOption {
      description = "Name of the interface to use WireGuard with.";
      type = with types; str;
      default = "wg69";
    };

    ipv4.subnet = mkOption {
      description = "CIDR notation for the IPv4 subnet to use over WireGuard.";
      type = with types; str;
      default = "10.69.0.0/16";
    };

    ipv6.subnet = mkOption {
      description = "CIDR notation for the IPv6 subnet to use over WireGuard.";
      type = with types; str;
      default = "fd69::/16";
    };
  };

  config =
    {
      assertions = [
        {
          assertion = config.security.sudo.enable;
          message = "Sudo is not enabled.";
        }
        {
          assertion = any (x: x == "wheel") config.my.extraGroups;
          message = ''User is not in the "wheel" group.'';
        }
      ];
    }
    // mkMerge [
      (mkIf (cfg.client.enable || cfg.server.enable) {
        secrets."wireguard-private-key-${this.hostname}".file = "${inputs.self}/secrets/wireguard-private-key-${this.hostname}";

        networking.firewall.trustedInterfaces = [ cfg.interface ];

        topology = with cfg; {
          nodes.${this.hostname}.interfaces.${interface} = {
            network = interface;
            icon = "interfaces.wireguard";
          };
        };
      })
      (mkIf cfg.client.enable {
        networking.wg-quick.interfaces.${cfg.interface} = mkMerge [
          (with this.wireguard; {
            type = "amneziawg";
            privateKeyFile = config.secrets."wireguard-private-key-${this.hostname}".path;
            address = [
              "${ipv4.address}/16"
              "${ipv6.address}/16"
            ];
            inherit extraOptions;
          })
          (with cfg.server; {
            peers = [
              {
                inherit publicKey;
                endpoint = "${address}:${toString port}";
                allowedIPs =
                  if cfg.client.enableTrafficRouting then
                    [
                      "::/0"
                      "0.0.0.0/0"
                    ]
                  else
                    [
                      cfg.ipv6.subnet
                      cfg.ipv4.subnet
                    ];
              }
            ];
            dns = [
              ipv6.address
              ipv4.address
            ];
            postUp = DNSSetup;
          })
        ];

        environment.systemPackages = with pkgs; [
          (writeShellApplication {
            name = "wg-toggle";
            runtimeInputs = [
              amneziawg-tools
              iproute2
              jq
            ];
            text = ''
              ip46() {
                sudo ip -4 "$@"
                sudo ip -6 "$@"
              }

              fwmark=$(sudo awg show ${cfg.interface} fwmark) || exit
              if ip -j rule list lookup "$fwmark" | jq -e 'length > 0' >/dev/null; then
                ip46 rule del lookup main suppress_prefixlength 0
                ip46 rule del lookup "$fwmark"
              else
                ip46 rule add not fwmark "$fwmark" lookup "$fwmark"
                ip46 rule add lookup main suppress_prefixlength 0
              fi
            '';
          })
        ];
      })
      (mkIf cfg.server.enable {
        networking = {
          wireguard = {
            enable = true;
            type = "amneziawg";
            interfaces.${cfg.interface} = with cfg.server; {
              privateKeyFile = config.secrets."wireguard-private-key-${this.hostname}".path;
              ips = [
                "${ipv6.address}/16"
                "${ipv4.address}/16"
              ];
              listenPort = port;
              inherit peers extraOptions;
              postSetup = DNSSetup;
              allowedIPsAsRoutes = false;
            };
          };

          nat = {
            enable = true;
            enableIPv6 = true;

            externalInterface = mkDefault "eth0";

            internalInterfaces = [ cfg.interface ];
            internalIPs = [ cfg.ipv4.subnet ];
            internalIPv6s = [ cfg.ipv6.subnet ];
          };

          firewall.allowedUDPPorts = [ cfg.server.port ];
        };

        services.prometheus.exporters.wireguard = {
          enable = false; # TODO Doesn't work with amneziawg-tools.
          listenAddress = mkDefault this.wireguard.ipv4.address;
          withRemoteIp = true;
          port = 9586;
        };

        topology = with cfg; {
          networks = {
            ${interface} = {
              name = interface;
              cidrv4 = ipv4.subnet;
              cidrv6 = ipv6.subnet;
              icon = "interfaces.wireguard";
            };
          };

          nodes.${this.hostname}.interfaces.${interface}.physicalConnections = mapAttrsToList (
            name: _: config.lib.topology.mkConnection name interface
          ) (filterAttrs (n: v: !v.isOther && n != this.hostname && hasAttr "wireguard" v) my.configurations);
        };
      })
    ];
}

Consider giving Nix/NixOS a try! <3