This page looks best with JavaScript enabled

MASQUERADE/SNAT - Port Redirection Iptables

 ·  🎃 kr0m

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:

vi /etc/sysctl.conf

net.ipv4.ip_forward = 1
sysctl -p

If we want to masquerade, it’s as simple as:

iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -d 0.0.0.0/0 -j MASQUERADE

On the other hand, if we want to do SNAT:

iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -d 0.0.0.0/0 -j SNAT –to-source 72.23.11.111

Another interesting aspect of iptables is port redirection, which is achieved as follows:

iptables -t nat -A PREROUTING -s 192.168.200.0/24 -d 0.0.0.0/0 -p tcp –dport 80 -j REDIRECT –to-port 3128

For redirection to another machine:

iptables -t nat -A PREROUTING -p tcp –dport 32002 -j DNAT –to-destination 10.0.0.2:22

If you liked the article, you can treat me to a RedBull here