I want to forward port 2222 on an Ubuntu 12.04 server to remote host 1.2.3.4 port 22, using iptables.
After reading many web pages on port-forwarding, I issue
$ sysctl net.ipv4.conf.eth0.forwarding
net.ipv4.conf.eth0.forwarding = 1
$ sudo iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 2222 -j DNAT --to-destination 1.2.3.4:22
Which forwards traffic as I desired. But ssh does not work. Turns out I needed to also supply
$ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
And now it's good. I understand the above commands; what I don't understand is the plethora of sites giving the first command and none giving the second. Under what conditions would the first command suffice?
Note: Example site giving only the DNAT commmand.
The sites you are referring to are likely recommending
DNAT
in the context of using iptables on a router that connects an internal LAN to the public Internet. In this case, since all the traffic between the Internet and the internal LAN must flow through the iptables router, the returning packets are automagically rewritten for you as well.In your configuration, you are trying to direct the traffic to a remote host. The
MASQUERADE
line is necessary in order to rewrite the packets going to 1.2.3.4 such that packets returning from 1.2.3.4 will reach your iptables box, in order to be rewritten and returned to the original sender properly.Big picture: what are you trying to accomplish? Port forwarding is probably not the right tool.