Network Address Translation (NAT) with iptables is often used to allow systems on a private network to access external networks, like the internet, using a single public IP address. One of the most common uses of NAT is for masquerading, which allows all devices on a private network to appear as if they’re coming from a single device with a public IP.
Here is a step-by-step tutorial for setting up masquerading with iptables:
Prerequisites
- A Linux system with iptables installed.
- This system should have two network interfaces: one connected to the private network (e.g., eth1) and another to the public network/internet (e.g., eth0).
- Root or superuser access.
Steps by Step Guide
Step 1: Enable IP Forwarding
Before a Linux system can forward packets from one network to another, it must have IP forwarding enabled.
echo 1 > /proc/sys/net/ipv4/ip_forward
To make this change permanent, edit the /etc/sysctl.conf file:
nano /etc/sysctl.conf
Add or modify the line:
net.ipv4.ip_forward = 1
Save and exit. To apply the change without rebooting, run:
sysctl -p
Step 2: Set Up NAT Using Masquerading
First, flush the existing NAT table and set up the default rules:
iptables -t nat -F
Now, set up masquerading for the external interface (eth0 in this example):
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Step 3: Allow Forwarding Rules
For the private network (eth1 in our example) to access the external network (eth0), you need to set forwarding rules.
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
Step 4: Save the iptables Rules
After setting up your rules, you’ll want to save them so they persist after a reboot. The way you save iptables rules depends on your system.
On systems with iptables-persistent:
service iptables-persistent save
On Red Hat based systems (CentOS, Fedora):
service iptables save
If you don’t have any of these, you can manually save the rules:
iptables-save > /etc/iptables.rules
To restore the rules on boot, you can add iptables-restore < /etc/iptables.rules to your startup scripts or use the appropriate methods based on your distribution.
5. Test the Configuration:
From a device on your private network, try accessing the external network (like browsing the internet). If set up correctly, the device should be able to reach external addresses and the source address of the traffic should appear as the public IP of your Linux system (masquerading).
Important Notes
This tutorial provides a basic setup and does not account for advanced security practices. In a real-world scenario, you might want to employ further security measures to safeguard your network.
If you are behind a firewall or have additional firewalls in place, ensure that necessary ports and traffic are allowed.
Always backup your current iptables rules before making changes.