Sub topic 13
Getting through NAT: UPnP, STUN, hole punching, and relays
This chapter assumes you know the NAT translation table, source NAT/PAT, port forwarding, and the mapping and filtering behaviors from earlier chapters. You should also be comfortable with TCP and UDP ports and with reading packet captures or conntrack output.
The problem: two peers, no open door
A NAT device creates a mapping only when a host behind it sends traffic out. Inbound packets that match no mapping are dropped. That is fine for a client that contacts a public server. It is a problem for peer-to-peer software such as voice and video calls, online games, file sharing, and remote-access tools, where both endpoints may sit behind different NAT devices.
Neither peer can start the conversation, because neither has a public, reachable address and port. Four techniques solve this in different ways:
| Technique | Who does the work | What it achieves | Needs a third party |
|---|---|---|---|
| UPnP / NAT-PMP / PCP | The application asks the router | Creates a real port forward on demand | No |
| STUN | The application asks a public server | Learns its public address and port | Yes, a STUN server |
| Hole punching | Both peers, coordinated | Opens mappings on both NATs at once | Yes, for signaling |
| Relay (TURN) | A public server forwards the data | Works when nothing else does | Yes, and it carries all traffic |
Real applications try them in order, from cheapest to most expensive, and fall back when one fails.
Asking the router: UPnP, NAT-PMP, and PCP
Universal Plug and Play Internet Gateway Device (UPnP IGD) lets a program on the LAN ask the router to create a port forward. The program discovers the router with multicast SSDP messages, then sends SOAP requests such as AddPortMapping. The router installs a DNAT rule, as if an administrator had configured it by hand.
NAT-PMP (NAT Port Mapping Protocol) and its successor PCP (Port Control Protocol) do the same job with a much simpler binary protocol over UDP. PCP also supports IPv6 firewalls and can work with carrier-grade NAT if the provider supports it.
A mapping request carries four things:
- The internal address and port the service listens on.
- The external port the application would like.
- The protocol, TCP or UDP.
- A lease duration, after which the mapping expires unless it is renewed.
The router may grant a different external port than the one requested, so the application must read the response.
These protocols have limits:
- They work only when the router supports them and has them enabled. Many security guides recommend turning UPnP off.
- Any program on the LAN can open ports without authentication, including malware.
- They cannot help behind carrier-grade NAT, because the ISP's device does not answer the request. The router may even report a private "external" address.
- Multiple devices can compete for the same external port.
Learning your public address with STUN
A host behind NAT usually does not know its public address. Its network interface shows only the private one. STUN (Session Traversal Utilities for NAT, RFC 8489) solves this with a simple exchange:
- The client sends a Binding Request from a local UDP socket to a STUN server on the public internet.
- The server reads the source address and port of the packet as it arrived. These are the values after translation.
- The server returns them in a Binding Response, in a field called XOR-MAPPED-ADDRESS.
The client now knows the public IP:port that the NAT assigned to that socket. This is called the server-reflexive address.
Two details matter:
- The mapping is tied to the local socket. If the application opens a new socket, the NAT may assign a different external port. The same socket must be used for the STUN query and for the later peer traffic.
- The address is only useful if the NAT reuses that mapping for other destinations. That depends on the NAT's mapping behavior.
Why mapping behavior decides the outcome
Recall the behaviors from the previous chapter. With endpoint-independent mapping, the NAT uses the same external IP:port for a given internal socket no matter which destination it talks to. The port that STUN reported is then valid for a peer too. With address-dependent or address-and-port-dependent mapping (often called symmetric NAT), the NAT picks a new external port for each destination. The port that STUN reported works only for the STUN server. A peer who sends to it hits a port that has no mapping, and the packet is dropped.
Hole punching
UDP hole punching uses the fact that an outbound packet creates a mapping and, depending on the filtering behavior, lets replies from that destination back in. If both peers send to each other's public address at about the same time, each NAT sees an outbound packet and creates a mapping that admits the other peer's packets.
The procedure needs a rendezvous server, which both peers can reach, to exchange addresses:
- Peers A and B each use STUN to learn their public
IP:port. - Each peer sends that address to the rendezvous server. The server passes it to the other peer. This step is called signaling.
- A and B each start sending UDP packets to the other's public address.
- A's first packet is probably dropped by B's NAT, but it creates a mapping on A's NAT that permits B's packets.
- B's packets then arrive at A's NAT, match the mapping, and pass. The same happens in the other direction.
- Direct traffic flows. No server is in the data path.
Whether this works depends on the NAT types:
| Peer A NAT | Peer B NAT | Hole punching works? |
|---|---|---|
| Endpoint-independent mapping | Endpoint-independent mapping | Yes |
| Endpoint-independent mapping | Address- or port-dependent mapping | Often, with filtering that allows it |
| Address- or port-dependent mapping | Address- or port-dependent mapping | Usually no, unless the peers guess ports |
Some implementations try to predict the next port when a symmetric NAT allocates ports sequentially. This is unreliable, and port randomization defeats it.
TCP hole punching also exists. Both peers perform a simultaneous open, with each side connecting to the other from the same local port. It works less often than UDP, because it depends on the NAT handling unexpected SYN packets correctly and on both sides reusing the local port (SO_REUSEADDR/SO_REUSEPORT). Many modern systems therefore use UDP-based transports such as QUIC or their own protocol.
Keeping the hole open
NAT mappings expire when idle. UDP mappings often last only 30 seconds to a few minutes. Applications send small keepalive packets, usually every 15 to 25 seconds, to keep the mapping alive. If the keepalive interval is longer than the NAT's timeout, the connection silently dies and must be re-established.
A quick way to watch mappings on a Linux NAT gateway is the connection tracking table:
# Show UDP mappings, including the remaining timeout of each entry
sudo conntrack -L -p udpRun this on the gateway while a peer-to-peer application connects. You can see the original tuple, the reply tuple, and the countdown that shows when the mapping would expire without traffic.
Relays: TURN
When hole punching fails, a relay is the last resort. TURN (Traversal Using Relays around NAT, RFC 8656) is a protocol where a client asks a public server to allocate a relayed address and forward traffic for it.
- The client sends an Allocate request to the TURN server and receives a relayed transport address on the server.
- The client gives that address to its peer through signaling.
- The peer sends data to the relayed address. The server forwards it to the client through the client's own outbound connection to the server.
Because the client initiated the connection to the server, its NAT allows the return traffic. The relay always works, but it has costs. All media passes through the server, so you pay for bandwidth, and latency rises because the path is longer. TURN servers normally require credentials to prevent abuse as open relays.
ICE: putting it together
ICE (Interactive Connectivity Establishment, RFC 8445) is the framework that combines these techniques. WebRTC uses it. Each peer gathers a list of candidates, which are possible addresses where it could be reached:
- Host candidates are the local interface addresses.
- Server-reflexive candidates are the public addresses learned from STUN.
- Relayed candidates are the addresses allocated on a TURN server.
The peers exchange candidate lists through signaling, then test pairs of candidates with STUN checks. They pick the best pair that works, preferring direct paths and using a relay only if nothing else succeeds.
Do not use that line; it is not part of the chapter.
Common errors
- Using a different socket for STUN and for traffic. The NAT assigns a different external port, so the address learned from STUN is wrong.
- Not sending keepalives. The mapping expires and the connection stops after a pause.
- Starting hole punching without timing coordination. If one side sends long before the other, its packet is dropped and no mapping admits the reply, so the exchange must be retried.
- Assuming UPnP works everywhere. It fails on routers with it disabled and behind carrier-grade NAT.
- Omitting a TURN fallback. Roughly one connection in several fails to establish directly in the real world, so a product without a relay will have unreachable users.
- Testing only on one network. Two peers on the same LAN, or both behind permissive NATs, hide failures that appear on mobile and corporate networks.
Exercise
Two peers each learn their public address through STUN and then exchange them through a signaling server. Peer A's NAT uses endpoint-independent mapping. Peer B's NAT assigns a new external port for every destination. Why might A be unable to reach B directly, and what should the application do next?
Show answer
The port that STUN reported for B belongs to the mapping B's NAT created for the STUN server. When B sends to A, its NAT creates a new mapping with a different external port, so A's packets to the STUN-reported port hit no mapping and are dropped. A can learn B's real port only if it sees B's first packet arrive, and A's filtering may block that packet. The application should try the remaining ICE candidate pairs and, if none works, fall back to a TURN relay.
Exercise
A UDP application behind a home NAT works for the first minute and then stops after the users pause talking. Packet captures show no traffic during the pause. What is the likely cause and the fix?
Show answer
The NAT's idle timeout for UDP mappings expired during the pause, so the mapping was removed and incoming packets were dropped. The fix is to send small keepalive packets at an interval shorter than the NAT timeout, commonly every 15 to 25 seconds.