From ded73650a9d1b3669a08ba60f2e1a284e50ef3a3 Mon Sep 17 00:00:00 2001 From: Lander Van den Bulcke Date: Thu, 11 Sep 2025 23:14:49 +0200 Subject: [PATCH] feat: use network namespace for wireguard Signed-off-by: Lander Van den Bulcke --- hosts/hosting-02/default.nix | 63 +++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/hosts/hosting-02/default.nix b/hosts/hosting-02/default.nix index 565fd45..d8a6517 100644 --- a/hosts/hosting-02/default.nix +++ b/hosts/hosting-02/default.nix @@ -35,33 +35,51 @@ address = [ "2a01:4f8:c013:7fc0::/64" ]; - - routingPolicyRules = [ - { - From = "10.64.244.95/32"; - Table = "vpn"; - } - { - From = "fc00:bbbb:bbbb:bb01::1:f45e/128"; - Table = "vpn"; - } - { - User = config.users.users.vpn.uid; - Table = "vpn"; - Family = "both"; - } - ]; }; - users.groups.vpn = { }; - users.users.vpn = { - isSystemUser = true; - group = "vpn"; - uid = 51280; + systemd.services."netns@" = { + description = "Network namespace %i"; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStart = "${pkgs.iproute2}/bin/ip netns add %i"; + ExecStop = "${pkgs.iproute2}/bin/ip netns del %i"; + }; }; + systemd.services."veth-setup@" = { + description = "Setup veth pair for %i namespace"; + after = [ "netns@%i.service" ]; + requires = [ "netns@%i.service" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStart = '' + ${pkgs.iproute2}/bin/ip link add veth-%i type veth peer name veth-ns-%i + ${pkgs.iproute2}/bin/ip link set veth-ns-%i netns %i + ${pkgs.iproute2}/bin/ip link set veth-%i up + ${pkgs.iproute2}/bin/ip netns exec %i ${pkgs.iproute2}/bin/ip link set veth-ns-%i up + ${pkgs.iproute2}/bin/ip netns exec %i ${pkgs.iproute2}/bin/ip addr add 10.0.0.2/24 dev veth-ns-%i + ${pkgs.iproute2}/bin/ip netns exec %i ${pkgs.iproute2}/bin/ip route add default via 10.0.0.1 + ''; + ExecStop = "${pkgs.iproute2}/bin/ip link del veth-%i"; + }; + }; + + systemd.network.networks."50-veth" = { + matchConfig.Name = "veth-*"; + networkConfig = { + Address = "10.0.0.1/24"; + }; + }; + + systemd.services."wireguard-wg0".requires = [ + "netns@vpn.service" + "veth-setup@vpn.service" + ]; networking.wireguard = { enable = true; + useNetworkd = false; interfaces.wg0 = { ips = [ @@ -83,7 +101,8 @@ listenPort = 51820; privateKeyFile = config.sops.secrets.wireguardKey.path; - table = "133"; + socketNamespace = "init"; + interfaceNamespace = "vpn"; }; };