Sub topic 3
Hairpin NAT and NAT Edge Cases
This chapter assumes basic IPv4 addressing, default gateways, TCP/UDP ports, and Linux shell commands. You should also know that a NAT device rewrites packet addresses and keeps connection state.
Hairpin NAT
Hairpin NAT, also called NAT loopback, lets a client inside a private network reach an internal service through the network's public address. For example, a laptop at 192.168.1.20 connects to 203.0.113.5:8080. The gateway must:
- Rewrite the destination to
192.168.1.10:80. - Rewrite the source so the server replies through the gateway.
- Reverse both translations in the reply.
Without the source rewrite, the server may reply directly to the laptop. The laptop then receives a reply from an unexpected address and rejects the connection.
# Forward the public address to the internal web server
sudo iptables -t nat -A PREROUTING -d 203.0.113.5 -p tcp --dport 8080 \
-j DNAT --to-destination 192.168.1.10:80
# Ensure the server replies through the gateway
sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 \
-d 192.168.1.10 -p tcp --dport 80 -j MASQUERADETroubleshooting Port Forwarding
Test from outside the NAT device. First confirm that the service listens:
sudo ss -ltn 'sport = :80'
curl -v http://203.0.113.5:8080/If local access works but the outside test fails, check the forwarding rule, the gateway firewall, the server firewall, and the server's default gateway. Test hairpin access separately because some gateways do not support it.
Protocols and NAT Behavior
NAT works best when addresses and ports stay in packet headers. Protocols that embed addresses in their payload, such as some file-transfer and voice protocols, may need an application helper or a modern proxy.
NAT mapping behavior determines whether the same outside endpoint receives the same translated port. Filtering behavior determines which unsolicited replies are accepted. Strict mappings and filters make peer-to-peer connections harder.
NAT Traversal and Provider NAT
UPnP can ask a home gateway to create a port forward. STUN tells a device which public address and port it appears to use. Hole punching uses those mappings for peer-to-peer traffic. A relay carries traffic through a public server when direct communication fails.
Carrier-grade NAT (CGNAT) places many customers behind one provider address. If your gateway's WAN address differs from the address shown by an external service, inbound port forwarding may be impossible without provider support.
NAT and IPv6
IPv6 provides globally routable addresses, so it does not need NAT for address conservation. Firewalls still control inbound traffic. Some networks use IPv6-to-IPv4 translation, but that is a compatibility mechanism rather than the normal IPv6 design.
Exercise
Why does hairpin NAT need a source-address rewrite?
Show answer
It makes the internal server send its reply through the gateway, allowing the gateway to reverse the destination and source translations.