From 622376ecb09f7cd85b3be3604ea83c4499916f29 Mon Sep 17 00:00:00 2001 From: TNE Date: Sun, 21 Jul 2024 07:20:31 +0200 Subject: [PATCH] nixos/nat: Prevent NAT reflection on connections not coming from behind the NAT --- .../services/networking/nat-iptables.nix | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/nixos/modules/services/networking/nat-iptables.nix b/nixos/modules/services/networking/nat-iptables.nix index 4660ff6f0e15..1f8d6c24d9b6 100644 --- a/nixos/modules/services/networking/nat-iptables.nix +++ b/nixos/modules/services/networking/nat-iptables.nix @@ -77,15 +77,25 @@ let -j DNAT --to-destination ${fwd.destination} # Allow connections to ${loopbackip}:${toString fwd.sourcePort} from other hosts behind NAT - ${iptables} -w -t nat -A nixos-nat-pre \ - -d ${loopbackip} -p ${fwd.proto} \ - --dport ${builtins.toString fwd.sourcePort} \ - -j DNAT --to-destination ${fwd.destination} - - ${iptables} -w -t nat -A nixos-nat-post \ - -d ${destinationIP} -p ${fwd.proto} \ - --dport ${destinationPorts} \ - -j SNAT --to-source ${loopbackip} + ${concatMapStrings (range: '' + ${iptables} -w -t nat -A nixos-nat-pre \ + -d ${loopbackip} -p ${fwd.proto} -s '${range}' \ + --dport ${builtins.toString fwd.sourcePort} \ + -j DNAT --to-destination ${fwd.destination} + ${iptables} -w -t nat -A nixos-nat-post \ + -d ${destinationIP} -p ${fwd.proto} \ + -s '${range}' --dport ${destinationPorts} \ + -j SNAT --to-source ${loopbackip} + '') internalIPs} + ${concatMapStrings (iface: '' + ${iptables} -w -t nat -A nixos-nat-pre \ + -d ${loopbackip} -p ${fwd.proto} -i '${iface}' \ + --dport ${builtins.toString fwd.sourcePort} \ + -j DNAT --to-destination ${fwd.destination} + ${iptables} -w -t nat -A nixos-nat-post \ + -d ${destinationIP} -p ${fwd.proto} \ + -i '${iface}' --dport ${destinationPorts} \ + -j SNAT --to-source ${loopbackip} '') fwd.loopbackIPs} '') forwardPorts} '';