summaryrefslogtreecommitdiff
path: root/modules/yggdrasil-wg/default.nix
blob: 48672fcbd495389f87ebe9cf25c0da3205f7c829 (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
{ config, hostName, lib, pkgs, ... }:

with lib;

let
  listenPort = 51820;
  udp2rawPort = 51821;
  wgSubnet = "2a03:4000:52:ada:1";
  wgSubnetLength = 80;
  wgHostLength = wgSubnetLength + 16;
  batSubnet = "2a03:4000:52:ada:2";
  batSubnetLength = 80;
  batHostLength = batSubnetLength + 16;

  links = mkLinks [
    { from = "vidhar";
      to = "surtr";
      endpointHost = "202.61.241.61";
      udp2raw = true;
      PersistentKeepalive = 25;
    }
    { from = "sif";
      to = "surtr";
      endpointHost = "202.61.241.61";
      udp2raw = true;
      PersistentKeepalive = 25;
    }
    { from = "sif";
      to = "vidhar";
      endpointHost = "192.168.2.168";
      PersistentKeepalive = 25;
    }
  ];
  wgHostIPs = {
    surtr = "${wgSubnet}::/${toString wgHostLength}";
    vidhar = "${wgSubnet}:1::/${toString wgHostLength}";
    sif = "${wgSubnet}:2::/${toString wgHostLength}";
  };
  greHostMACPrefixes = {
    surtr = "02:00:01:00:00";
    vidhar = "02:00:01:00:01";
    sif = "02:00:01:00:02";
  };
  batHostMACs = {
    surtr = "02:00:00:00:00:00";
    vidhar = "02:00:00:01:00:00";
    sif = "02:00:00:02:00:00";
  };
  batHostIPs = {
    surtr = ["${batSubnet}::/${toString batHostLength}"];
    vidhar = ["${batSubnet}:1::/${toString batHostLength}"];
    sif = ["${batSubnet}:2::/${toString batHostLength}"];
  };

  mkPublicKeyPath = host: ./hosts + "/${host}.pub";
  mkPrivateKeyPath = host: ./hosts + "/${host}.priv";

  kernel = config.boot.kernelPackages;
  
  publicKeyPath = mkPublicKeyPath hostName;
  privateKeyPath = mkPrivateKeyPath hostName;
  inNetwork = pathExists privateKeyPath && pathExists publicKeyPath;
  hostLinks = filter ({ from, to, ... }: from == hostName || to == hostName) links;
  linkToPeer = opts@{from, to, ...}:
    let
      other = if from == hostName then to else from;
    in {
      AllowedIPs = wgHostIPs.${other};
      PublicKey = trim (readFile (mkPublicKeyPath other));
    } // (optionalAttrs (from == hostName) (filterAttrs (n: _v: !(elem n ["from" "to" "endpointHost" "udp2raw"])) opts // optionalAttrs (opts ? "endpointHost" && from == hostName) (if opts ? "udp2raw" then { Endpoint = "127.0.0.1:${toString (udp2rawPort + opts.udp2raw)}"; } else { Endpoint = "${opts.endpointHost}:${toString listenPort}"; })));
  linkToGreDev = opts@{from, to, ...}:
    let
      other = if from == hostName then to else from;
    in nameValuePair "yggre-${other}" {
      netdevConfig = {
        Name = "yggre-${other}";
        Kind = "ip6gretap";
      };
      tunnelConfig = {
        Local = stripSubnet wgHostIPs.${hostName};
        Remote = stripSubnet wgHostIPs.${other};
      };
    };
  linkToGreNetwork = ix: opts@{from, to, ...}:
    let
      other = if from == hostName then to else from;
    in nameValuePair "yggre-${other}" {
      matchConfig = {
        Name = "yggre-${other}";
      };
      linkConfig = {
        MACAddress = "${greHostMACPrefixes.${hostName}}:${toHexByte ix}";
        RequiredForOnline = false;
      };
      networkConfig = {
        BatmanAdvanced = "yggdrasil";
        LinkLocalAddressing = "no";
      };
    };
  
  trim = str: if hasSuffix "\n" str then trim (removeSuffix "\n" str) else str;
  stripSubnet = addr: let matchRes = builtins.match "^(.*)/[0-9]+$" addr; in if matchRes == null then addr else elemAt matchRes 0;
  optIx = optName: xs: let
    withOpts = listToAttrs (imap0 (ix: x: nameValuePair x.name (x.value // { ${optName} = ix; })) (filter (x: x.value.${optName} or false) (imap0 (ix: nameValuePair (toString ix)) xs)));
    withoutOpts = listToAttrs (map (nv: nameValuePair nv.name (removeAttrs nv.value [optName])) (filter (x: !(x.value.${optName} or false)) (imap0 (ix: nameValuePair (toString ix)) xs)));
  in genList (ix: withOpts.${toString ix} or withoutOpts.${toString ix}) (length xs);
  mkLinks = optIx "udp2raw";
  toHexByte = n: let
    hex = toHexString n;
  in if (stringLength hex < 2) then "0${hex}" else hex;
in {
  config = {
    assertions = [
      { assertion = inNetwork || !(pathExists privateKeyPath || pathExists publicKeyPath);
        message = "yggdrasil-wg: Either both public and private keys must exist or neither.";
      }
      { assertion = !inNetwork || (wgHostIPs ? "${hostName}");
        message = "yggdrasil-wg: Entry in wgHostIPs must exist.";
      }
    ] ++ map ({from, to, ...}: let other = if from == hostName then to else from; in { assertion = pathExists (mkPublicKeyPath other); message = "yggdrasil-wg: This host (${hostName}) has a link with ‘${other}’, but no public key is available for ‘${other}’."; }) hostLinks;

    systemd.network = mkIf inNetwork {
      enable = true;
      netdevs = {
        yggdrasil-wg = {
          netdevConfig = {
            Name = "yggdrasil-wg";
            Kind = "wireguard";
          };
          wireguardConfig = {
            PrivateKeyFile = config.sops.secrets."yggdrasil-wg.priv".path;
            ListenPort = listenPort;
          };
          wireguardPeers = map (opts@{to, from, ...}: { wireguardPeerConfig = linkToPeer opts; }) hostLinks;
        };
        yggdrasil = {
          netdevConfig = {
            Name = "yggdrasil";
            Kind = "batadv";
          };
          linkConfig = {
            MACAddress = "${batHostMACs.${hostName}}";
          };
        };
      } // listToAttrs (map linkToGreDev hostLinks);

      networks = {
        yggdrasil-wg = {
          name = "yggdrasil-wg";
          matchConfig = {
            Name = "yggdrasil-wg";
          };
          address = [wgHostIPs.${hostName}];
          routes = [
            { routeConfig = {
                Destination = "${wgSubnet}::/${toString wgSubnetLength}";
              };
            }
          ];
          linkConfig = {
            RequiredForOnline = false;
          };
          networkConfig = {
            Tunnel = map (opts@{from, to, ...}: let other = if from == hostName then to else from; in "yggre-${other}") hostLinks;
          };
        };
        yggdrasil = {
          name = "yggdrasil";
          matchConfig = {
            Name = "yggdrasil";
          };
          address = batHostIPs.${hostName};
          routes = [
            { routeConfig = {
                Destination = "${batSubnet}::/${toString batSubnetLength}";
              };
            }
          ];
          linkConfig = {
            RequiredForOnline = false;
          };
        };
      } // listToAttrs (imap0 linkToGreNetwork hostLinks);
    };

    systemd.services = listToAttrs (filter ({ value, ...}: value != null) (map (opts@{to, from, ...}: let other = if from == hostName then to else from; in nameValuePair "yggdrasil-udp2raw@${other}" (if opts ? "endpointHost" && opts ? "udp2raw" then {
      path = with pkgs; [iptables];
      wantedBy = [ "network.target" ];
      serviceConfig = {
        RuntimeDirectory = ["udp2raw-config-${other}"];
        RuntimeDirectoryMode = "0700";
        ExecStartPre = pkgs.writeShellScript "udp2raw-mkconfig-${other}.sh" ''
          umask 0077
          secret=$(cat ${config.sops.secrets."yggdrasil-udp2raw-secret".path})
          cat >''${RUNTIME_DIRECTORY}/udp2raw.conf <<EOF
          ${if from == hostName then ''
            -c
            -l 127.0.0.1:${toString (udp2rawPort + opts.udp2raw)}
            -r ${opts.endpointHost}:${toString (udp2rawPort + opts.udp2raw)}
          '' else ''
            -s
            -l 0.0.0.0:${toString (udp2rawPort + opts.udp2raw)}
            -r 127.0.0.1:${toString listenPort}
          ''}
          -k $secret
          --auth-mode hmac_sha1
          --raw-mode faketcp
          --seq-mode 4
          -a
          --retry-on-error
          EOF
        '';
        ExecStart = "${pkgs.udp2raw}/bin/udp2raw --conf-file \${RUNTIME_DIRECTORY}/udp2raw.conf";
        Restart = "always";
      };
    } else null)) hostLinks));

    sops.secrets = {
      "yggdrasil-wg.priv" = mkIf (pathExists privateKeyPath) {
        format = "binary";
        sopsFile = privateKeyPath;
        mode = "0640";
        owner = "root";
        group = "systemd-network";
      };
      "yggdrasil-udp2raw-secret" = mkIf (any (opts@{to, from, ...}: opts ? "endpointHost" && opts ? "udp2raw") hostLinks) {
        format = "binary";
        sopsFile = ./udp2raw-secret;
      };
    };

    networking.hosts = mkIf inNetwork (listToAttrs (concatMap ({name, value}: map (ip: nameValuePair (stripSubnet ip) ["${name}.yggdrasil"]) value) (mapAttrsToList nameValuePair batHostIPs)));

    boot.extraModulePackages = optional (versionOlder kernel.kernel.version "5.6") kernel.wireguard ++ [kernel.batman_adv];
    environment.systemPackages = with pkgs; [ wireguard-tools batctl ];
  };
}