Run systemd service in network namespace

I could prepend ip netns exec xx where applicable (e.g. serviceConfig.ExecStart). But ip netns requires root privileges. What can I do if serviceConfig.User isn’t "root"?

maybe using JoinNamespaceOf (see man systemd.unit) on another unit that is running as root ?

1 Like

@azazel75 thanks a lot! got it working:

{ config, pkgs, lib, ... }: {
  systemd.services."netns@" = {
    description = "%I network namespace";
    before = [ "network.target" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
      PrivateNetwork = true;
      ExecStart = (pkgs.writeScript "netns-up" ''
        #! ${pkgs.bash}/bin/bash
        ${pkgs.iproute}/bin/ip netns add $1
        ${pkgs.utillinux}/bin/umount /var/run/netns/$1
        ${pkgs.utillinux}/bin/mount --bind /proc/self/ns/net /var/run/netns/$1
      '') + " %I";
      ExecStop = "${pkgs.iproute}/bin/ip netns del %I";
    };
  };
}

Any systemd.services.<name> can join with:

bindsTo = [ "netns@wg.service" ];
after = [ "netns@wg.service" ];
unitConfig.JoinsNamespaceOf = "netns@wg.service";
serviceConfig.PrivateNetwork = true;

stolen from https://github.com/systemd/systemd/issues/2741#issuecomment-336736214

1 Like

I might write a blog post soon about using this to sandbox transmission in a network namespace with wireguard, since I have a working setup. My Raspberry Pi is a NixOS seedbox, yay!