What is IP Masquerade and how to rule it with iptables?

IP Masquerade is also known as Network Address Translation (NAT) and Network Connection Sharing some other popular operating systems. It is basically a method for allowing a computer that doesn’t have a public Internet wide IP address communicate with other computers on the Internet with the help of another computer sitting inbetween it and the Internet.

As you know IP address are used on the Internet to identify machines. Given a packet with an IP address, every router that makes up the Internet knows where to send that packet to get it to its destination. Now, there are also a few ranges of IP addresses that have been reserved for private use inside Local Area Networks and other networks that are not directly connected to the Internet. These private addresses are guaranteed not to be in use on the public Internet.

This causes problems for machines that are connected to private networks are use private IP addresses, because they can’t be connected directly to the Internet. They don’t have an IP address that is allowed to be used on the public Internet. IP Masquerade solves this problem by allowing a machine with a private IP address to communicate with the Internet, while at the same time modifying the machine’s packets to use a valid public IP address instead of the original private IP address. Packets returning from the Internet are modified back to use the original IP address before reaching private IP machine.

Note that this is not limited to the internet network masquerade/NAT can be used to route traffic from one network to an other let say 10.0.0.0/24 and 192.168.0.0/24

Iptables masquerade rule can be replaced with SNAT rule

iptables -t nat -A POSTROUTING -o eth2 -s 10.0.0.0/24  -j MASQUERADE

=

iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth2 -j SNAT --to-source 192.168.1.2
# supposing eth2 assigned ip is 192.168.1.2

Both masquerade and snat require ip_forward enabled at the kernel level with echo "1" > /proc/sys/net/ipv4/ip_forward or permanently by editing the settings file nano /etc/sysctl.conf.

IP Forward makes the machine act like a router and thus redirect/forward packets from all active interface logically by the targeted network (local/net/other/etc) or by following the route table. Note that enabling ip_forward may introduce important security risk, if ip_forward can not be avoided, it needs to be supervised/secured by additional iptables/route rules.

Share this post on:

Related posts:

How does Linux's display work?
How to scale the desktop's resolution?