IPsec and IKEv2

On this page

IPsec protects traffic at the IP layer based on policies, while IKEv2 is responsible for authenticating peers, negotiating algorithms, and maintaining security associations. Taking the example of headquarters 10.10.0.0/24 accessing branch 10.20.0.0/24: business hosts send packets to the gateway, which determines if protection is needed and encapsulates them using the established outbound SA; the peer gateway looks up the inbound SA, authenticates and decrypts, checks the policy, and then forwards the traffic to the internal network.

There are three independent things here: where system routing sends the packet, how the policy requires protection, and whether the SA has available keys and state. IKE showing "connected" only proves that part of this is true.

Quick DiagnosisWhat to Check
IKE SA and Child SAControl message status and business traffic status
ESP and AHWhether encryption is used and which fields are authenticated
Tunnel and TransportWhether the complete original IP packet is encapsulated
Can IKE_AUTH see the header?Boundary between protected payloads and outer headers
Why are there two formats for UDP 4500?Zero-marked IKE vs. non-zero SPI for ESP
Does rekeying re-verify the user?Rekey vs. Reauthentication
SA exists but no traffic counters?Routing, selectors, forwarding, and return path

Policies and Security Associations: Why They Are Stored Separately

The Security Policy Database (SPD) expresses whether traffic should be dropped, bypassed, or protected by IPsec; the Security Association Database (SAD) stores specific algorithms, keys, SPIs, sequence numbers, and lifecycle states. A policy can point to different generations of SAs at different times, and old and new SAs may coexist briefly during rekeying. IPsec Architecture RFC 4301

ESP SAs are unidirectional: A→B and B→A use their own SPIs, keys, and sequence numbers. One IKEv2 Child SA negotiation typically creates such a pair of SAs; management tools may display them collectively as a single CHILD_SA. The IKE SA protects subsequent control messages for both parties; its SPI and ESP's SPI do not belong to the same numbering space. strongSwan IPsec Introduction

Inbound ESP uses the SPI recognized by the receiving side to look up the security association; the SPI is not a password, nor is it a user identity. Even if a packet finds an SA, it must still pass authentication, replay checks, and policy constraints. You cannot treat a packet as legitimate business traffic just because it has the correct SPI.

How Traffic Selectors Restrict a Tunnel

Traffic Selectors include address ranges, protocols, and port ranges. The initiator can propose a broader range, and the responder accepts a narrower range based on policy. For example, if headquarters proposes accessing the entire branch 10.20.0.0/24 from 10.10.0.0/24, but the final policy only allows TCP 443 to branch server 10.20.0.8, you cannot interpret a successful negotiation as allowing access to any port on the entire branch subnet.

The following only demonstrates selector matching for one direction that has already been determined, without simulating full IKE negotiation or kernel SPD priority.

from ipaddress import ip_address, ip_network

def protected_flow(src, dst, protocol, dport):
    return (ip_address(src) in ip_network('10.10.0.0/24')
            and ip_address(dst) == ip_address('10.20.0.8')
            and protocol == 6 and dport == 443)

assert protected_flow('10.10.0.9', '10.20.0.8', 6, 443)
assert not protected_flow('10.10.0.9', '10.20.0.8', 6, 22)
assert not protected_flow('10.10.0.9', '10.20.0.9', 6, 443)
assert not protected_flow('10.11.0.9', '10.20.0.8', 6, 443)
print('Partial model with matching address, protocol, and port passed')

If you find the SPI, can you deliver the inner packet?

Replacing the correct SPI with the outbound SA's SPI, even if saved on the same device, does not constitute inbound state for this direction. After restoration, if you change the destination port, the cryptographic check may pass, but the packet could still be rejected due to selectors. The SPI is not a passcode.

Preparing the visual
If you find the SPI, can you deliver the inner packet?

SPI locates unidirectional key state; selectors constrain protected traffic. Finding the SA, successful authentication, and policy allowance are three sequential criteria.

ESP: Visible Fields, Encrypted Content, and Authentication

ESP uses IP protocol number 50, and AH uses 51; these numbers are protocol numbers, not TCP/UDP ports. ESP can provide confidentiality and integrity, determined by negotiated transforms; AH provides authentication without encryption and covers selected IP header fields, making it more sensitive to NAT address rewriting. Not all ESP combinations can be described as using a single fixed encryption algorithm.

PartVisibility and Function
SPI 4 B, Sequence Number 4 BPlaintext header, helps locate SA and replay check
Explicit IVAlgorithm-dependent; 8 B for AES-GCM-ESP
Payload, Padding, Pad Length, Next HeaderContent protected under the encryption transform
ICV / TagIntegrity check, length determined by the transform

Transport mode typically protects the upper-layer content after the original IP header; Tunnel mode treats the complete original IP packet as inner payload, adding a new outer IP header. The former does not mean the original IP header is completely immutable, nor does the latter equal end-to-end business encryption: the gateway-to-gateway tunnel terminates at the peer gateway. ESP RFC 4303

Don't Confuse the Three Lengths of AES-GCM

The nonce for AES-GCM-ESP consists of a 4 B salt and an 8 B explicit IV. The salt is allocated with key material; it is not sent as a 4 B field in the ESP header for each packet; the explicit IV appears in the packet and must not repeat under the same key. The SPI and sequence number participate in the Additional Authenticated Data (AAD), so they cannot be arbitrarily rewritten.

Tag support length is determined by the specific transform identifier: RFC 4106 requires support for 16 B, and allows 8 B or 12 B; you cannot uniformly write "GCM's ICV is 12 B". The example below selects a 16 B Tag, minimum four-byte alignment, IPv4 without options, and UDP NAT-T; there is no additional traffic-hiding padding. AES-GCM-ESP RFC 4106

IPv4 Tunnel + UDP Encapsulation + AES-GCM: Accounting for a 1,000 B Inner Packet Outer IP 20 B UDP 8 B ESP Header 8 B Explicit IV 8 B Encrypted Content 1004 B Tag 16 B Encrypted Content = Inner Packet 1000 + Padding 2 + Tail 2 Tail is Pad Length and Next Header; no additional four-byte Non-ESP Marker Total length 1064 B; box widths in the diagram do not represent true byte proportions Fixed use of 16 B Tag, minimum four-byte alignment, IPv4 without options; actual budget depends on negotiated algorithms and encapsulation.
def esp_tunnel_size(inner, outer_ip=20, udp=True):
    padding = (-(inner + 2)) % 4
    total = outer_ip + (8 if udp else 0) + 8 + 8 + inner + padding + 2 + 16
    return total, padding

assert esp_tunnel_size(1000) == (1064, 2)
assert esp_tunnel_size(1000, udp=False) == (1056, 2)
assert esp_tunnel_size(1000, outer_ip=40) == (1084, 2)
assert max(n for n in range(1501) if esp_tunnel_size(n)[0] <= 1500) == 1438
assert esp_tunnel_size(1438) == (1500, 0)
assert esp_tunnel_size(1439)[0] == 1504
print('ESP length budget under clear algorithm and encapsulation assumptions passed')

1438 B is the maximum complete inner IP packet under this set of assumptions, not TCP application payload. Inner IPv4/TCP must also deduct its own header; calculations should be redone if algorithms, outer IPv6, IP options, or other tunnels change.

Sequence numbers and the receive replay window allow a certain degree of out-of-order packets while rejecting duplicates. ESN uses extended sequence numbers, but the online ESP sequence number field remains the lower 32 bits, with the high bits inferred from state and participating in authentication. The replay window is not a reliable transmission window: lost ESP packets will not be automatically retransmitted by ESP.

IKEv2: Derive Protection Keys First, Then Complete Identity Authentication

Without additional challenges, EAP, or extended exchanges, initial establishment typically involves two request-response exchanges: IKE_SA_INIT and IKE_AUTH, i.e., approximately two network RTTs, plus computation time. Cookies, failed DH group retries, authentication methods, and packet loss can all increase time; you cannot write that all connections consist of a constant four packets. IKEv2 Initial Exchange

Basic establishment requires two request-response exchanges; authentication extensions can add round trips Initiator Responder IKE_SA_INIT: Proposals, DH Public Key, Ni IKE_SA_INIT: Selection, DH Public Key, Nr IKE_AUTH: Identity, AUTH, Child Proposals and Selectors IKE_AUTH: Identity, AUTH, Accepted Child Parameters Protection keys exist, but peer identity authentication is not yet complete IKE_AUTH's protected payloads are encrypted; outer IP/UDP and IKE headers remain visible; EAP can continue exchanges.

The IKE_SA_INIT exchange proposes algorithms, temporary DH public keys, and nonces. Obtaining a shared secret at this stage does not mean the other party's identity has been proven: identity verification must bind to the negotiation record to prevent establishing an encrypted channel shared only with an attacker.

The encrypted payload of IKE_AUTH contains identity, authentication material, and parameters required for the first Child SA; the outer IP/UDP and IKE headers remain visible. AUTH can be based on mechanisms such as signatures or shared keys; it cannot be limited to "signing the first message with a certificate private key." The input for basic signature authentication also includes the other party's nonce and identity payloads processed with SK_pi/SK_pr, establishing a binding between the handshake and identity. RFC 7296 §2.15

EAP authentication may require multiple IKE_AUTH round trips; declaring IDi does not mean EAP identity authentication is complete. Even after authentication passes, you must still check if that identity is authorized to request the corresponding selectors.

Order and Purpose in Key Derivation

In the basic DH flow, let g^ir be the shared secret calculated by both parties using "their own private key and the other party's public key"; it is not a direct DH operation on two public KE values.

StageBasic Derivation Expression
Initial IKE SeedSKEYSEED = prf(Ni | Nr, g^ir)
IKE Key Expansionprf+(SKEYSEED, Ni | Nr | SPIi | SPIr)
First Child / Child without new DHKEYMAT = prf+(SK_d, Ni | Nr)
CREATE_CHILD_SA with new DHKEYMAT = prf+(SK_d, g^ir_new | Ni | Nr)

prf+ is the iterative expansion function defined by IKE, not infinitely repeating an HMAC result. The expanded IKE material sequentially serves SK_d, integrity/encryption for both directions, and identity authentication auxiliary purposes; AEAD combinations do not require additional keys for traditional integrity algorithms. SK_pi/SK_pr are not certificate private keys. RFC 7296 §2.13–2.17

The first Child uses the nonce from IKE_SA_INIT; subsequent creations use nonces from corresponding new exchanges. When there is a new DH, the shared secret comes before Ni/Nr, not as an additional field that can be arbitrarily placed at the end. The basic first Child having no additional KE exchange does not mean the entire connection has no temporary DH.

NAT-T: Distinguishing IKE and ESP on UDP 4500

Native ESP has no TCP/UDP ports, making it difficult for many NATs to correctly maintain multi-client ESP mappings. NAT-T encapsulates ESP in UDP, commonly using 4500; IKE usually establishes from UDP 500 first, detecting NAT or switching to 4500 based on functional conditions. Seeing 4500 alone is insufficient to assert NAT is present; behaviors like MOBIKE also affect port usage. strongSwan NAT Traversal

UDP 4500 PayloadJudgment Method
IKE MessagePreceded by four zero-byte Non-ESP Marker, followed by IKE header
UDP Encapsulated ESPStarts directly from non-zero SPI, without adding these four zeros
NAT KeepaliveSpecific single byte 0xff, used to maintain mapping

Therefore, the previous ESP length budget only adds an 8 B UDP header, without adding the 4 B IKE-specific marker. NAT keepalives maintain the mapping, while protected IKE liveness checks confirm peer response; the two cannot replace each other. UDP Encapsulation RFC 3948

Rekeying, Reauthentication, and Address Migration

CREATE_CHILD_SA can establish additional Children, replace existing Children, and can also be used for IKE SA rekeying. The basic exchange is one request plus one response, approximately one RTT; "negotiation completed in less than 0.5 RTT" has no corresponding protocol guarantee.

Rekeying updates keys and associations, but does not equal re-verifying the current status of certificates or re-executing user authentication. Reauthentication retraces the authentication process, affecting different states. Implementations typically allow old and new SAs to overlap briefly, receiving in-flight old packets; expiration, byte/packet counts, replay sequence numbers, and simultaneous rekeying initiation by both parties all require handling. strongSwan SA Renewal

MOBIKE is an IKEv2 extension requiring support and negotiation from both parties, allowing the tunnel to update its path as the outer address changes; you cannot assert migration support just because a device says "IKEv2". It does not create new identities for applications, nor does it guarantee zero packet loss during switching. MOBIKE RFC 4555

When certificate chains are large, IKE messages may be limited by MTU and fragmentation. IKEv2's encrypted message fragmentation extension is different from IP-layer fragmentation, and does not mean ESP packets can ignore PMTU. IKE Fragmentation RFC 7383

From IKE Success to Business Success

Linux's policy-based IPsec captures matching traffic based on policies; route-based methods like the XFRM interface make routing management more intuitive, but still rely on correct association of policies, SAs, and interfaces. Creating an interface or adding a route does not itself establish a cryptographic session. strongSwan Route-based VPN

PhenomenonEvidence to Continue Checking
No IKE_SA_INIT response receivedOuter reachability, UDP ports, firewall, peer listening
Received NO_PROPOSAL_CHOSENBoth parties' algorithm proposals and matched connection configurations
AUTHENTICATION_FAILEDActual identity, credentials, trust chain, and authentication method
IKE SA exists but Child failsESP proposals, TS, address allocation, and authorization
Child established but outbound counter not increasingWhether business packets reach the gateway, and if routing/policy match
Outbound increasing but inbound notPeer counters, return path, filtering, NAT-T, and SA state
Small packets work, large transfers stallPMTU, encapsulation budget, ICMP feedback, and fragmentation

You can check actual negotiation results with swanctl --list-sas, then compare with business flows and routing; Linux ip -s xfrm policy can observe policies. When exporting SA state, be aware that some raw state commands may contain key material; diagnostic sharing should prioritize summaries that do not output keys. Performance judgments should also be based on actual traffic and whether offloading is effective, rather than directly deriving throughput limits from terms like "enterprise-grade" or "kernel implementation."