Sub topic 4
How the NAT device remembers connections
This chapter assumes you know the 5-tuple (source address, source port, destination address, destination port, protocol). It also assumes you know that NAT rewrites addresses and ports in packet headers. Here you will learn the state that makes this work: the translation table, which on Linux is the connection tracking table.
Why NAT needs memory
Rewriting the source address of an outgoing packet is simple. The hard part is the reply. A reply arrives addressed to the gateway's public address, for example 203.0.113.5:51514. Nothing in that packet says which private host started the conversation. The gateway must remember, so it keeps one entry for each connection it has translated.
The entry stores two views of the same flow. The kernel's connection tracking subsystem, called conntrack, records both:
- The original tuple is the flow as the private host sent it.
- The reply tuple is the flow as the remote server will answer it, after translation.
When a packet arrives, the NAT device looks for a matching tuple in either direction. A match in the original direction gets the forward translation. A match in the reply direction gets the reverse translation. No match means the packet belongs to no known connection.
Anatomy of one entry
Suppose 192.168.1.20 opens a TLS connection to 93.184.216.34:443. The gateway's public address is 203.0.113.5. After the handshake starts, conntrack shows an entry like this:
tcp 6 431999 ESTABLISHED src=192.168.1.20 dst=93.184.216.34 sport=51514 dport=443 src=93.184.216.34 dst=203.0.113.5 sport=443 dport=51514 [ASSURED]Read it in two halves.
- The first
src/dst/sport/dportgroup is the original tuple: private host to server. - The second group is the reply tuple: server to the gateway's public address. The destination
203.0.113.5:51514is the translated source.
The number 431999 is the seconds left before the entry expires. ASSURED means traffic has been seen in both directions.
The kernel does not store a separate "translation rule". The translation is implied by the difference between the two tuples. Here the original source 192.168.1.20 became 203.0.113.5 in the reply tuple. Reversing that difference translates replies.
Following a packet and its reply
The order of events matters.
- The first packet of a connection finds no entry. In Linux this packet is in state
NEW. It passes through thenattable, and a rule such asMASQUERADEpicks the translation. - The kernel stores the result in the table.
- Every later packet of that connection, in either direction, is translated from the table. The
nattable rules are not evaluated again for it.
Step 3 explains a common surprise: editing a NAT rule does not change connections that already exist. Existing flows keep their old translation until they end or expire. After changing a rule, you may need to delete the old entries to see the new behavior.
Port collisions
Two private hosts can choose the same source port. Both 192.168.1.20 and 192.168.1.21 might connect to the same server with source port 51514. The reply tuples would then be identical, and the gateway could not tell the replies apart.
The kernel handles this when it creates the entry. If the preferred translated tuple is already taken, it picks a different source port.
| Original tuple (private side) | Reply tuple (public side) | Note |
|---|---|---|
| `192.168.1.20:51514 -> 93.184.216.34:443` | `93.184.216.34:443 -> 203.0.113.5:51514` | Port kept |
| `192.168.1.21:51514 -> 93.184.216.34:443` | `93.184.216.34:443 -> 203.0.113.5:1024` | Port changed to avoid collision |
This is the mechanism behind port address translation, covered in the next chapter. The table is what makes it safe to share one public address.
Connection states
Conntrack tracks more than address pairs. It also tracks a state for each flow, which firewall rules can match on:
| State | Meaning |
|---|---|
| `NEW` | First packet of a connection the table has not seen |
| `ESTABLISHED` | Traffic has been seen in both directions |
| `RELATED` | A new connection tied to an existing one, such as an ICMP error or an FTP data channel |
| `INVALID` | A packet that fits no known connection and is not a valid start, for example a stray TCP ACK |
This is why a NAT gateway acts as a basic stateful firewall for inbound traffic. An outside host that sends an unsolicited packet to the public address matches no entry. Unless a destination NAT rule (port forwarding) applies, the packet has nowhere to be sent. A reply to a packet that a private host sent first does match, so it is let through.
Entry lifetime and timeouts
Entries cannot live forever, because the table is finite and the gateway cannot know when a UDP "connection" has ended. TCP entries follow the TCP state machine. UDP and ICMP entries rely on timers.
Typical Linux defaults are shown below. Check your kernel's actual values, because they vary by version and distribution.
| Flow type | Approximate default timeout |
|---|---|
| TCP `ESTABLISHED` | 432000 s (5 days) |
| TCP `SYN_SENT` | 120 s |
| TCP `TIME_WAIT` | 120 s |
| UDP, no reply seen | 30 s |
| UDP, traffic in both directions | 120 s |
| ICMP | 30 s |
Each packet that matches an entry resets its timer. An idle flow is therefore removed only after a full timeout with no traffic.
Consumer routers and cloud NAT services often use much shorter TCP idle timeouts than Linux does. After the entry is removed, the next packet from either side matches nothing. Typical symptoms are an SSH session that freezes after a few idle minutes, or a long-lived database connection that fails with a reset after a quiet period. The usual fixes are TCP keepalives that send traffic more often than the timeout, or a longer timeout on the device.
Inspecting the table
List tracked TCP connections:
# Inspect the kernel's connection tracking table (NAT mappings)
sudo conntrack -L -p tcpWatch entries appear and disappear in real time while you generate traffic:
# Stream NEW, UPDATE and DESTROY events for TCP
sudo conntrack -E -p tcpCheck how full the table is, and what its limit is:
# Current entry count and maximum table size
sudo conntrack -C
cat /proc/sys/net/netfilter/nf_conntrack_maxDelete the entries for one internal host. This forces new connections to pass through the current rules:
# Remove tracked connections whose original source is 192.168.1.20
sudo conntrack -D -s 192.168.1.20The conntrack command comes from the conntrack package (conntrack-tools) on most distributions, and it needs root.
Common errors
- Table full. Each tracked flow uses kernel memory. When the count reaches
nf_conntrack_max, new connections are dropped. The kernel log showsnf_conntrack: table full, dropping packet. Busy gateways, port scans, and DNS-heavy or UDP-heavy workloads cause this. Raise the limit withsysctl -w net.netfilter.nf_conntrack_max=...only after you confirm that memory allows it, and find the source of the flood. - Asymmetric routing. The table only works if the reply passes back through the same gateway. If the reply takes another path, the gateway sees a packet from the server with no matching entry. It is usually marked
INVALIDand dropped, and the other path may not translate the reply at all. - Stale mappings after a rule change. As noted above, old entries keep their old translation. Test with a new connection, or delete the old entries.
- Missing return path in a firewall. A
FORWARDpolicy ofDROPblocks replies unless a rule acceptsESTABLISHED,RELATEDtraffic. NAT creates the entry, but the filter table still decides whether the packet may pass. - Assuming the table works without the module. NAT in iptables and nftables depends on conntrack. If the conntrack modules are not loaded,
conntrack -Lshows nothing and NAT does not work.
What to take forward
The translation table is the state behind every NAT feature. Source NAT creates entries for outbound connections. Destination NAT creates entries for inbound ones. In both cases the original and reply tuples define the translation. Timeouts and table size set practical limits on how long and how many flows a NAT device can carry.
Exercise
A host at 192.168.1.30 opens a UDP flow to 198.51.100.7:5000 from source port 40000. The gateway at 203.0.113.5 translates it. The remote host replies 90 seconds after the last packet it received, and the gateway uses the default timeouts from this chapter. Does the reply reach the host if the remote side never sent anything earlier? Which tuple does the gateway match the reply against, and what would you change if a reply arriving after a long silence must work?
Show answer
With no earlier reply, the UDP entry uses the shorter "no reply seen" timeout of about 30 seconds. After 90 seconds of silence, the entry has expired, so the reply matches nothing and is dropped. If the entry were still alive, the gateway would match the reply against the reply tuple, 198.51.100.7:5000 -> 203.0.113.5:(translated source port), and reverse the translation to 192.168.1.30:40000. To make late replies work, send keepalive packets from the host more often than the timeout, or raise the UDP timeout on the gateway (the net.netfilter.nfconntrackudp_timeout sysctl).
Exercise
You change a MASQUERADE rule to a different outgoing interface, but an existing download from 192.168.1.20 still uses the old translation. Why, and how would you check and fix it?
Show answer
The first packet of that connection created a conntrack entry, and later packets are translated from the entry without re-evaluating the nat table. Check it with "sudo conntrack -L -p tcp" and look at the reply tuple for the old address. Fix it by ending the connection or deleting its entry with "sudo conntrack -D -s 192.168.1.20", so that the next connection is evaluated against the new rule.