Iptables is a very useful tool in the life of every sysadmin. With it, you can filter traffic, redirect it, make modifications to it, or even prioritize it. This time we will see how to masquerade a network and redirect incoming traffic. This is usually a typical scenario in a home network where we have a router that serves as a gateway to the rest of the devices. This way, with a single public IP, we can access the Internet, and if we need a port of one of the internal devices to be accessible from the outside, it will be possible.
The first thing we need to understand is the difference between masquerading and source NAT (SNAT). With masquerading, we let the kernel decide which source IP to use when forwarding the packet. On the other hand, with SNAT, we decide which IP to use. This is useful, for example, if we have multiple WAN IPs and we want to use one or the other depending on the internal device in our LAN.
First, we need to enable routing in the kernel:
net.ipv4.ip_forward = 1
If we want to masquerade, it’s as simple as:
On the other hand, if we want to do SNAT:
Another interesting aspect of iptables is port redirection, which is achieved as follows:
For redirection to another machine: