diff options
Diffstat (limited to 'lib')
-rw-r--r-- | lib/default.nix | 1 | ||||
-rw-r--r-- | lib/private-wireguard.nix | 44 |
2 files changed, 45 insertions, 0 deletions
diff --git a/lib/default.nix b/lib/default.nix index c2866c9..fe43eb1 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -14,6 +14,7 @@ inputs.agenix.nixosModules.age ../hosts/common ../hosts/${hostname} + ./private-wireguard.nix { networking.hostName = hostname; nixpkgs = { diff --git a/lib/private-wireguard.nix b/lib/private-wireguard.nix new file mode 100644 index 0000000..e063f39 --- /dev/null +++ b/lib/private-wireguard.nix @@ -0,0 +1,44 @@ +{ 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 { + networking = let + age.secrets.wg-net.file = ../secrets/network/hostname/wireguard_privatekey.age; + in { + wireguard.interfaces.wg0 = { + listenPort = port; + privateKeyFile = "/run/agenix/wireguard_privatekey"; + 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; + }; + }; + }; +} |