Skip to content

Instantly share code, notes, and snippets.

@nixbitcoin
Created May 28, 2020 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nixbitcoin/72c5b5b77471775f5d28eb98ec7ba22b to your computer and use it in GitHub Desktop.
Save nixbitcoin/72c5b5b77471775f5d28eb98ec7ba22b to your computer and use it in GitHub Desktop.
netns-generalized
mkNetns = { name, iface }:
mkIf config.services.${name}.enable = {
description = "Create ${name} namespace";
requires = [ "netns.service" ];
after = [ "netns.service" ];
requiredBy = [ "${name}.service" ];
bindsTo = [ "${name}.service" ];
before = [ "${name}.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = "yes";
ExecStartPre = "-${pkgs.iproute}/bin/ip netns delete ${name}";
ExecStart = [
"${pkgs.iproute}/bin/ip netns add ${name}"
"${pkgs.iproute}/bin/ip -n ${name} link set lo up"
"${pkgs.iproute}/bin/ip link add ${iface} type veth peer name br-${iface}"
"${pkgs.iproute}/bin/ip link set ${iface} netns ${name}"
"${pkgs.iproute}/bin/ip -n ${name} addr add ${cfg.${name}.ipAddress}/24 dev ${iface}"
"${pkgs.iproute}/bin/ip link set br-${iface} up"
"${pkgs.iproute}/bin/ip -n ${name} link set ${iface} up"
"${pkgs.iproute}/bin/ip link set br-${iface} master br0"
"${pkgs.iproute}/bin/ip -n ${name} route add default via ${cfg.bridge.ipAddress}"
]
++ (optionals config.services.${name}.enforceTor [
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -P OUTPUT DROP"
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -A OUTPUT -d 127.0.0.1,${cfg.bridge.ipAddress} -j ACCEPT"
(lib.forEach ${cfg.${name}.availableNetns} (y: optionals config.services.${y}.enable [
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -A OUTPUT -d ${cfg.y.ipAddress} -j ACCEPT"
]))
]
++ (optionals config.services.${name}.enforceTor && config.services.${availableNetns}.enable [
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -A OUTPUT -d ${cfg.availableNetns.ipAddress} -j ACCEPT"
])
++ [
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -P INPUT DROP"
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -A INPUT -s 127.0.0.1,${cfg.bridge.ipAddress} -j ACCEPT"
]
++ (optionals config.services.${availableNetns}.enable [
"${pkgs.iproute}/bin/ip netns exec ${name} ${pkgs.iptables}/bin/iptables -A INPUT -s ${cfg.availableNetns.ipAddress} -j ACCEPT"
]);
ExecStop = ''
${pkgs.iproute}/bin/ip netns delete ${name} ;\
${pkgs.iproute}/bin/ip link del br-${iface}
'';
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment