aboutsummaryrefslogtreecommitdiff
path: root/modules/wireguard/default.nix
blob: c9fc063908fe4a59744db8edc9b607d9d39fd5ef (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
{ config, lib, pkgs, nodes, builtins, ... }:

with lib; {
  imports = [ ./options.nix ./roaming.nix ];

  config = mkIf config.wireguard.enable (let
    cfg = config.wireguard;

    peers = let
      attrPeers = mapAttrs (n: node:
        let peer = node.config.wireguard;
        in {
          endpoint =
            "${node.config.deployment.targetHost}:${toString peer.port}";
          publicKey = peer.publicKey;
          persistentKeepalive = 25;
          allowedIPs = [
            "${peer.v4.address}/32"
            "${peer.v6.ula}::${peer.v6.address}/128"
            "${peer.v6.gua}::${peer.v6.address}/128"
          ] ++ peer.allowedIPs;
        }) (filterAttrs (n: node: node.config.wireguard.enable) nodes);
      peers = attrValues attrPeers;
    in peers;
  in {
    secrets = mkIf config.wireguard.enable {
      wireguard = {
        source = ../../secrets
          + ("/" + "${config.networking.hostName}.privkey");
        dest = "/root/wireguard/privkey";
      };
    };

    networking.wireguard.interfaces = mkIf config.wireguard.enable {
      wg0 = with { ifname = "wg0"; }; {
        ips = [
          "${cfg.v4.address}/${toString cfg.v4.prefixLength}"
          "${cfg.v6.ula}::${cfg.v6.address}/128"
          "${cfg.v6.gua}::${cfg.v6.address}/128"
        ];
        listenPort = cfg.port;
        postSetup = ''
          ${pkgs.nftables}/bin/nft add table ${ifname}
          ${pkgs.nftables}/bin/nft 'add chain ${ifname} prerouting { type nat hook prerouting priority 0 ; }'
          ${pkgs.nftables}/bin/nft 'add chain ${ifname} postrouting { type nat hook postrouting priority 100 ; }'
          ${pkgs.nftables}/bin/nft add rule ${ifname} postrouting ip saddr ${cfg.v4.network}/${
            toString cfg.v4.prefixLength
          } oif ${cfg.natInterface} masquerade

          ${pkgs.iproute2}/bin/ip link set ${ifname} multicast on
        '';
        postShutdown = ''
          ${pkgs.nftables}/bin/nft flush table ${ifname}
          ${pkgs.nftables}/bin/nft delete table ${ifname}
        '';
        privateKeyFile = "/root/wireguard/privkey";
        peers = peers;
      };
    };

    boot.kernel.sysctl = {
      "net.ipv4.ip_forward" = lib.mkDefault true;
      "net.ipv6.conf.all.forwarding" = true;
      "net.netfilter.nf_conntrack_tcp_be_liberal" = true;
    };
  });
}