Sub topic 8
Hands-on: masquerading and port forwarding on Linux
This chapter assumes you know IPv4 subnetting, what a default gateway does, how TCP and UDP ports work, and how to run commands in a Linux shell. It also assumes you have read the earlier chapters on the translation table, source NAT with PAT, and port forwarding. Here you will turn those ideas into working rules on a Linux gateway.
The lab setup
The examples use one Linux host that sits between a private LAN and the public network.
| Item | Value |
|---|---|
| WAN interface | `eth0`, public address `203.0.113.5` |
| LAN interface | `eth1`, address `192.168.1.1/24` |
| Internal web server | `192.168.1.10`, listening on TCP port 80 |
| Other LAN hosts | `192.168.1.0/24`, default gateway `192.168.1.1` |
The addresses 203.0.113.0/24 are reserved for documentation, so treat 203.0.113.5 as a stand-in for your real public address. Run all commands as root or with sudo. Rules made with these commands live in kernel memory and are lost at reboot unless you save them (covered near the end).
How Linux does NAT
Linux NAT is done by the kernel's netfilter framework. Packets pass through fixed hook points, and NAT rules attach to some of them:
- PREROUTING runs when a packet arrives, before the kernel decides where to send it. Destination NAT (DNAT) belongs here, so the routing decision sees the rewritten destination.
- FORWARD runs for packets that are passing through the host, not addressed to it. The filter rules that allow or block forwarded traffic live here.
- POSTROUTING runs just before a packet leaves. Source NAT (SNAT and MASQUERADE) belongs here, after routing has chosen the outgoing interface.
Only the first packet of a connection traverses the NAT rules. The kernel records the result in its connection tracking table (conntrack), and all later packets of that connection, in both directions, are translated automatically from that entry. This is why you write a rule only for the direction that starts the connection, and never for the replies.
Step 1: enable IP forwarding
By default a Linux host drops packets that are not addressed to it. A gateway must be allowed to route them.
# Allow the Linux host to forward packets between interfaces
sudo sysctl -w net.ipv4.ip_forward=1This takes effect immediately but does not survive a reboot. To make it permanent, put net.ipv4.ip_forward = 1 in a file such as /etc/sysctl.d/99-forward.conf and run sudo sysctl --system.
Without this setting, NAT rules may look correct, yet LAN clients get no replies because the kernel never routes their packets.
Step 2: masquerading for outbound traffic
Masquerading is source NAT for hosts that share one public address.
# eth0 = public/WAN interface, 192.168.1.0/24 = private LAN
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADERead the rule piece by piece:
-t natselects the nat table.-A POSTROUTINGappends the rule to the POSTROUTING chain.-s 192.168.1.0/24matches packets from the LAN.-o eth0matches packets leaving through the WAN interface.-j MASQUERADErewrites the source address to the current address ofeth0.
When two LAN hosts happen to use the same source port, the kernel picks a different source port for one of them, so each connection keeps a unique entry and replies can be matched to the right host.
MASQUERADE or SNAT
MASQUERADE looks up the outgoing interface's address each time. That suits a WAN address that changes, such as one assigned by DHCP. If the address is fixed, -j SNAT --to-source 203.0.113.5 does the same job with slightly less work per connection. A drawback of MASQUERADE is that when the interface goes down, the kernel flushes the tracked connections that used its old address. This is usually the right behavior when the address changes.
Step 3: port forwarding with DNAT
Port forwarding is destination NAT. This example exposes the internal web server on port 8080 of the gateway.
# Forward TCP port 8080 on the gateway's WAN interface to 192.168.1.10:80
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
# Allow the forwarded traffic through the filter table
sudo iptables -A FORWARD -i eth0 -p tcp -d 192.168.1.10 --dport 80 -j ACCEPTTwo separate rules are needed because NAT and filtering are separate jobs:
- The PREROUTING rule rewrites the destination from
203.0.113.5:8080to192.168.1.10:80. - The FORWARD rule permits the packet. It matches the destination after DNAT, so it uses port 80 and the private address, not 8080. If your FORWARD policy is
ACCEPTand you have no restrictive rules, this rule is not needed. On a gateway with a defaultDROPpolicy, it is required.
Replies from the server travel back through the gateway because the server's default gateway is 192.168.1.1. The conntrack entry reverses the translation, and the client sees replies coming from 203.0.113.5:8080, which is the address it contacted.
The same setup with nftables
Modern distributions are moving from iptables to nftables. The same port forward and masquerade look like this:
# Same setup with nftables
sudo nft add table ip nat
sudo nft 'add chain ip nat prerouting { type nat hook prerouting priority dstnat; policy accept; }'
sudo nft 'add chain ip nat postrouting { type nat hook postrouting priority srcnat; policy accept; }'
sudo nft add rule ip nat prerouting iifname "eth0" tcp dport 8080 dnat to 192.168.1.10:80
sudo nft add rule ip nat postrouting oifname "eth0" masqueradeThe structure is the same. You create a table, then chains attached to the prerouting and postrouting hooks, then rules in those chains. The priority dstnat and priority srcnat values place the chains at the conventional points in the hook ordering.
These commands create only the NAT part. If your system has an nftables filter ruleset with a default drop policy on the forward hook, you still need a separate rule that accepts the forwarded traffic.
Check which tool your system really uses. On many current distributions the iptables command is a compatibility layer over nftables, and you can see its rules with sudo nft list ruleset. Avoid managing the same rules with both tools by hand, because the result is hard to reason about.
Hairpin NAT
A LAN client that tries http://203.0.113.5:8080/ reaches the gateway from inside. DNAT sends the packet to 192.168.1.10. The server sees the client's real LAN address as the source and replies directly to it, skipping the gateway. The client then receives a reply from 192.168.1.10 when it expected 203.0.113.5, and drops it.
The fix is to also rewrite the source for this traffic, so the server replies to the gateway:
# Hairpin NAT: let LAN clients use the public address 203.0.113.5:8080
sudo iptables -t nat -A PREROUTING -d 203.0.113.5 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -d 192.168.1.10 -p tcp --dport 80 -j MASQUERADEThe first rule has no -i eth0, so it matches packets from any interface, including the LAN, as long as the destination is the public address. The second rule masquerades LAN-to-server traffic so the server sees the gateway as the source. A later chapter covers hairpin NAT and its trade-offs in more depth.
Inspect and verify
The conntrack tool shows what the kernel has recorded.
# Inspect the kernel's connection tracking table (NAT mappings)
sudo conntrack -L -p tcpEach entry lists an original tuple and a reply tuple. For a forwarded connection, the original tuple has destination 203.0.113.5:8080, while the reply tuple has source 192.168.1.10:80. The difference between the two is the translation.
You can also list the rules with their packet counters:
sudo iptables -t nat -L -n -vA counter that stays at zero after a test means traffic never matched that rule. That tells you where to look next.
Test in two steps, so you can separate a service that is not listening from a forwarding or firewall problem:
# On the internal server: confirm the service is listening
sudo ss -ltn 'sport = :80'
# From a host outside the network: test the forwarded port
curl -v http://203.0.113.5:8080/Common errors
| Symptom | Likely cause |
|---|---|
| LAN hosts cannot reach the internet at all | `net.ipv4.ip_forward` is 0, or the masquerade rule names the wrong `-o` interface |
| Port forward times out from outside | FORWARD chain drops the traffic, or the upstream router or ISP blocks the port |
| Port forward works outside but not from the LAN | Hairpin NAT is missing |
| Connection works, but the server logs show the gateway's address as the client | A masquerade rule is matching the forwarded traffic, hiding the real client address |
| Connection refused immediately | The gateway is reachable but nothing is listening on the internal server, or the server's local firewall rejects the connection |
| Forward works until reboot | Rules and the sysctl setting were never saved |
A server whose default gateway is not the NAT host is a frequent cause of silent failure. The reply then leaves by another path, with an unexpected source address, and the client discards it.
Making the rules persistent
Rules added from the command line vanish at reboot. Save and restore them with the mechanism your distribution provides. On Debian and Ubuntu, the iptables-persistent package saves the current rules with sudo netfilter-persistent save. For nftables, store the rules in /etc/nftables.conf and enable the nftables service. Record the sysctl change in /etc/sysctl.d/ as shown earlier.
Exercise
A LAN client at 192.168.1.50 opens a connection through your gateway to a website. Which iptables chain and table hold the rule that rewrites its source address, and why must that rule sit there rather than in PREROUTING?
Show answer
The rule is in the POSTROUTING chain of the nat table. Source NAT must run after the routing decision, because MASQUERADE uses the address of the outgoing interface, and that interface is only known once routing has chosen it. The conntrack entry created there translates the reply packets automatically.
Exercise
You added the DNAT rule for port 8080 and the server is listening on port 80. A test from the internet times out, and iptables -t nat -L -n -v shows the DNAT rule's packet counter is increasing. The filter table has a default DROP policy on FORWARD. What is the most likely missing piece, and what should the rule match?
Show answer
A FORWARD rule that accepts the traffic. The counter shows DNAT is working, so packets reach the gateway and get translated, but the FORWARD policy drops them. The rule must match the destination after translation: -d 192.168.1.10 -p tcp --dport 80, not port 8080.