IPsec and IKEv2: AH, ESP, NAT Traversal, and WireGuard
Network-layer security with IPsec: security associations and policies, the IKEv2 key exchange (captured and explained), AH and ESP in transport and tunnel modes, replay protection, NAT traversal over UDP 4500, rekeying, and WireGuard as the modern minimal alternative, all run in the lab.
kvi5hnuCode Sprout team member22 min readOn this page
TLS protects one application's connection. IPsec protects IP packets themselves, so every application between two hosts or two networks is covered without changing any of them. It's the classic technology for site-to-site VPNs (virtual private networks: private links built across the public internet), for remote-access VPNs, and for protecting traffic between routers. It's also big: an architecture (RFC 4301), two packet formats (AH and ESP, described below), a key exchange protocol (IKEv2, RFC 7296), and many algorithms and extensions. This article runs each piece in the course lab with strongSwan and the Linux kernel's IPsec implementation, and ends with WireGuard, a much smaller design that does a similar job.
The IPsec architecture
IPsec can run on a host, protecting its own traffic, or on a security gateway (SG) that protects traffic for a network behind it. The three common deployments are host to host, host to gateway (a laptop connecting to the office), and gateway to gateway (two offices connected over the internet). Implementations can be built into the IP stack, inserted as a driver below it ("bump in the stack"), or placed in a separate inline box ("bump in the wire").
Three databases decide what happens to each packet:
- The security policy database (SPD) says, for each kind of traffic, whether to protect it, let it bypass IPsec, or discard it. Policies match on traffic selectors: addresses, protocol and ports.
- The security association database (SAD) holds the active security associations (SAs). An SA is a one-way agreement: algorithms, keys, sequence numbers and lifetime for traffic in one direction. Each SA is identified by a 32-bit security parameter index (SPI) carried in every packet. Two-way traffic needs a pair of SAs.
- The peer authorization database (PAD) says which peers may authenticate, how, and which traffic selectors each may ask for.
The lab builds two sites: 10.1.0.0/24 behind gateway gw1 (198.51.100.1) and 10.2.0.0/24 behind gw2 (203.0.113.2), with a router between them standing in for the internet. Once strongSwan has loaded its configuration, gw1's kernel already has policies, before any SA exists:
src 10.1.0.0/24 dst 10.2.0.0/24
dir out priority 375424 ptype main
tmpl src 198.51.100.1 dst 203.0.113.2
src 10.2.0.0/24 dst 10.1.0.0/24
dir fwd priority 375424 ptype main
tmpl src 203.0.113.2 dst 198.51.100.1
src 10.2.0.0/24 dst 10.1.0.0/24
dir in priority 375424 ptype main
tmpl src 203.0.113.2 dst 198.51.100.1
Each policy has a src/dst selector, a direction, and a tmpl (template) line that names the outer addresses of the SA that must carry the traffic. Traffic from 10.1.0.0/24 to 10.2.0.0/24 must leave (dir out) through a tunnel from 198.51.100.1 to 203.0.113.2, and traffic arriving the other way must have come through it (dir in, and dir fwd for traffic being routed on to the LAN). The configuration used start_action = trap: the first matching packet triggers key negotiation. So the first ping is dropped while IKE (the key exchange, next section) runs, and the rest go through:
64 bytes from 10.2.0.10: icmp_seq=2 ttl=62 time=0.236 ms
64 bytes from 10.2.0.10: icmp_seq=3 ttl=62 time=0.333 ms
64 bytes from 10.2.0.10: icmp_seq=4 ttl=62 time=0.311 ms
4 packets transmitted, 3 received, 25% packet loss, time 927ms
IKEv2: negotiating the SAs
Manually configured keys never change and don't scale, so SAs are almost always created by the Internet Key Exchange protocol, version 2 (IKEv2, RFC 7296). IKE runs over UDP port 500 (and 4500, below). It first builds an IKE SA, an authenticated, encrypted control channel between the two peers, and then uses it to create child SAs for the data. Here's the whole lifetime of the lab tunnel, captured on the router:
4 198.51.100.1 -> 203.0.113.2 UDP 500 274 bytes IKE_SA_INIT msg 0 request SA KE Nonce N×5
5 203.0.113.2 -> 198.51.100.1 UDP 500 282 bytes IKE_SA_INIT msg 0 response SA KE Nonce N×6
6 198.51.100.1 -> 203.0.113.2 UDP 4500 373 bytes IKE_AUTH msg 1 request SK
7 203.0.113.2 -> 198.51.100.1 UDP 4500 286 bytes IKE_AUTH msg 1 response SK
16 198.51.100.1 -> 203.0.113.2 UDP 4500 283 bytes CREATE_CHILD_SA msg 2 request SK
17 203.0.113.2 -> 198.51.100.1 UDP 4500 271 bytes CREATE_CHILD_SA msg 2 response SK
18 198.51.100.1 -> 203.0.113.2 UDP 4500 115 bytes INFORMATIONAL msg 3 request SK
19 203.0.113.2 -> 198.51.100.1 UDP 4500 115 bytes INFORMATIONAL msg 3 response SK
24 198.51.100.1 -> 203.0.113.2 UDP 4500 111 bytes INFORMATIONAL msg 4 request SK
25 203.0.113.2 -> 198.51.100.1 UDP 4500 103 bytes INFORMATIONAL msg 4 response SK
Each line is one packet: frame number, addresses, UDP port, size, the exchange type, its message ID, whether it's a request or response, and the payloads it carries (N×5 means five Notify payloads; SK means everything is encrypted). The diagram below shows the same exchanges as a ladder.

Every IKE message starts with a header holding both peers' IKE SPIs (8 bytes each), the next payload type, the version (2.0), the exchange type, flags (initiator, response) and a message ID. Messages are requests and responses: the initiator of each exchange retransmits until it gets a response, and the message ID matches the two and protects against replays. A sequence of payloads follows, each with a generic header (next payload, a critical bit, length). strongSwan's log names them:
generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
parsed IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(CHDLESS_SUP) N(MULT_AUTH) ]
selected proposal: IKE:AES_GCM_16_256/PRF_HMAC_SHA2_384/CURVE_25519
authentication of 'gw1.example.com' (myself) with pre-shared key
generating IKE_AUTH request 1 [ IDi N(INIT_CONTACT) IDr AUTH SA TSi TSr N(MOBIKE_SUP) N(ADD_4_ADDR) N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]
parsed IKE_AUTH response 1 [ IDr AUTH SA TSi TSr N(MOBIKE_SUP) N(ADD_4_ADDR) ]
authentication of 'gw2.example.com' with pre-shared key successful
IKE_SA site[1] established between 198.51.100.1[gw1.example.com]...203.0.113.2[gw2.example.com]
selected proposal: ESP:AES_GCM_16_256/NO_EXT_SEQ
CHILD_SA net{2} established and TS 10.1.0.0/24 === 10.2.0.0/24
generating CREATE_CHILD_SA request 2 [ N(REKEY_SA) SA No KE TSi TSr ]
parsed CREATE_CHILD_SA response 2 [ SA No KE TSi TSr ]
selected proposal: ESP:AES_GCM_16_256/CURVE_25519/NO_EXT_SEQ
inbound CHILD_SA net{3} established and TS 10.1.0.0/24 === 10.2.0.0/24
outbound CHILD_SA net{3} established and TS 10.1.0.0/24 === 10.2.0.0/24
generating INFORMATIONAL request 3 [ D ]
parsed INFORMATIONAL response 3 [ D ]
generating INFORMATIONAL request 4 [ D ]
parsed INFORMATIONAL response 4 [ ]
The brackets list each message's payloads in order. No is the nonce, and each N(...) is a Notify payload with its type, for example NATD_S_IP for NAT detection. The selected proposal lines show the algorithms both sides agreed on.
IKE_SA_INIT
The first exchange is in the clear. Here's the initiator's request, decoded by tshark:
Initiator SPI: cb01b6c3424f2bb5
Responder SPI: 0000000000000000
Exchange type: IKE_SA_INIT (34)
Message ID: 0x00000000
payload: Security Association (33)
transform (ENCR): AES-GCM with a 16 octet ICV (20)
transform (PRF): PRF_HMAC_SHA2_384 (6)
transform (D-H): Curve25519 (31)
payload: Key Exchange (34)
group: Curve25519 (31)
key exchange data: 92fdf3e7514c7223… (32 bytes)
payload: Nonce (40)
nonce: 0eeccc9355ee6371… (32 bytes)
payload: Notify (41) - NAT_DETECTION_SOURCE_IP
payload: Notify (41) - NAT_DETECTION_DESTINATION_IP
payload: Notify (41) - IKEV2_FRAGMENTATION_SUPPORTED
payload: Notify (41) - SIGNATURE_HASH_ALGORITHMS
payload: Notify (41) - REDIRECT_SUPPORTED
- The responder's SPI is zero: the responder hasn't picked one yet.
- The SA payload carries one or more proposals, each a list of transforms: an encryption algorithm (here AES-GCM with a 256-bit key, article 79), a pseudorandom function (HMAC-SHA-384), and a key exchange group (Curve25519). An integrity algorithm would also be listed if the cipher weren't AEAD. The responder picks exactly one combination.
- KE is the initiator's Diffie-Hellman public value (32 bytes for X25519), and the nonce adds fresh randomness from each side.
- Notify (N) payloads carry status and capabilities: NAT detection hashes, support for IKE fragmentation (RFC 7383), the signature hashes it accepts, support for redirection to another gateway.
From the nonces and the shared Diffie-Hellman secret, both sides compute a seed, SKEYSEED, and derive the IKE SA's keys from it: SK_d (for deriving child SA keys), SK_ai/SK_ar (integrity, unused with AEAD), SK_ei/SK_er (encryption) and SK_pi/SK_pr (used in authentication). If the responder doesn't like the proposed group, it answers with INVALID_KE_PAYLOAD and the initiator retries with a supported one. Under a flood of fake requests, a responder can demand a COOKIE first, so it doesn't spend CPU and memory until the initiator proves it can receive packets at its claimed address.
IKE_AUTH
Everything after IKE_SA_INIT travels inside an encrypted SK payload, which is why the capture only shows "SK". The log shows what was inside:
- IDi and IDr: the identities (
gw1.example.com,gw2.example.com). - AUTH: proof of identity, a signature or MAC over the first message, the peer's nonce and the identity. The lab uses a pre-shared key. Production gateways usually sign with certificates (article 80), and remote-access VPNs often authenticate users with EAP inside IKE (article 81), with the gateway authenticating itself by certificate. RFC 5998 also allows EAP-only mutual authentication.
- SA, TSi and TSr: the proposal and traffic selectors for the first child SA. The initiator proposes ranges of addresses, ports and protocols, and the responder can narrow them to what its policy allows.
- Further notifications: support for MOBIKE (RFC 4555), which lets a peer change its IP address without rebuilding the SA, as phones do when switching between Wi-Fi and cellular.
A CP (configuration) payload can also appear here. Remote-access clients use it to request an internal IP address and DNS servers from the gateway.
After two round trips, the IKE SA and the first child SA both exist:
site: #1, ESTABLISHED, IKEv2, cb01b6c3424f2bb5_i* 01f3b4988a1366f5_r
local 'gw1.example.com' @ 198.51.100.1[4500]
remote 'gw2.example.com' @ 203.0.113.2[4500]
AES_GCM_16-256/PRF_HMAC_SHA2_384/CURVE_25519
established 1s ago, rekeying in 14072s
net: #2, reqid 1, INSTALLED, TUNNEL, ESP:AES_GCM_16-256
installed 1s ago, rekeying in 3488s, expires in 3959s
in c09ab88b, 252 bytes, 3 packets, 1s ago
out c9b43866, 252 bytes, 3 packets, 1s ago
local 10.1.0.0/24
remote 10.2.0.0/24
The * marks this side's SPI. The child SA net is a tunnel-mode ESP SA with an inbound and an outbound SPI, each counting bytes and packets. Here are the same SAs as the kernel holds them:
src 198.51.100.1 dst 203.0.113.2
proto esp spi 0xc9b43866 reqid 1 mode tunnel
replay-window 0 flag af-unspec
aead rfc4106(gcm(aes)) 0x(36-byte key hidden) 128
lastused 2026-11-20 23:55:50
anti-replay context: seq 0x0, oseq 0x3, bitmap 0x00000000
dir out
src 203.0.113.2 dst 198.51.100.1
proto esp spi 0xc09ab88b reqid 1 mode tunnel
replay-window 32 flag af-unspec
aead rfc4106(gcm(aes)) 0x(36-byte key hidden) 128
lastused 2026-11-20 23:55:50
anti-replay context: seq 0x3, oseq 0x0, bitmap 0x00000007
dir in
The 36-byte AES-GCM key is 32 bytes of key plus a 4-byte salt that forms part of the nonce, and the 128 after it is the ICV length in bits. On the outbound SA, oseq 0x3 counts the 3 packets sent; on the inbound SA, seq 0x3 is the highest sequence number received. The inbound SA has a replay window of 32 packets, and its bitmap (0x7, binary 111, one bit per recent sequence number) shows that it has seen sequence numbers 1 to 3.
CREATE_CHILD_SA and INFORMATIONAL
SAs have lifetimes, by time or by data volume, and are rekeyed before they expire. A CREATE_CHILD_SA exchange creates a new child SA, rekeys an existing one, or rekeys the IKE SA itself. The lab forced one:
rekey completed successfully
net: #2, reqid 1, DELETED, TUNNEL, ESP:AES_GCM_16-256
in c09ab88b, 336 bytes, 4 packets, 2s ago
out c9b43866, 252 bytes, 3 packets, 4s ago
net: #3, reqid 1, INSTALLED, TUNNEL, ESP:AES_GCM_16-256/CURVE_25519
in c2c4591a, 168 bytes, 2 packets, 0s ago
out cfc21ba5, 168 bytes, 2 packets, 0s ago
terminate completed successfully
The rekey carried a fresh KE payload, so the new child SA's keys come from a new Diffie-Hellman exchange (CURVE_25519 now appears in its algorithms): forward secrecy for the data, not just for the IKE SA. The old SA was deleted with an INFORMATIONAL exchange carrying a Delete (D) payload. INFORMATIONAL exchanges also carry error notifications and serve as liveness checks (dead peer detection): an empty request that must be answered. Terminating the tunnel sent two more Delete exchanges, one for the child SA and one for the IKE SA.
An extension called better-than-nothing security (BTNS, RFC 5386) allows unauthenticated IPsec, accepting any peer's key, to protect against passive eavesdropping where no credentials exist. It saw little use.
ESP and AH
IPsec has two packet formats, and each can be used in two modes:

- Transport mode inserts the IPsec header after the original IP header and protects the payload. It's for host-to-host protection.
- Tunnel mode wraps the entire original packet inside a new IP packet between the SA endpoints. It's what gateways use, and it also hides the inner addresses.
ESP
The Encapsulating Security Payload (ESP, RFC 4303, IP protocol 50) provides confidentiality, integrity and replay protection. Its header is just the SPI and a 32-bit sequence number; then come the IV (for GCM, 8 bytes), the encrypted payload, a trailer with padding, a pad-length byte and a next header byte (which says what the payload is: 4 for an IPv4 packet in tunnel mode, 6 for TCP in transport mode), and the integrity check value (ICV). The lab's tunnel packets:
8 198.51.100.1 -> 203.0.113.2 proto 50 154 bytes SPI 0xc9b43866 seq 1
9 203.0.113.2 -> 198.51.100.1 proto 50 154 bytes SPI 0xc09ab88b seq 1
10 198.51.100.1 -> 203.0.113.2 proto 50 154 bytes SPI 0xc9b43866 seq 2
11 203.0.113.2 -> 198.51.100.1 proto 50 154 bytes SPI 0xc09ab88b seq 2
12 198.51.100.1 -> 203.0.113.2 proto 50 154 bytes SPI 0xc9b43866 seq 3
13 203.0.113.2 -> 198.51.100.1 proto 50 154 bytes SPI 0xc09ab88b seq 3
14 198.51.100.1 -> 203.0.113.2 proto 50 154 bytes SPI 0xc9b43866 seq 4
15 203.0.113.2 -> 198.51.100.1 proto 50 154 bytes SPI 0xc09ab88b seq 4
The SPI tells the receiver which SA to use, and the sequence number counts up from 1. Each 154-byte frame carries one 84-byte ping packet. The sizes add up like this: the 84-byte inner packet plus the 2 trailer bytes is 86, padded to a multiple of 4 gives 88; then 88 + 16 (ICV) + 8 (IV) + 8 (SPI and sequence number) = 120 bytes of ESP; plus a 20-byte outer IP header = 140; plus the 14-byte Ethernet header = 154. An observer learns the gateways' addresses, the SPIs and the packet sizes, but not the inner addresses, protocol or content. Inside the tunnel, the hosts see ordinary packets:
23:55:51.572186 IP 10.1.0.10 > 10.2.0.10: ICMP echo request, id 232, seq 1, length 64
23:55:51.572195 IP 10.2.0.10 > 10.1.0.10: ICMP echo reply, id 232, seq 1, length 64
The extended sequence number (ESN) option uses 64-bit counters (only the low 32 bits are sent), so fast links don't need rekeying just because the counter would wrap. The current algorithm requirements are in RFC 8221: AES-GCM and ChaCha20-Poly1305 are recommended, and DES, 3DES and MD5 are gone. IP-TFS (RFC 9347) adds traffic flow confidentiality by sending fixed-size, fixed-rate packets that hide traffic patterns.
AH
The Authentication Header (AH, RFC 4302, IP protocol 51) provides integrity and replay protection, but no encryption. Its distinguishing feature is that it also authenticates most of the outer IP header: everything except fields that legitimately change in transit (TTL or hop limit, the header checksum, and a few others), which are treated as zero for the computation. The lab set up manual transport-mode SAs between two hosts, one with AH and one with ESP, and sent one ping containing the text SECRET-PIN-1234 with each:
none frame 98 bytes IP 84 ICMP Echo (ping) request id=0x0034, seq=1/256, ttl=64
payload text visible on the wire: yes
ah frame 130 bytes IP 116 ICMP Echo (ping) request id=0x004c, seq=1/256
payload text visible on the wire: yes
esp frame 134 bytes IP 120 ESP ESP (SPI=0x00001001)
payload text visible on the wire: no
With AH, the ICMP packet is still readable on the wire. Only ESP hides it. The AH header itself:
Next header: ICMP (1)
Length: 6 (32 bytes)
AH SPI: 0x00001001
AH Sequence: 1
AH ICV: e6a1825d…
Internet Control Message Protocol
Its length field counts 32-bit words minus 2, so 6 means (6 + 2) × 4 = 32 bytes: 12 fixed bytes (next header, length, reserved, SPI, sequence number), a 16-byte truncated HMAC-SHA-256 ICV, and 4 bytes of padding. Because AH covers the source address, any NAT on the path breaks it. ESP can authenticate without encrypting, too (with the NULL cipher, RFC 2410), and protects everything except the outer IP header, which is rarely worth protecting anyway. So AH is now optional for IPsec implementations and rarely used. Wrapped ESP (WESP, RFC 5840) adds a small header that lets firewalls and intrusion detection systems recognize ESP-NULL traffic and inspect it, which plain ESP doesn't let them distinguish from encrypted traffic.
Replay protection
An attacker who records an ESP packet can resend it. The receiver keeps a sliding anti-replay window of recently seen sequence numbers and drops duplicates and packets that are too old. The lab captured one ESP packet on its way to the receiver and injected three more copies of it:
before: anti-replay context: seq 0x1, oseq 0x0, bitmap 0x00000001
captured one ESP echo request on the way to b, then sent 3 more copies of it
after: anti-replay context: seq 0x2, oseq 0x0, bitmap 0x00000003
XfrmInStateSeqError 3
The bitmap goes from 0x1 (binary 01) to 0x3 (binary 11): two packets accepted (the earlier test and this one), and the kernel's XfrmInStateSeqError counter shows the three replays rejected. The packets were valid ciphertext with a correct ICV; only the sequence number check stopped them.
NAT traversal
ESP has no ports, so a NAT that multiplexes many hosts behind one address has nothing to translate, and AH breaks outright when addresses change. NAT traversal (RFC 3947 for detection and RFC 3948 for encapsulation; NAT itself is in article 35) solves this. In IKE_SA_INIT, each side sends NAT_DETECTION_SOURCE_IP and NAT_DETECTION_DESTINATION_IP notifications containing hashes of the addresses and ports it believes it's using. If the receiver's hash of what it actually sees doesn't match, there's a NAT in between. Both sides then switch IKE to UDP port 4500 and wrap ESP in UDP on the same port.
The lab put a laptop at 10.0.0.10 behind a NAT router (198.51.100.1) and had it connect to gw2:
generating IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(REDIR_SUP) ]
parsed IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(CHDLESS_SUP) N(MULT_AUTH) ]
local host is behind NAT, sending keep alives
On the internet side of the NAT:
4 198.51.100.1:500 -> 203.0.113.2:500 274 bytes ISAKMP IKE_SA_INIT MID=00 Initiator Request
5 203.0.113.2:500 -> 198.51.100.1:500 282 bytes ISAKMP IKE_SA_INIT MID=00 Responder Response
6 198.51.100.1:4500 -> 203.0.113.2:4500 372 bytes ISAKMP IKE_AUTH MID=01 Initiator Request
7 203.0.113.2:4500 -> 198.51.100.1:4500 286 bytes ISAKMP IKE_AUTH MID=01 Responder Response
8 198.51.100.1:4500 -> 203.0.113.2:4500 162 bytes ESP ESP
9 203.0.113.2:4500 -> 198.51.100.1:4500 162 bytes ESP ESP
10 198.51.100.1:4500 -> 203.0.113.2:4500 162 bytes ESP ESP
11 203.0.113.2:4500 -> 198.51.100.1:4500 162 bytes ESP ESP
IKE started on port 500, then moved to 4500, and the ESP packets travel as UDP datagrams on port 4500, which the NAT can track like any other UDP flow. The responder sees the NAT's public address, not the laptop's private one:
site: #1, ESTABLISHED, IKEv2, 658c14b80d6d3b25_i 0f6cfb77fbdfdaf8_r*
local 'gw2.example.com' @ 203.0.113.2[4500]
remote 'laptop.example.com' @ 198.51.100.1[4500]
AES_GCM_16-256/PRF_HMAC_SHA2_384/CURVE_25519
net: #1, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_GCM_16-256
installed 2s ago, rekeying in 3244s, expires in 3958s
in c5199b4e, 168 bytes, 2 packets, 1s ago
out c62ca7be, 168 bytes, 2 packets, 1s ago
The mode is TUNNEL-in-UDP. Each packet costs 8 more bytes for the UDP header:
frame 162 bytes, outer IP 148, UDP length 128, then ESP SPI 0xc5199b4e seq 1
On port 4500, IKE messages begin with four zero bytes (a non-ESP marker) so the receiver can tell them from ESP packets, whose SPI is never zero. The side behind the NAT sends one-byte keepalives (every 20 seconds by default in strongSwan) so the NAT doesn't forget the mapping. Where even UDP is blocked, RFC 9329 defines carrying IKE and ESP over TCP, usually on port 4500 or 443.
Notice also that in the lab without NAT, strongSwan still moved IKE_AUTH to port 4500. RFC 7296 allows that, and it avoids problems with middleboxes that treat port 500 specially. ESP stayed as native protocol 50 because no NAT was detected.
Multicast and L2TP/IPsec
IPsec SAs are normally between two peers, but a group of receivers can share an SA for multicast traffic. A group controller and key server hands out the group keys using the Group Domain of Interpretation (GDOI, RFC 6407), which is based on IKEv1; RFC 9838 (November 2025) replaces it with group key management over IKEv2 (G-IKEv2), and the SAs use multicast destination addresses. This is used in some private WANs (wide area networks linking an organization's sites) and broadcast systems.
L2TP/IPsec (RFC 3193) carries the Layer 2 Tunneling Protocol, and through it PPP sessions with user authentication and address assignment, inside transport-mode ESP. It was the built-in VPN in Windows, macOS and older phones for many years. IKEv2 with EAP and configuration payloads does the same job more directly, and most platforms are phasing L2TP out.
Post-quantum IPsec
IKEv2's key exchange can be hybridized like TLS's. RFC 9370 lets the peers run up to seven additional key exchanges after IKE_SA_INIT, in new IKE_INTERMEDIATE exchanges (RFC 9242), which also solves the problem that a post-quantum public key doesn't fit in an unfragmented IKE_SA_INIT packet. Using ML-KEM in IKEv2 this way is specified in an IETF draft that has been approved and is waiting for publication as an RFC, and strongSwan 6 already implements it. RFC 8784 offers a stopgap: mixing a post-quantum preshared key (PPK) into the derivation, which protects against future quantum attacks if the PPK stays secret.
WireGuard
WireGuard (in Linux since 5.6, March 2020, and available on every major platform) takes the opposite approach to IPsec: no negotiation, one fixed set of algorithms, and a few thousand lines of kernel code. Each peer has a Curve25519 key pair, and you configure each side with the other's public key, its endpoint, and the allowed IPs it may use:
a public key: CJQE95B3Byr/oFArcp2zDyU0+TYMV0XFVEDU7rM9BVI= (32 bytes, base64)
b public key: +P2nYMKL4sgaA4N/EDOEOFr/3l0mRFYMzF/4MHArsQ8=
interface: wg0
public key: CJQE95B3Byr/oFArcp2zDyU0+TYMV0XFVEDU7rM9BVI=
private key: (hidden)
listening port: 51820
peer: +P2nYMKL4sgaA4N/EDOEOFr/3l0mRFYMzF/4MHArsQ8=
endpoint: 198.51.100.2:51820
allowed ips: 10.99.0.2/32
The allowed IPs list does double duty, which WireGuard calls cryptokey routing: outgoing packets to 10.99.0.2 are encrypted to that peer, and incoming packets decrypted with that peer's key are accepted only if their inner source address is in its list. That replaces IPsec's SPD and traffic selectors.
The first packet to the peer triggers a handshake, based on the Noise IK pattern (one of the handshake recipes of the Noise protocol framework, in which the initiator already knows the responder's static key), with no algorithm negotiation:
1 198.51.100.1 -> 198.51.100.2 frame 190, UDP payload 148 Handshake Initiation sender 0xff4483d2
2 198.51.100.2 -> 198.51.100.1 frame 134, UDP payload 92 Handshake Response sender 0x89b0496e receiver 0xff4483d2
3 198.51.100.1 -> 198.51.100.2 frame 170, UDP payload 128 Transport Data receiver 0x89b0496e counter 0
4 198.51.100.2 -> 198.51.100.1 frame 170, UDP payload 128 Transport Data receiver 0xff4483d2 counter 0
5 198.51.100.1 -> 198.51.100.2 frame 170, UDP payload 128 Transport Data receiver 0x89b0496e counter 1
6 198.51.100.2 -> 198.51.100.1 frame 170, UDP payload 128 Transport Data receiver 0xff4483d2 counter 1
sender and receiver are the random 32-bit indexes each side picked, which play the role of IPsec's SPIs. Each Transport Data frame is 170 bytes: the 84-byte ping padded to 96, plus the 16-byte header and the 16-byte tag, gives the 128-byte UDP payload; add 8 (UDP), 20 (IP) and 14 (Ethernet).
- Handshake Initiation, 148 bytes: a type, the sender's random 32-bit index, an ephemeral Curve25519 public key, the sender's static public key (encrypted), an encrypted timestamp (which defeats replay of old initiations), and two MACs. mac1, keyed with the responder's public key, lets the responder discard junk cheaply. mac2 is used only under load: the responder replies with a Cookie Reply instead of processing the handshake, and the initiator must return the cookie, much like IKE's COOKIE.
- Handshake Response, 92 bytes: the responder's index, the initiator's index, its own ephemeral key, an empty encrypted payload that proves it derived the keys, and the MACs.
- Transport Data: a 16-byte header (type, the receiver's index and a 64-bit counter, which serves as the nonce and for replay protection), then the packet encrypted with ChaCha20-Poly1305, padded to a multiple of 16 bytes, with a 16-byte tag.
Hashing uses BLAKE2s, a fast modern hash function. Keys are renegotiated every two minutes, and peers that have nothing to send stay silent, so a WireGuard interface is invisible to scanners: it never answers a packet that doesn't carry a valid MAC for its key. After the pings:
interface: wg0
public key: CJQE95B3Byr/oFArcp2zDyU0+TYMV0XFVEDU7rM9BVI=
private key: (hidden)
listening port: 51820
peer: +P2nYMKL4sgaA4N/EDOEOFr/3l0mRFYMzF/4MHArsQ8=
endpoint: 198.51.100.2:51820
allowed ips: 10.99.0.2/32
latest handshake: 1 second ago
transfer: 476 B received, 532 B sent
WireGuard carries roaming built in: if an authenticated packet arrives from a new address, the peer's endpoint is updated. It doesn't do user authentication, address assignment or certificate management. Products such as Tailscale and many commercial VPNs add those on top. Its fixed algorithms are also a deliberate trade-off: changing them means a new protocol version.
Here's what each scheme measured in this article costs for one small packet:

Overhead matters mostly for MTU: a tunnel that adds 60 to 80 bytes to every packet reduces the path MTU, and if path MTU discovery is broken (article 47), large packets vanish. That's why WireGuard interfaces default to an MTU of 1420 bytes (wg-quick sets the outgoing link's MTU minus 80), and why gateways often clamp TCP's MSS for tunneled traffic.
Common questions
Should I use IPsec or WireGuard?
For new VPNs between systems you control, WireGuard is simpler to configure, audit and run. IPsec is the choice for interoperability with existing routers, firewalls and phones' built-in clients, for certificate- or EAP-based user authentication, for standards compliance, or for hardware offload in network equipment.
Why did IKE_AUTH use port 4500 when there was no NAT?
IKEv2 allows switching to port 4500 after IKE_SA_INIT, and strongSwan does it routinely, which helps with middleboxes that interfere with port 500. Only ESP's encapsulation depends on NAT detection.
Does IPsec hide which websites I visit?
Through a tunnel to a VPN gateway, the network between you and the gateway sees only encrypted packets to the gateway. The gateway, and everything beyond it, sees your traffic as usual (protected only by TLS, if used).
Why is IKE on UDP rather than TCP?
IKE has its own retransmission and only a few messages, and UDP lets it work with NAT and avoids TCP's state and connection setup. Large messages (certificates, post-quantum keys) are handled by IKE fragmentation instead of IP fragmentation, which NATs and firewalls often drop.
What is IKEv1, and should I still see it?
The original 1998 protocol, with Main Mode, Aggressive Mode and Quick Mode. It's more complex, has known weaknesses with pre-shared keys in Aggressive Mode, and is deprecated (RFC 9395). Disable it wherever possible.
Can IPsec protect IPv6 neighbor discovery or routing protocols?
In principle, with manual SAs, since IKE can't run before addresses work. In practice, OSPFv3 uses IPsec AH or ESP with manual keys or its own authentication trailer, and SEND (secure neighbor discovery) never saw deployment.
Summary
- IPsec protects IP packets using policies (SPD), security associations (SAD, identified by SPIs) and a peer authorization database. SAs are one-way; a two-way tunnel needs a pair.
- IKEv2 sets up SAs in two round trips: IKE_SA_INIT (proposals, X25519 key exchange, nonces, NAT detection, in the clear) and IKE_AUTH (identities, authentication, traffic selectors, encrypted). CREATE_CHILD_SA rekeys, with a new key exchange for forward secrecy; INFORMATIONAL deletes SAs and checks liveness.
- ESP (protocol 50) encrypts and authenticates; AH (protocol 51) only authenticates, includes the IP header, breaks with NAT and is rarely used. The lab's AH ping was readable on the wire; ESP's wasn't.
- Tunnel mode wraps whole packets for gateways; transport mode protects host-to-host payloads. Sequence numbers and the replay window rejected three replayed packets.
- NAT traversal detects NATs with hashed addresses in IKE_SA_INIT and moves IKE and ESP to UDP port 4500, at 8 bytes per packet.
- WireGuard uses fixed algorithms (Curve25519, ChaCha20-Poly1305, BLAKE2s), a 148-byte and 92-byte handshake, cryptokey routing, and silence towards unauthenticated packets.
Practice questions
1. An ESP tunnel uses AES-GCM with an 8-byte IV and a 16-byte ICV. How big is the outer IPv4 packet for an inner 1,400-byte packet?
Answer
Outer IP header 20 + ESP header 8 + IV 8 + payload (1,400 + 2 trailer bytes = 1,402, padded to a multiple of 4: 1,404) + ICV 16 = 1,456 bytes. Inside a 1,500-byte MTU that fits, but an inner packet of 1,460 bytes wouldn't (20 + 8 + 8 + 1,464 + 16 = 1,516).
2. Why does IPsec need two SAs for one tunnel, and how does the receiver pick the right one for an incoming packet?
Answer
An SA is one-way: each direction has its own keys and sequence numbers. The receiver looks up the SA by the SPI in the packet (together with the destination address and protocol); it chose that SPI itself when the SA was negotiated, so it's unique on that receiver.
3. Two hosts behind the same NAT both open IPsec tunnels to the same gateway using native ESP. What goes wrong, and how does NAT traversal fix it?
Answer
Both flows reach the gateway from the same public address, and ESP has no ports, so the NAT can't tell which inside host a returning ESP packet belongs to. With NAT-T, ESP is wrapped in UDP, and each host's UDP 4500 flow gets its own external port mapping, so the NAT can demultiplex replies like any UDP traffic.
4. A gateway receives ESP packets with sequence numbers 100, 101, 103, 102, 101 and 40, with a 32-packet replay window. Which are accepted?
Answer
100, 101, 103 and 102 (102 arrived out of order but within the window and not yet seen). The second 101 is a duplicate, and 40 is older than the window's lower edge (103 − 32 = 71), so both are dropped.
5. Why does a WireGuard peer that is configured but idle never respond to a port scan?
Answer
It processes only messages with a valid mac1, which requires knowing its public key, and it never sends error messages. A scanner's probe is silently discarded, so the port looks closed or filtered.
6. A security policy says "protect 10.1.0.0/24 ⇄ 10.2.0.0/24." A host in 10.1.0.0/24 pings 10.3.0.5. What happens?
Answer
No protect policy matches, so the packet follows the default (in the lab, bypass), and it's routed normally, unencrypted, toward its destination. If the policy set ended with a discard rule for everything else, it would be dropped. That's why VPN configurations that must not leak use a "protect or discard" policy for all traffic.
Previous: Network Access Control: 802.1X, EAP and MACsec
Next: TLS 1.3: The Handshake, Record Protocol, 0-RTT, ECH and DTLS

More in TCP/IP Course
Quiz: TCP/IP Delicate Details
Twenty-five questions on the details that catch out experienced engineers: sequence numbers for SYN and FIN, TIME_WAIT versus tcp_fin_timeout, Karn's algorithm, socket buffer doubling, even and odd ephemeral ports, IPv6 checksums and fragmentation, negative DNS caching, and capture filter traps.
Quiz: TCP/IP Interview Questions
Thirty-three networking questions of the kind asked in developer, SRE and network engineering interviews: what happens when you load a URL, TCP versus UDP, handshakes, closing and TIME_WAIT, subnetting, NAT, DNS, MTU problems, congestion, TLS and QUIC, and debugging slow or failing connections.
Quiz: TCP/IP Course Final Exam (All Parts)
The final exam for the TCP/IP course: thirty questions across all fourteen parts, from packets and addressing through Ethernet, ARP, IP, DHCP, NAT, ICMP, UDP, DNS, TCP connections, reliability, congestion control, security, QUIC and troubleshooting.
Quiz: Modern Transports and Troubleshooting (TCP/IP Part 14)
Review modern transports and troubleshooting: QUIC packets, handshakes, 0-RTT, streams and connection migration, HTTP/3, Multipath TCP, SCTP multihoming, and a layered method for diagnosing real network faults.
Discussion
Sign in to ask a question or share what you learned.