NAT and Masquerading with iptables
You'll learn how to rewrite packet addresses with iptables NAT rules to enable routing, hide internal networks, and forward ports.
Network Address Translation (NAT) changes the source or destination IP addresses in packets as they pass through your firewall. Think of it like a receptionist who forwards calls: external callers dial one number, but the receptionist routes them to the correct internal extension.
The NAT Table
iptables uses the nat table specifically for address translation, with three main chains:
- PREROUTING: Changes destination addresses (DNAT) before routing decisions
- POSTROUTING: Changes source addresses (SNAT/Masquerade) after routing decisions
- OUTPUT: For locally-generated packets needing NAT
Source NAT (SNAT)
SNAT replaces the source IP of outgoing packets, typically to allow private IPs to reach the internet:
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 203.0.113.5
Masquerading
Masquerade is dynamic SNAT for interfaces with changing IPs (like home routers with DHCP):
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Destination NAT (DNAT) and Port Forwarding
DNAT redirects incoming traffic to different internal hosts or ports:
# Forward external port 80 to internal server
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10:80
This enables port forwarding—exposing internal services through your firewall's public IP.
Key Takeaway: The NAT table in iptables rewrites packet addresses: use SNAT/Masquerade in POSTROUTING to hide internal networks, and DNAT in PREROUTING for port forwarding to internal services.