Created
May 28, 2020 10:33
-
-
Save nixbitcoin/72c5b5b77471775f5d28eb98ec7ba22b to your computer and use it in GitHub Desktop.
netns-generalized
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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