IPsec: AH, ESP and IKE
TLS protects one application connection; IPsec protects IP packets themselves, whatever they carry. It is the classic technology behind site-to-site VPNs between offices, many remote-access VPNs, and the encryption of links between data centres and clouds. For an analyst, IPsec traffic looks like a stream of opaque packets with a few cleartext numbers in front, plus a negotiation (IKE) that reveals a lot about how well the tunnel is configured. This lesson builds and protects an ESP packet in Python, implements the anti-replay check, and reads IKE and ESP in a synthetic capture. VPN designs in general are covered in VPNs and Network Security.
The pieces
| Part | Protocol | Does |
|---|---|---|
| IKEv2 (RFC 7296) | UDP 500, or 4500 with NAT traversal | authenticates the peers (certificates, EAP or pre-shared keys), negotiates algorithms, derives keys, creates security associations (SAs) |
| ESP (RFC 4303) | IP protocol 50 (or inside UDP 4500 behind NAT) | encryption and integrity of the payload |
| AH (RFC 4302) | IP protocol 51 | integrity only, including most of the outer IP header, so it breaks with NAT; rarely used today |
Each SA is one direction of protected traffic, identified by a 32-bit SPI (security parameter index) and carrying a sequence number that increases with every packet. Tunnel mode wraps the whole original IP packet (site-to-site VPNs); transport mode protects only the payload of a packet between two hosts.
An ESP packet, built and checked
The program builds an ESP packet in tunnel mode with AES-128-GCM (the layout of RFC 4106: SPI, sequence number, 8-byte IV, ciphertext, 16-byte integrity check value). The key and salt are fixed lab values; a real SA's keys come from IKE and are never reused. It then shows what an observer sees and what happens when one bit of the ciphertext is flipped in transit.
import struct
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
KEY, SALT = bytes(range(16)), bytes.fromhex("0a0b0c0d") # lab-only values from "IKE"
SPI = 0x00001001
def esp_seal(seq, inner_packet, next_header=4): # 4 = IPv4 inside (tunnel mode)
pad_len = (-(len(inner_packet) + 2)) % 4
plaintext = inner_packet + bytes(range(1, pad_len + 1)) + bytes([pad_len, next_header])
iv = struct.pack("!Q", seq) # unique per packet (here: the sequence number)
header = struct.pack("!II", SPI, seq)
return header + iv + AESGCM(KEY).encrypt(SALT + iv, plaintext, header) # SPI and seq are authenticated too
def esp_open(packet):
header, iv, body = packet[:8], packet[8:16], packet[16:]
plain = AESGCM(KEY).decrypt(SALT + iv, body, header)
pad_len, nh = plain[-2], plain[-1]
return plain[:-2 - pad_len], nh
inner = bytes.fromhex("4500001c00010000400100000a0a0005c0000219") + b"\x08\x00\xf7\xff\x00\x00\x00\x00"
pkt = esp_seal(1, inner)
spi, seq = struct.unpack("!II", pkt[:8])
print(f"ESP packet: {len(pkt)} bytes; visible: SPI 0x{spi:08x}, sequence {seq}; the rest is ciphertext + ICV")
print("ciphertext starts:", pkt[16:24].hex(" "), "... (the inner addresses 10.10.0.5 -> 192.0.2.25 are hidden)")
data, nh = esp_open(pkt)
print("receiver decrypts:", len(data), "bytes, next header", nh, "(IPv4), inner source", ".".join(map(str, data[12:16])))
tampered = bytearray(pkt); tampered[20] ^= 0x01
try:
esp_open(bytes(tampered))
except InvalidTag:
print("one flipped bit: integrity check fails, packet dropped")ESP packet: 64 bytes; visible: SPI 0x00001001, sequence 1; the rest is ciphertext + ICV
ciphertext starts: 3f 22 ee 2f a4 ef da dc ... (the inner addresses 10.10.0.5 -> 192.0.2.25 are hidden)
receiver decrypts: 28 bytes, next header 4 (IPv4), inner source 10.10.0.5
one flipped bit: integrity check fails, packet dropped
Anti-replay
An attacker who records an ESP packet can't read or change it, but could send it again. The receiver therefore tracks sequence numbers in a sliding window (64 packets by default in RFC 4303) and rejects duplicates and packets that are too old. Packets may arrive out of order within the window.
class ReplayWindow:
def __init__(self, size=64):
self.size, self.top, self.seen = size, 0, set()
def check(self, seq):
if seq == 0:
return "drop (sequence 0 never valid)"
if seq > self.top:
self.top = seq
self.seen = {s for s in self.seen if s > self.top - self.size} | {seq}
return "accept (new highest)"
if seq <= self.top - self.size:
return "drop (too old, left of window)"
if seq in self.seen:
return "drop (REPLAY)"
self.seen.add(seq)
return "accept (late, inside window)"
w = ReplayWindow()
for seq in [1, 2, 3, 5, 4, 5, 100, 40, 37, 37]:
print(f"seq {seq:>3}: {w.check(seq)}")seq 1: accept (new highest)
seq 2: accept (new highest)
seq 3: accept (new highest)
seq 5: accept (new highest)
seq 4: accept (late, inside window)
seq 5: drop (REPLAY)
seq 100: accept (new highest)
seq 40: accept (late, inside window)
seq 37: accept (late, inside window)
seq 37: drop (REPLAY)
Sequence 4 arrives late but inside the window and is accepted; the second 5 is a replay. After 100 arrives, the window covers 37–100, so 40 and 37 are accepted once and the second 37 is dropped. (36 or lower would be "too old".)
IKE and ESP in a capture
The session writes a synthetic capture of a site-to-site tunnel between two lab gateways (192.0.2.1 and 198.51.100.1): the first IKEv2 exchange (IKE_SA_INIT) on UDP 500 and three ESP packets, then reads it with tshark.
python3 - <<'PY'
from scapy.all import Ether, IP, UDP, Raw, wrpcap
from scapy.layers.ipsec import ESP
from scapy.layers.isakmp import ISAKMP
t0, pkts = 1768471200.0, []
A, B = ("192.0.2.1", "02:00:00:00:02:01"), ("198.51.100.1", "02:00:00:00:64:01")
ike = ISAKMP(init_cookie=b"\x11" * 8, resp_cookie=b"\x00" * 8, next_payload=33, version=0x20, exch_type=34, flags=0x08, id=0)
pkts.append(Ether(src=A[1], dst=B[1])/IP(src=A[0], dst=B[0])/UDP(sport=500, dport=500)/ike)
for seq in (1, 2, 3):
pkts.append(Ether(src=A[1], dst=B[1])/IP(src=A[0], dst=B[0])/ESP(spi=0x1001, seq=seq)/Raw(bytes(48)))
for i, p in enumerate(pkts):
p.time = t0 + i * 0.1
wrpcap("ipsec.pcap", pkts)
PY
tshark -r ipsec.pcap
echo "--- ESP fields an observer can read:"
tshark -r ipsec.pcap -Y esp -T fields -e ip.src -e ip.dst -e esp.spi -e esp.sequence -e frame.len 1 0.000000 192.0.2.1 → 198.51.100.1 ISAKMP 70 IKE_SA_INIT MID=00 Initiator Request
2 0.100000 192.0.2.1 → 198.51.100.1 ESP 90 ESP (SPI=0x00001001)
3 0.200000 192.0.2.1 → 198.51.100.1 ESP 90 ESP (SPI=0x00001001)
4 0.300000 192.0.2.1 → 198.51.100.1 ESP 90 ESP (SPI=0x00001001)
--- ESP fields an observer can read:
192.0.2.1 198.51.100.1 0x00001001 1 90
192.0.2.1 198.51.100.1 0x00001001 2 90
192.0.2.1 198.51.100.1 0x00001001 3 90
That is all an observer gets from ESP: the gateways' addresses, the SPI, the sequence numbers and the sizes. A real IKE_SA_INIT would also show, in cleartext, the proposed algorithms and Diffie-Hellman groups (the synthetic one here carries no payloads).
Weaknesses and their detection
- Weak proposals. DES/3DES, MD5/SHA-1 integrity, Diffie-Hellman groups 1, 2 or 5 (768–1536-bit MODP). Detection: IKE proposals in captures or gateway logs; scans of your own VPN endpoints with IKE probing tools. Fix: AES-GCM, SHA-256 or better, DH group 14 (2048-bit MODP) as the minimum and preferably elliptic-curve groups 19/20 (ECP-256/384) or 31 (Curve25519). RFC 8247 marks group 1 MUST NOT, groups 2 and 5 SHOULD NOT, group 14 MUST and group 19 SHOULD.
- IKEv1 aggressive mode with pre-shared keys (concept): the responder sends a hash derived from the PSK before authenticating the initiator, which allows offline guessing of weak PSKs. Fix: IKEv2, or main mode; certificates or long random PSKs.
- Weak or shared PSKs across many peers: one leak opens every tunnel. Fix: per-peer certificates.
- Unexpected peers or tunnels: IKE from addresses that are not configured partners, tunnels that renegotiate constantly, ESP to unknown destinations. Gateway logs and flow data show them.
Pitfalls
- Thinking IPsec means "the traffic is safe" end to end. A site-to-site tunnel protects the path between gateways; inside each site the traffic is plain again.
- Mixing up AH and ESP: AH gives no confidentiality.
- Blocking UDP 4500 or protocol 50 and then debugging "VPN connects but no traffic". IKE (500) works, the data path doesn't.
Practice
1. In the ESP program, why is the SPI and sequence number passed as associated data to AES-GCM?
They travel in clear but must not be changed: authenticating them as associated data means a modified SPI or sequence number fails the integrity check, which keeps the anti-replay logic trustworthy.
2. With a 64-packet window and the highest sequence number 100, which of 30, 36, 37 and 99 are accepted if not seen before?
37 and 99 (the window is 37–100); 30 and 36 are too old.
3. Why does AH not work through NAT?
AH's integrity check covers the outer IP addresses. NAT rewrites the source address, so the receiver's check fails. ESP doesn't cover the outer header, and NAT traversal wraps it in UDP 4500 so the NAT can track ports.
Test yourself
Which IPsec protocol provides encryption?
- AH
- ESP
- IKE
- GRE
What can a passive observer read in an ESP packet?
- The inner IP addresses
- The SPI, the sequence number, the outer addresses and the size
- The payload
- The encryption key
What does the ESP anti-replay window reject?
- Packets arriving out of order inside the window
- Duplicate sequence numbers and packets older than the window
- All packets after 64
- Encrypted packets
Which UDP ports does IKE use?
- 53 and 123
- 500, and 4500 with NAT traversal
- 1194
- 51820