about summary refs log tree commit diff
path: root/lib/private-wireguard.nix
blob: 5369c3f930eda98e2488afa3074fe242f26833c1 (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
{ lib, hostname, config, ... }:

let
  inherit (lib) mkEnableOption mkOption mkIf types;
  inherit (builtins) readFile fromTOML fromJSON;

  cfg = config.networking.private-wireguard;
  port = 51871;
  wgcfg = fromTOML (readFile ./../configs/wireguard.toml);
  allPeers = wgcfg.peers;
  thisPeer = allPeers."${hostname}" or null;
  otherPeers = lib.filterAttrs (n: v: n != hostname) allPeers;
in {
  options.networking.private-wireguard = {
    enable = mkEnableOption "Enable private wireguard vpn connection";
  };

  config = lib.mkIf cfg.enable {
    age.secrets.wg-privkey = {
      file = ../secrets/network/${config.networking.hostName}/wireguard_privatekey.age;
      mode = "0440";
      owner = "0";
    };

    networking = {
      wireguard.interfaces.wg0 = {
        listenPort = port;
        privateKeyFile = "/run/agenix/wg-privkey";
        ips = [
          "${wgcfg.subnet4}.${toString thisPeer.ipv4}/${toString wgcfg.mask4}"
        ];

        peers = lib.mapAttrsToList
          (name: peer: {
            allowedIPs = [
              "${wgcfg.subnet4}.${toString peer.ipv4}/${toString wgcfg.mask4}"
            ];
            publicKey = peer.key;
          } // lib.optionalAttrs (peer ? externalIp) {
            endpoint = "${peer.externalIp}:${toString port}";
          } // lib.optionalAttrs (!(thisPeer ? externalIp)) {
            persistentKeepalive = 10;
          })
          otherPeers;
      };
    };
  };
}