Port forwarding with DNAT and SNAT without touching other packets

Posted by w00t on Server Fault See other posts from Server Fault or by w00t
Published on 2012-07-03T13:13:41Z Indexed on 2012/07/03 15:17 UTC
Read the original article Hit count: 201

Filed under:
|

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?

© Server Fault or respective owner

Related posts about linux

Related posts about iptables