Port forwarding with DNAT and SNAT without touching other packets
- by w00t
I have a Linux gateway with iptables which does routing and port forwarding. I want the port forwarding to happen independent of the routing.
To port forward, I add this to the nat table:
iptables -t nat -A "$PRE" -p tcp -d $GW --dport $fromPort -j DNAT --to-destination $toHost:$toPort
iptables -t nat -A "$POST" -p tcp -d $toHost --dport $toPort -j SNAT --to $SRC
$PRE and POST are actually destination-specific chains that I jump to from the PREROUTING and POSTROUTING chains respectively so I can keep the iptables clean. $SRC is the IP address I'm SNATing to which is different from the gateway IP $GW.
The problem with this setup is that regular routed packets that were not DNATed but happen to go to the same $toHost:$toPort combo will also be SNATed.
I wish to avoid this. Any clever things I can do?