Course contentsShow
← Linux
Lesson 1152 of 1,81910. Network Administration and Kernel StacksFree lesson

NAT Strategies and Implementation

Implement SNAT, DNAT, and Masquerading for network address translation.

In this lesson, you will learn how to manipulate packet headers using Netfilter to implement SNAT, DNAT, and Masquerading for seamless network traffic translation.

Network Address Translation (NAT) allows a Linux gateway to modify the source or destination IP addresses of packets as they transit the kernel. This is essential for hiding internal network topology or mapping public-facing services to private backend servers.

SNAT and Masquerading

Source NAT (SNAT) is used when you need to change the source address of packets leaving your network. This is common when internal clients (with private IPs) need to reach the internet. You use the SNAT target when you have a static public IP:

nft add rule ip nat postrouting oif "eth0" snat to 198.51.100.1

If your public IP is dynamic (e.g., provided by DHCP on a WAN interface), use masquerade instead. It automatically handles the IP address discovery:

nft add rule ip nat postrouting oif "eth0" masquerade

DNAT

Destination NAT (DNAT) is used to redirect incoming traffic from the outside world to a specific internal server. This is the mechanism behind port forwarding. If an external client connects to your gateway's public port 80, you can transparently forward that request to an internal web server:

nft add rule ip nat prerouting iif "eth0" tcp dport 80 dnat to 192.168.1.50:80

Mechanics at Play

These translations rely on the Netfilter Hook System and Connection Tracking (conntrack). When a packet undergoes NAT, the kernel creates an entry in the conntrack table. This ensures that all subsequent packets in the same flow are translated consistently without re-evaluating the rule set for every single packet.

It is important to remember that NAT happens primarily in the prerouting chain (for DNAT) and the postrouting chain (for SNAT). By modifying these headers, you decouple the addressing of your internal infrastructure from the routing expectations of the public internet.

Key Takeaway: Use SNAT for static IP source translation, Masquerading for dynamic interfaces, and DNAT for redirecting incoming traffic to internal services.