Linux – How does iptables MASQUERADE work on the incoming side

iptableslinuxnat;route

I'm still reading the iptables manual page and other documents and
digging around questions and their answers.

This is the problem which arises.
When we setup the NAT we use a POSTROUTING rule such as this:

iptables -A POSTROUTING -t nat -j MASQUERADE -o eth0 

It seems when a packet hits this chain then an internal host needs to initialize
some connection with the internet right? Incoming traffic will route through the same path without hitting the chain? Am I right on this?

Best Answer

The POSTROUTING chain is checked for all packets which leave the system, even the locally generated ones (they leave out PREROUTING and use OUTPUT instead).

The rule is limited to traffic which is outgoing via eth0. "Incoming" is every traffic being routed (if you related this to POSTROUTING). You probably mean traffic from the Internet (eth0). Usually traffic which comes in on eth0 will not leave the system via eth0.

POSTROUTING affects outgoing traffic only (and only the first packet of a connection). If replies arrive on eth0 then they are recognized as part of the SNAT connection and their destination address (and port) are automatically translated to their original values (those overwritten by the MASQUERADE target).

Related Question