refactor: put namespaced vm code in module

Signed-off-by: Lander Van den Bulcke <landervandenbulcke@gmail.com>
This commit is contained in:
Lander Van den Bulcke 2025-09-19 14:46:07 +02:00
parent df715a7e8f
commit fc2d98e503
Signed by: lander
GPG key ID: 0142722B4B0C536F
4 changed files with 158 additions and 80 deletions

View file

@ -1,4 +1,8 @@
{ config, pkgs, ... }:
{
config,
pkgs,
...
}:
{
networking.firewall = {
enable = true;
@ -11,85 +15,15 @@
];
};
networking.iproute2.enable = true;
systemd.network.config = {
routeTables = {
vpn = 133;
};
addRouteTablesToIPRoute2 = true;
};
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 =
let
script = pkgs.writers.writeBash "veth-up" ''
ns="$1"
${pkgs.iproute2}/bin/ip link add veth-init-$ns type veth peer name veth-ns-$ns
${pkgs.iproute2}/bin/ip link set veth-ns-$ns netns $ns
${pkgs.iproute2}/bin/ip link set veth-init-$ns up
${pkgs.iproute2}/bin/ip netns exec $ns ${pkgs.iproute2}/bin/ip link set veth-ns-$ns up
${pkgs.iproute2}/bin/ip netns exec $ns ${pkgs.iproute2}/bin/ip addr add 10.0.0.2/24 dev veth-ns-$ns
'';
in
"${script} %i";
ExecStop = "${pkgs.iproute2}/bin/ip link del veth-%i";
};
};
systemd.network.networks."50-veth" = {
matchConfig.Name = "veth-init-vpn";
networkConfig = {
Address = "10.0.0.1/24";
};
};
systemd.services."wireguard-wg0".requires = [
"netns@vpn.service"
"veth-setup@vpn.service"
];
networking.wireguard = {
services.namespaced-vpn = {
enable = true;
useNetworkd = false;
interfaces.wg0 = {
ips = [
"10.64.244.95/32"
"fc00:bbbb:bbbb:bb01::1:f45e/128"
];
peers = [
{
publicKey = "KkShcqgwbkX2A9n1hhST6qu+m3ldxdJ2Lx8Eiw6mdXw=";
allowedIPs = [
"0.0.0.0/0"
"::0/0"
];
endpoint = "146.70.117.226:51820";
persistentKeepalive = 25;
}
];
listenPort = 51820;
privateKeyFile = config.sops.secrets.wireguardKey.path;
socketNamespace = "init";
interfaceNamespace = "vpn";
};
ips = [
"10.64.244.95/32"
"fc00:bbbb:bbbb:bb01::1:f45e/128"
];
publicKey = "KkShcqgwbkX2A9n1hhST6qu+m3ldxdJ2Lx8Eiw6mdXw=";
endpoint = "146.70.117.226:51820";
privateKeyFile = config.sops.secrets.wireguardKey.path;
};
environment.systemPackages = with pkgs; [