Sub topic 11
Why some protocols break behind NAT
This chapter assumes you know how a NAT device rewrites addresses and ports, how the translation table (connection tracking) works, and the difference between source NAT and destination NAT. You should also be comfortable reading iptables rules.
The core problem: NAT rewrites headers, not meanings
A NAT device edits the IP header and the TCP or UDP header. It does not understand what is inside the payload. That works for protocols where the payload never mentions an address or port, such as plain HTTP. HTTP sends a request out and reads the response on the same connection.
Some protocols break because they:
- Copy an IP address or port into the payload, so the peer is told an address that NAT never rewrote.
- Need the remote side to open a new connection back to the client, which NAT would drop because no table entry exists.
- Use a transport that has no ports, so PAT has nothing to multiplex on.
- Authenticate or checksum the very fields NAT changes.
The sections below take these in order.
Embedded addresses: FTP active mode
FTP uses two connections. The control connection goes from client to server port 21. In active mode, the client then tells the server where to connect for data, using a PORT command written in the payload as six decimal numbers: four for the address, two for the port (high byte, low byte).
def port_command(ip: str, port: int) -> str:
"""Build the FTP PORT command a client sends in active mode."""
octets = ip.replace(".", ",")
return f"PORT {octets},{port // 256},{port % 256}\r\n"
def parse_port_command(line: str) -> tuple[str, int]:
"""Recover the address and port the server will connect to."""
nums = [int(n) for n in line.strip().split(" ", 1)[1].split(",")]
return ".".join(str(n) for n in nums[:4]), nums[4] * 256 + nums[5]
cmd = port_command("192.168.1.10", 50000)
print(cmd.strip()) # PORT 192,168,1,10,195,80
print(parse_port_command(cmd)) # ('192.168.1.10', 50000)The client is at 192.168.1.10, a private address. NAT rewrites the IP header of this packet, so the server sees the source 203.0.113.5. The payload still says 192,168,1,10. The server then tries to connect to a private address that is not routable on the internet. Even if the address were correct, the incoming data connection would match no table entry and would be dropped.
Helpers (ALGs)
A fix is an application layer gateway (ALG), called a conntrack helper on Linux. It watches the control connection and does two things:
- It rewrites the address and port in the payload, using the public address and a port the NAT device chooses.
- It creates an expectation, a temporary table entry that allows the specific incoming data connection that the rewritten command announces.
Rewriting the payload has side effects. If 192,168,1,10,195,80 becomes 203,0,113,5,195,80, the text length changes. The helper must then adjust TCP sequence and acknowledgment numbers for the rest of the connection. It must also recompute the checksum, which covers the payload and a pseudo-header containing the IP addresses.
Since Linux 4.7, helpers are no longer assigned automatically. You must request them explicitly, because automatic assignment let any traffic on port 21 trigger parsing and opened a security risk.
sudo modprobe nf_conntrack_ftp
sudo iptables -t raw -A PREROUTING -p tcp --dport 21 -j CT --helper ftpThe first command loads the helper module. The second attaches it to connections arriving for port 21. The helper does not allow forwarding by itself, so your FORWARD policy must still permit the related data connection. You can match it with -m conntrack --ctstate RELATED,ESTABLISHED.
Where helpers fall short
ALGs look convenient but have real limits:
- Encryption defeats them. FTPS and SIP over TLS hide the payload, so the helper cannot find or edit addresses.
- Non-standard ports are not recognized unless you configure the helper for them.
- Each protocol needs its own code, and parsing bugs have caused security problems. Some routers ship buggy SIP ALGs that corrupt traffic and are best disabled.
- They only work on the NAT device in the path. Two NAT layers (a home router behind CGNAT) can each mangle the payload differently.
The better fix is often to avoid the problem. FTP passive mode (PASV) has the client open both connections outward, so no inbound connection is needed. The server's PASV reply does contain an address, but that is the server's own, which is normally public. A server behind its own NAT must be configured with its public address in that reply.
Inbound connections and unknown peers
The second category does not involve payload addresses. Any protocol where a remote host must start a connection to a client breaks, because the table has no entry for it. Examples include a SIP phone waiting for an incoming call, a game host, and peer-to-peer file sharing.
A NAT device only creates a mapping when an inside host sends the first packet. Without a mapping, an unsolicited packet from outside has no destination to rewrite to. It is either dropped or lands on the NAT device itself. The usual remedies are:
- A static port forward for a known service.
- Keepalive packets, so a UDP mapping created by an outbound packet stays alive. UDP entries typically expire after tens of seconds of silence.
- A rendezvous server and traversal techniques, covered in a later chapter.
SIP and RTP: addresses in the middle of a session
SIP sets up a call and describes the media streams using SDP, a text body inside the SIP message. SDP contains a line such as c=IN IP4 192.168.1.10 and an m=audio 40000 RTP/AVP 0 line. These tell the other party where to send the RTP audio stream. If NAT leaves them as they are, the far end sends audio to a private address. The result is the classic symptom of a call that connects but has one-way audio or no audio.
Signaling can work while media fails, because the signaling connection was created by an inside host, while RTP flows on separate UDP ports that the far end addresses blindly. Common fixes are a SIP ALG (fragile), a SIP-aware proxy or session border controller that rewrites SDP, and STUN or ICE on the client so it learns its public mapping and advertises that.
Protocols without ports
PAT needs a port number to keep many hosts distinct behind one address. Some protocols have none:
| Protocol | IP protocol number | Why NAT struggles |
|---|---|---|
| ICMP | 1 | No ports. Linux tracks echo requests using the ICMP identifier field instead. Errors are matched to the connection they refer to. |
| ESP (IPsec) | 50 | No ports, and the packet is encrypted and integrity-protected. Only one inside host can map to a given peer reliably. |
| AH (IPsec) | 51 | Its integrity check covers the IP addresses, so any rewrite invalidates it. |
| GRE (PPTP data) | 47 | No ports. PPTP needs a helper that matches the call ID in the GRE header. |
IPsec has a standard workaround called NAT-T. It wraps ESP in UDP on port 4500, so NAT sees ordinary UDP with ports it can translate. Both ends detect the presence of NAT during the key exchange and switch to the UDP encapsulation.
Other things NAT changes
- Checksums. TCP and UDP checksums include a pseudo-header with the IP addresses, so NAT must update them on every rewritten packet. Software that sets the checksum field to zero in UDP IPv4 can mask errors, but that is not a general fix.
- Fragmentation. Only the first fragment of a datagram carries the port numbers. A NAT device must reassemble fragments or track them, or it cannot translate later fragments. Linux conntrack reassembles before translating.
- Identity in the payload. Protocols that log or authorize by client IP (some licensing servers, IRC
ident, access lists) see the NAT device's public address for every inside host. - Embedded URLs. A web page that hardcodes
http://192.168.1.10/...breaks for outside users regardless of NAT, because the address is private.
Troubleshooting checklist
- Check whether the failing step is the first connection or a later, separate one. If the first works and a second fails, suspect an embedded address or an inbound connection.
- Capture on both sides of the NAT device and compare payloads, not only headers. Use
tcpdump -A -i eth0 port 21. - Run
sudo conntrack -Land look for[UNREPLIED]entries, which show an attempt with no reply, and for entries marked as expected connections. - Confirm the helper is loaded (
lsmod | grep conntrack_ftp) and explicitly attached with aCT --helperrule. - Prefer a protocol mode that avoids the problem, such as FTP passive mode, TLS-based signaling with a proxy, or NAT-T for IPsec.
Exercise
A client at 192.168.1.20 behind a PAT gateway uses FTP active mode. It sends PORT 192,168,1,20,200,10. What port will the server try to connect to, and why does the connection fail without an ALG?
Show answer
The port is 200 × 256 + 10 = 51210. The gateway rewrote only the IP header of the control packet, so the payload still names the private address 192.168.1.20. The server tries to reach that private address, which is not routable from the internet. Even with a correct address, no table entry exists for an inbound connection to that port.
Exercise
A SIP call connects and both phones ring, but the caller hears no audio. Signaling uses one TCP or UDP flow and media uses separate UDP ports. Give the most likely cause and two fixes.
Show answer
The SDP body in the SIP message still advertises the phone's private address and RTP port, so the far end sends audio to an address it cannot reach. Signaling works because the inside host opened that flow first. Fixes: use STUN or ICE on the phone so it advertises its public mapping, or put a SIP-aware proxy or session border controller at the edge that rewrites SDP. A SIP ALG on the router is a third option but is often unreliable.