{ config, lib, ... }: let cfg = config.router; # systemd-networkd runs unprivileged and could not read root-only key files. # LoadCredential= makes systemd read them as root and hand networkd a copy # in its credentials directory, so the files can stay 0600 root. credDir = "/run/credentials/systemd-networkd.service"; keyCred = name: "wg-${name}-key"; pskCred = name: peer: "wg-${name}-${peer}-psk"; credentials = lib.concatLists ( lib.mapAttrsToList ( name: wg: [ "${keyCred name}:${toString wg.privateKeyFile}" ] ++ lib.concatLists ( lib.mapAttrsToList ( peer: p: lib.optional (p.presharedKeyFile != null) "${pskCred name peer}:${toString p.presharedKeyFile}" ) wg.peers ) ) cfg.wireguard ); in { config = lib.mkIf (cfg.enable && cfg.wireguard != { }) { systemd.network.netdevs = lib.mapAttrs' ( name: wg: lib.nameValuePair "30-wg-${name}" { netdevConfig = { Kind = "wireguard"; Name = wg.interface; } // lib.optionalAttrs (wg.mtu != null) { MTUBytes = wg.mtu; }; wireguardConfig = { PrivateKeyFile = "${credDir}/${keyCred name}"; } // lib.optionalAttrs (wg.listenPort != null) { ListenPort = wg.listenPort; }; wireguardPeers = lib.mapAttrsToList ( peer: p: { PublicKey = p.publicKey; AllowedIPs = p.allowedIPs; } // lib.optionalAttrs (p.endpoint != null) { Endpoint = p.endpoint; } // lib.optionalAttrs (p.persistentKeepalive != null) { PersistentKeepalive = p.persistentKeepalive; } // lib.optionalAttrs (p.presharedKeyFile != null) { PresharedKeyFile = "${credDir}/${pskCred name peer}"; } ) wg.peers; } ) cfg.wireguard; systemd.services.systemd-networkd.serviceConfig.LoadCredential = credentials; systemd.network.networks = lib.mapAttrs' ( name: wg: lib.nameValuePair "30-wg-${name}" { matchConfig.Name = wg.interface; address = wg.addresses; networkConfig = { ConfigureWithoutCarrier = true; IPv6AcceptRA = false; }; # Cryptokey routing: a peer's allowedIPs are the destinations sent into the tunnel. routes = lib.concatMap ( p: map ( ip: let sameFamily = lib.filter (s: lib.hasInfix ":" s == lib.hasInfix ":" ip) wg.sourceAddresses; in { Destination = ip; } // lib.optionalAttrs (sameFamily != [ ]) { PreferredSource = builtins.head sameFamily; } ) p.allowedIPs ) (lib.attrValues wg.peers); } ) cfg.wireguard; }; }