Files
nixos-router/modules/router/wireguard.nix
nilsandClaude Sonnet 5.5 5572172904 Re-resolve WireGuard peers' endpoint names
systemd-networkd resolves an endpoint name once, when it creates the
device. A peer behind a dynamic DNS name that changes its address was
never found again until the next restart.

A timer (router.wireguardEndpointRefresh, default 1min, null for off)
runs wg set for the peers with a name whose last handshake is older than
135 seconds, as wireguard-tools' reresolve-dns does. Working tunnels are
left alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV9dZrK6nipHkPfyM4F
2026-11-08 18:17:01 +01:00

175 lines
5.9 KiB
Nix

{
config,
lib,
pkgs,
...
}:
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
);
# Peers whose endpoint is a name (not an address). systemd-networkd looks a
# name up when it creates the device (and retries until it resolves, every
# 25 s at most), but never again: after the peer's address changes both
# sides keep sending to the old one.
isName = e: e != null && !lib.hasPrefix "[" e && builtins.match "[0-9.]+:[0-9]+" e == null;
namedPeers = lib.concatLists (
lib.mapAttrsToList (
name: wg:
lib.concatLists (
lib.mapAttrsToList (
peer: p:
lib.optional (isName p.endpoint) {
inherit (wg) interface;
inherit peer;
inherit (p) publicKey endpoint;
}
) 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;
# Look the names up again, like wireguard-tools' reresolve-dns: only for
# peers that have not shown a handshake lately (a working tunnel is left
# alone; with keepalive, handshakes are at most about two minutes apart).
systemd.services.router-wireguard-reresolve =
lib.mkIf (cfg.wireguardEndpointRefresh != null && namedPeers != [ ])
{
description = "Look up the names of WireGuard peer endpoints again";
after = [ "systemd-networkd.service" ];
path = [
pkgs.wireguard-tools
pkgs.gawk
pkgs.coreutils
];
script = ''
now=$(date +%s)
refresh() { # device peer-name public-key endpoint
last=$(wg show "$1" latest-handshakes 2>/dev/null | awk -v k="$3" '$1 == k { print $2 }')
[ -n "$last" ] || return 0 # no such device or peer (yet)
if [ "$last" -gt 0 ] && [ $((now - last)) -lt 135 ]; then return 0; fi
before=$(wg show "$1" endpoints | awk -v k="$3" '$1 == k { print $2 }')
if ! wg set "$1" peer "$3" endpoint "$4"; then
echo "$1: $2: cannot resolve $4"
return 0
fi
after=$(wg show "$1" endpoints | awk -v k="$3" '$1 == k { print $2 }')
if [ "$before" != "$after" ]; then echo "$1: $2: endpoint $before -> $after ($4)"; fi
}
''
+ lib.concatMapStrings (
p:
"refresh ${
lib.escapeShellArgs [
p.interface
p.peer
p.publicKey
p.endpoint
]
}\n"
) namedPeers;
serviceConfig = {
Type = "oneshot";
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_NETLINK"
"AF_UNIX"
];
NoNewPrivileges = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
};
};
systemd.timers.router-wireguard-reresolve =
lib.mkIf (cfg.wireguardEndpointRefresh != null && namedPeers != [ ])
{
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "2min";
OnUnitActiveSec = cfg.wireguardEndpointRefresh;
AccuracySec = "10s";
};
};
};
}