Skip to content
Tech Interview Prep
Technical interview guide

VPNs & Tunneling

Encapsulating traffic inside another protocol to create a private, often encrypted path across an untrusted network.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current IETF IPsec/IKEv2/NAT-T/GRE/L3VPN/VXLAN/PMTUD/UDP, NIST IPsec, WireGuard, OpenVPN 2.6, and TLS 1.3 references reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Compare IPsec transport and tunnel modes.

Answer

The 90-second answer

Assume IPv4, ESP rather than AH, and that "endpoints" means the devices terminating IPsec. The difference is one thing: what the outer IP header addresses. Transport mode keeps the original IP header as the outer header and inserts ESP between it and the transport header, so the packet on the wire is addressed host-to-host and only the payload is protected. Tunnel mode wraps the whole original packet, header included, inside a new packet addressed gateway-to-gateway, so the inner addresses are invisible on the wire. Pick transport when the two hosts talking are the two IPsec endpoints; pick tunnel when a gateway, a remote-access client, or overlapping address space is involved.

Mechanism

ESP in transport mode: [IP hdr][ESP hdr][TCP/UDP + data][ESP trailer][ICV]. The IP header's protocol field becomes 50, and the header stays in the clear (mutable fields like TTL and checksum can't be protected anyway). ESP in tunnel mode: [new IP hdr][ESP hdr][original IP hdr + payload][ESP trailer][ICV]. The original header is now encrypted payload.

AH differs: it authenticates the IP header too, so AH transport mode breaks under NAT. Any address rewrite invalidates the ICV and the packet is dropped. ESP doesn't cover the outer header, which is why ESP survives NAT once wrapped in UDP 4500 (NAT-T, RFC 3948; IKE itself uses UDP 500).

Comparison

TransportTunnel
outer src/dstthe two hoststhe two gateways
inner headervisible, routableencrypted
ESP overhead~22 B (8 hdr + 2 trailer + 12 ICV, SHA-1) + padding to 16 Bsame + 20 B new IPv4 header
NATESP needs NAT-T; AH impossibleESP needs NAT-T
typical usehost-to-host, GRE-over-IPsecsite-to-site, remote access

Worked trace

Host 10.0.0.5 → 10.0.1.9, gateways 203.0.113.1 and 198.51.100.1.

Transport: [IP 10.0.0.5→10.0.1.9 proto=50][ESP][TCP dport=443]. A router between them sees 10.0.0.5 → 10.0.1.9 and can route, QoS, and ACL on those addresses.

Tunnel: [IP 203.0.113.1→198.51.100.1 proto=50][ESP][IP 10.0.0.5→10.0.1.9 proto=6][TCP dport=443]. The router sees only the gateway addresses; 10.0.0.5 is encrypted.

Trade-offs and when not to use

Transport mode keeps the original addresses visible, so intermediate routers can route and classify on them, but it only works when the communicating hosts are themselves the IPsec endpoints, which doesn't scale to a site-to-site mesh. Tunnel mode scales to gateways and hides internal addressing (useful when both sites use 10.0.0.0/8), at the cost of ~20 extra bytes and no visibility for intermediate policy. Don't use transport mode for a gateway-to-gateway VPN; don't use tunnel mode when you need per-flow routing on the real addresses.

Failure modes

  • MTU black hole: tunnel mode adds ~50-73 B, so a 1500 B inner packet exceeds the path MTU. If ICMP "frag needed" is filtered, small packets pass and large transfers hang. Detect with ping -M do -s 1472 and step down; fix with MSS clamping or a lower tunnel MTU (~1400).
  • NAT + AH: ICV mismatch, silent drops. Detect by comparing counters on both ends.
  • Overlapping subnets in tunnel mode: two sites both on 192.168.1.0/24 collide; the SPD can't distinguish them. Detect at policy-install time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Compare route-based and policy-based site-to-site VPNs.

Answer

Both designs run the same IKEv2/IPsec tunnel; the difference is what decides which packets enter it.

Assumptions: I'm comparing IKEv2 site-to-site between two gateways, both under your control unless noted. If one side is a cloud gateway, that constrains the choice.

Mechanism

Policy-based (traffic-selector). The gateway keeps a security policy database (SPD) of local↔remote prefix pairs. IKEv2 negotiates those as TSi/TSr, and each child SA is bound to one selector pair. A packet is encrypted only if it matches a selector; anything else is routed normally or dropped by the crypto ACL. Ten prefixes means ten selectors and often ten SAs.

Route-based. The SPD is effectively a wildcard (0.0.0.0/0 ↔ 0.0.0.0/0). The tunnel is a routable interface: Cisco VTI, Juniper st0, Linux xfrm interface, or a cloud route-based gateway. The routing table decides what enters, so you can run BGP or OSPF over it.

Trace, packet 10.1.1.5 → 10.2.2.9:

  • Policy-based: SPD lookup → match 10.1.1.0/24 ↔ 10.2.2.0/24 → encrypt → send to peer IP. No match → out the default route in clear.
  • Route-based: route lookup → 10.2.2.0/24 via Tunnel0 → hand to tunnel interface → encrypt with wildcard selector → send.

Trade-offs

DimensionPolicy-basedRoute-based
Adding prefixesNew selector + SA per pairOne route, one SA
Dynamic routingNot possible (no interface)BGP/OSPF over the tunnel
Overlapping subnetsCan't disambiguateVRF per tunnel
FailoverDPD + multiple policy entriesBGP reconvergence
Cloud supportAzure policy-based: IKEv1, one connection, no BGPAWS and Azure route-based: IKEv2, BGP, active-active

When to pick which

Route-based is the default for anything beyond a couple of static prefixes: dynamic routing, multiple tunnels, overlapping address space, or any cloud gateway. Pick policy-based only when the peer forces it: an older ASA, a third-party appliance that only speaks selectors, or Azure's policy-based gateway.

Failure modes and detection

  • Selector mismatch: Phase 1 up, Phase 2 down, TS_UNACCEPTABLE or NO_PROPOSAL_CHOSEN. Check show crypto ipsec sa for a missing SA.
  • Asymmetric selectors: one side 10.1.1.0/24↔10.2.2.0/24, the other 0.0.0.0/0. Some platforms accept it, some don't; symptom is one direction working.
  • PMTUD black hole: small packets pass, large ones vanish. TCP handshake fine, TLS stalls. Test with DF-set pings of increasing size; fix with MSS clamp to 1360.
  • Route withdrawal: BGP drops the prefix and traffic blackholes with no backup. Watch BGP state and the route table.
  • DPD false positive: transient loss tears the SA down (Cisco IOS default 10 s interval, 2 retries). Raise the timer on lossy links.

Config, Cisco IOS-XE VTI:

interface Tunnel0
 ip address 169.254.1.1 255.255.255.252
 tunnel source GigabitEthernet0/0
 tunnel destination 203.0.113.9
 tunnel mode ipsec ipv4
 tunnel protection ipsec profile PROF
router bgp 65001
 neighbor 169.254.1.2 remote-as 65002

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Walk me through how Phase 1 and Phase 2 negotiations differ in purpose, exchange structure, and security parameters across IKEv1 and IKEv2.

Answer

Phase 1 creates the control-plane bidirectional secure channel (the IKE SA / ISAKMP SA) between two peers. Phase 2 leverages that channel to establish unidirectional data-plane Security Associations (IPsec SAs or Child SAs: ESP or AH) governed by negotiated Traffic Selectors.

Architectural Distinction and Purpose

Phase 1 / IKE SA (Control Plane, UDP 500 / 4500):
  Peer A <=================== Authenticated Control Channel ===================> Peer B
                             (Protects Rekey, Deletes, Child SAs)
                                              |
                                              v  negotiates
Phase 2 / Child SA (Data Plane, ESP / Protocol 50):
  Host A [10.1.0.0/24] -------- ESP SA Inbound SPI_A [K_e, K_a] --------> Host B [10.2.0.0/24]
                       <------- ESP SA Outbound SPI_B [K_e, K_a] -------
  1. Phase 1 (IKE SA): Authenticates the endpoints (PSK or X.509/PKI), executes an initial Diffie-Hellman (DH) exchange, and derives symmetric encryption and integrity keys (SK_e, SK_a, SK_d in IKEv2 / SKEYID in IKEv1). It protects all subsequent signaling, including keepalives, rekeying, and Phase 2 negotiations.
  2. Phase 2 (Child SA): Negotiates data-plane protection for actual user payloads. It determines the security protocol (ESP or AH), mode (tunnel vs. transport), cryptographic transforms (e.g., AES-GCM-256), Security Parameter Index (SPI) values for each direction, and Traffic Selectors (TSi, TSr subnets/ports/protocols matching the Security Policy Database, SPD).

Exchange Mechanics: IKEv1 vs. IKEv2

AttributePhase 1 (IKEv1 / RFC 2409)Phase 2 (IKEv1 / Quick Mode)IKEv2 (RFC 7296 Core Exchanges)
Exchange NameMain Mode (6 packets) or Aggressive Mode (3 packets)Quick Mode (3 packets)IKE_SA_INIT (2 pkts) + IKE_AUTH (2 pkts)
Round Trips3 RTT (Main) or 1.5 RTT (Aggressive)1.5 RTT1 RTT (INIT) + 1 RTT (AUTH) = 2 RTT total
Identity ProtectionYes in Main Mode (encrypted in msgs 5–6); No in Aggressive ModeYes (encrypted under Phase 1 keys)Yes (IKE_AUTH payloads encrypted under SK_e/SK_a)
Data SA PiggybackingNo; Quick Mode must run after Phase 1 finishesYes; produces the first IPsec SA pairYes; the first Child SA is negotiated directly inside IKE_AUTH
Subsequent Data SAsRequires another 3-packet Quick Mode exchangeSameCREATE_CHILD_SA exchange (1 RTT, 2 packets)
Perfect Forward Secrecy (PFS)DH is mandatory to establish Phase 1 keysOptional DH exchange per Quick ModeOptional DH exchange in CREATE_CHILD_SA

Key Derivation and Parameter Dependencies

In IKEv2, the IKE_SA_INIT exchange passes nonces (Ni, Nr) and DH public values (KEi, KEr). The shared secret SKEYSEED is calculated as prf(Ni | Nr, g^ir). From SKEYSEED, key material is expanded:

{SK_d | SK_ai | SK_ar | SK_ei | SK_er | SK_pi | SK_pr} = prf+ (SKEYSEED, Ni | Nr | SPIi | SPIr)
  • SK_ei / SK_er and SK_ai / SK_ar encrypt and authenticate subsequent control frames (including IKE_AUTH).
  • SK_d derives keys for Child SAs: KEYMAT = prf+ (SK_d, [g^ir (new DH if PFS enabled)] | Ni | Nr). If PFS is omitted in Phase 2, no new DH exchange takes place; KEYMAT relies solely on SK_d and fresh nonces. If PFS is configured, a new DH exponentiation is required, bounding exposure if an earlier DH secret is compromised.

Primary Failure Modes

  1. Phase 1 Failures: Proposal mismatch (mismatched DH group, cipher, PRF, or integrity algorithm), peer identity validation rejection (IDi/IDr mismatch), or authentication credential mismatch (wrong PSK or expired/untrusted certificate). Detected via NO_PROPOSAL_CHOSEN or AUTHENTICATION_FAILED notify payloads, with zero ESP packets ever generated.
  2. Phase 2 Failures: Phase 1 completes, but Traffic Selectors do not match (e.g., local subnet 10.1.0.0/24 offered, peer expects 10.1.0.0/16), or transform mismatch for ESP (e.g., peer disallows AES-CBC-128). Detected via TS_UNACCEPTABLE or NO_PROPOSAL_CHOSEN during IKE_AUTH or CREATE_CHILD_SA, leaving the IKE SA up while data traffic drops at the SPD.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Trace an IKEv2 negotiation failure.

Answer

The 90-second answer

Trace it in negotiation order, because which exchange fails tells you which layer broke. IKEv2 runs two phases: IKE_SA_INIT (message ID 0, unencrypted. Negotiates crypto suite and DH, exchanges nonces and NAT-detection hashes) and IKE_AUTH (message ID 1, encrypted. Authenticates identities and creates the first Child SA). A failure in IKE_SA_INIT is transport or crypto; a failure in IKE_AUTH is identity, credential or policy. So the first move is to find the highest message ID that got a response, then read the notify payload on the reply.

The single fact that redirects the whole trace: did the responder emit any notify at all? A notify means the packet arrived and policy rejected it. Silence means it never arrived.

Worked trace: PSK mismatch

Initiator 203.0.113.10:500 → responder 198.51.100.5:500.

1  IKE_SA_INIT req   msgid 0  SPIi=0x8f3a1c..  SPIr=0
   SA: AES-CBC-256 / PRF_HMAC_SHA2_256 / AUTH_HMAC_SHA2_256_128 / DH14
   KEi, Ni, NAT_DETECTION_SOURCE_IP
2  IKE_SA_INIT resp  msgid 0  SPIr=0x2c71b4..
   proposal chosen, KEr, Nr, NAT_DETECTION_DESTINATION_IP
   -> IKE SA keys derived
3  IKE_AUTH req      msgid 1  (encrypted)
   IDi=IPv4 203.0.113.10, AUTH=HMAC(PSK), SA/TSi=0.0.0.0/0, TSr=10.0.0.0/16
4  IKE_AUTH resp     msgid 1  (encrypted)
   notify AUTHENTICATION_FAILED (24). No responder AUTH, no Child SA.
   -> IKE SA torn down

Note the responder SPI is zero in packet 1 and filled in by packet 2, if you never see a non-zero SPIr, the responder never answered IKE_SA_INIT.

Notify payloads that name the failure

notifycodephasemeaning
NO_PROPOSAL_CHOSEN14IKE_SA_INITno common crypto suite
INVALID_KE_PAYLOAD17IKE_SA_INITwrong DH group; retry with the group in the notify
AUTHENTICATION_FAILED24IKE_AUTHAUTH payload didn't verify (PSK or cert)
INVALID_ID9IKE_AUTHIDi/IDr not acceptable
TS_UNACCEPTABLE38IKE_AUTHtraffic selectors don't match policy
INTERNAL_ADDRESS_FAILURE36IKE_AUTHconfig-payload address assignment failed

Retransmission arithmetic

If packet 2 never arrives, the initiator resends packet 1 with the same SPIi and same message ID. strongSwan's charon defaults are retransmit_timeout = 4.0 s, retransmit_base = 1.8, retransmit_tries = 5, giving intervals of 4, 7.2, 13.0, 23.3, 42.0 s: roughly 90 s before it declares the peer dead. Same msgid + same SPIi = retransmit. Same msgid with a different KEi = the INVALID_KE_PAYLOAD retry, which is normal, not a failure.

Trade-offs and failure modes

Responder log vs initiator log. The initiator only ever sees a timeout; the responder knows why it rejected. If the initiator shows retransmits and the responder log is empty, it's reachability, not crypto. Capture on both ends: packet received but no reply = policy/config; packet never received = network.

PSK vs certificate. A PSK mismatch returns a bare AUTHENTICATION_FAILED with no reason: deliberate, so the responder isn't an oracle. Certificate failures surface differently: a CERTREQ/CERT exchange, then INVALID_ID or a cert-validation error in the responder log.

  • UDP 500/4500 dropped: initiator retransmits msgid 0, responder log empty, tcpdump on the responder shows nothing.
  • NAT present but 4500 blocked: IKE_SA_INIT succeeds on 500, both sides detect NAT via the NAT_DETECTION hashes and switch to 4500, then IKE_AUTH retransmits msgid 1 indefinitely.
  • DH group mismatch: INVALID_KE_PAYLOAD, one extra round trip, not fatal.
  • PSK mismatch: AUTHENTICATION_FAILED, IKE SA torn down; do not retry with the same credentials.

What changes the diagnosis: a notify means the packet arrived and policy rejected it; silence means it never arrived. Everything else follows from that split.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Specify cryptographic proposals and rekey policy.

Answer

Assume a site-to-site IKEv2 VPN between two data centers, plus remote-access clients, ESP in tunnel mode, no AH because we cross NAT, and both ends running a current strongSwan-class stack. Here is the proposal, then the rekey policy, then what breaks.

Proposal. IKEv2 (RFC 7296) only: no IKEv1. The IKE SA offers AES-256-GCM for encryption with HMAC-SHA2-256 as the PRF, DH group 19 (256-bit ECP) as the floor and group 20 (384-bit ECP) preferred, and authentication by ECDSA P-256/P-384 or RSA-3072 with SHA-256. Because GCM is AEAD, the integrity algorithm is NONE (RFC 5282 for IKEv2, RFC 4106 for ESP). The Child SA offers ESP AES-256-GCM-16 with PFS: a fresh DH group 19/20 exchange on every rekey. AES-256-CBC plus HMAC-SHA2-256-128 stays as a second proposal only while a named legacy peer still needs it.

IKE SAChild SA
encryptionAES-256-GCMESP AES-256-GCM-16
integrityNONE (AEAD)NONE (AEAD)
PRFHMAC-SHA2-256—
DHgroup 19 floor, 20 preferredgroup 19/20, PFS on rekey
authECDSA P-256/P-384, RSA-3072—
lifetime8 h1 h or byte/packet limit

Rekey policy. The margin, how long before expiry you start the rekey, has to exceed the rekey handshake plus the link RTT plus retransmission headroom. A CREATE_CHILD_SA is one round trip, so on a 100 ms RTT link that is ~200 ms, but IKEv2 retransmits with exponential backoff, so I set the margin at 5–10% of the lifetime: a few minutes on a 1-hour SA. Add jitter of ±10% so a thousand tunnels sharing a 1-hour lifetime do not all rekey in the same second and spike CPU on the DH exchange.

Why the packet limit matters. ESP's sequence number is 32 bits (RFC 4303), so an SA carries at most 2^32 packets before it must rekey. At 1 Gbps with 1400-byte packets that is ~89,000 pps, so 2^32 packets is ~13 hours: a 1-hour lifetime rekeys long before. At 10 Gbps it is ~893,000 pps and exhaustion arrives in ~80 minutes, so a 1-hour lifetime is now cutting it close and you want a packet or byte limit that fires first. AES-GCM adds its own cap: RFC 4106 and NIST SP 800-38D bound a key to 2^32 invocations, so the same rekey-before-exhaustion rule applies.

Anti-replay. RFC 4303 sets a minimum window of 32 packets; 64 is the common default. On a high-bandwidth, high-RTT path where packets reorder by more than the window, raise it to 1024 or 4096. The cost is per-SA memory, not security: a replayed packet inside the window is still caught as a duplicate.

Failure modes. No-overlap: the new SA is not up before the old expires, traffic drops, and you see it as packet loss plus "no matching SA" logs; the fix is a bigger margin. Simultaneous rekey: both peers initiate, IKEv2 resolves it deterministically (RFC 7296 §2.8) and deletes the duplicate SA, so the symptom is transient duplicate SAs, not a broken tunnel. Sequence exhaustion: the stack refuses to send or drops the SA. Watch the sequence counter against the limit. Thundering herd: a CPU spike on the DH exchange, fixed by jitter.

Migration and rollback. Run the strong and legacy proposals side by side, log which peers negotiate the weak one, then remove it on a dated plan once that list is empty. Rollback reverts the cipher suite only; authentication and identity stay identical, so a rollback never weakens identity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Tune and troubleshoot anti-replay behavior.

Answer

Anti-replay is a receiver-side check on the ESP sequence number, and the tuning question is almost always the same one: is the window too small for the reordering your network actually produces, or is the replay counter climbing because something is genuinely duplicating packets? You answer that from the counter and the sequence numbers, not by widening the window first.

Assumptions: ESP tunnel mode, one SA, RFC 4303 anti-replay, Linux XFRM or strongSwan as the endpoint.

Mechanism

The sender keeps a 32-bit counter and increments it per packet (ESN extends this to 64 bits). The receiver keeps R, the highest accepted sequence number, and a W-bit bitmap covering [R-W+1, R]. On arrival of sequence S:

  • S > R: accept, slide the window to [S-W+1, S], set the bit.
  • R-W+1 <= S <= R: bit already set means received before, drop as replay; bit clear means accept and set it.
  • S < R-W+1: drop as too old.

RFC 4303 sets the default window at 64. RFC 6479 gives the high-performance bitmap form used for large windows.

Trace

W=64, R=1000, window covers 937..1000.

packetresult
S=950, bit clearaccept
S=950 again, bit setreplay drop
S=936, below windowtoo-old drop
S=1001, S>Raccept, R=1001, window 938..1001

The window is a packet-count tolerance, not a time tolerance. Reorder distance is roughly latency spread times packet rate. At 10 Gbps of 1400-byte ESP packets that is about 890k pps; a 5 ms spread between ECMP paths puts roughly 4,460 packets in flight. A window of 64 drops most of them as too old even though none is a replay. That arithmetic is what decides the window.

Trade-off

Size it as W >= (max path latency spread) x (peak pps) + margin. Widening costs bitmap memory and check time, and it enlarges the set of sequence numbers an attacker can exploit by reordering: a captured packet that was never delivered stays acceptable longer. So widen only to the measured spread. If the replay counter climbs with no reordering present, a bigger window hides the real cause.

Failure modes

symptomdetectioncost
ECMP per-packet hashing reordersreplay counter climbs, sequence gaps in a capture, no exact duplicateslegitimate drops until hashing is per-flow or window widened
Network duplication (mirror port, bad LB)exact duplicate sequence numbers, counter climbs steadilyreal drops if window is small
HA failover with unsynced replay statecounter spikes right after failover; standby's R behind the active's accepts already-seen packets, or false replays if R synced without the bitmapwindow opens or traffic drops
SA rekey / 32-bit counter wrap without ESNsequence-error counter, hard lifetime firesSA tears down
Crypto offload reorders completionscounter climbs under load onlydrops under burst

Read /proc/net/xfrm_stat: XfrmInReplay counts anti-replay drops, XfrmInStateSeqError counts sequence errors. strongSwan exposes replay_window, default 32. Correlate a counter climb with a sequence capture before changing anything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Troubleshoot a VPN that fails only behind NAT.

Answer

What I'd say first

"Fails only behind NAT" tells me the tunnel works when both peers hold public addresses and breaks when a NAT sits on the path. Before touching config I'd split the symptom: does IKE fail to come up, or does IKE come up and data not flow? Those are different bugs. I'd assume IKEv2/IPsec unless told otherwise, and I'd want the outer addresses and ports on both ends, plus whether the NAT is a home router, a cloud NAT gateway, or carrier-grade NAT.

Why NAT breaks IPsec

Three mechanisms, each mapping to a symptom.

ESP is IP protocol 50: no ports. A NAT can't demux several ESP flows to one public address, and many NATs won't track protocol 50 at all. So the peers must detect NAT and wrap ESP inside UDP.

The IKE payloads carry the sender's own address and port. Once NAT rewrites the outer header, those no longer match. IKEv2 detects this with NAT_DETECTION_SOURCE_IP and NAT_DETECTION_DESTINATION_IP: each a SHA-1 hash over (SPI, IP, port). Each side recomputes the hash from the source it actually sees and compares. Mismatch means NAT. Both sides then move to UDP 4500 for IKE_AUTH and for ESP (RFC 3948).

NAT mappings expire when idle. If the tunnel is quiet longer than the mapping timeout, the NAT drops the entry and the next packet from the peer is dropped. Keepalives keep the mapping warm.

Trace

Initiator → 500: HDR, SAi1, KEi, Ni, NAT_DETECTION_SOURCE_IP, NAT_DETECTION_DESTINATION_IP. Responder → 500: same payloads, its own hashes. Initiator recomputes the hash of the packet's source IP/port; it doesn't match the payload → NAT detected. Both switch to 4500; IKE_AUTH and ESP-in-UDP follow on 4500.

Failure modes and how I'd detect them

SymptomLikely causeDetection
IKE_AUTH completes, no dataUDP 4500 blocked, or NAT-T not negotiatedipsec statusall shows SA but zero data counters; tcpdump udp port 4500 shows nothing
Tunnel drops after idleNAT mapping expired; keepalive ≥ NAT timeoutcorrelate drop time with idle period; check keepalive interval
Ping works, large packets failMTU/DF black hole from ESP-in-UDP overheadping -M do -s 1400
Second client behind same NAT failsport collision / rebindingcompare SPIs and source ports on both ends
IKE_AUTH fails, "no matching peer config"identity bound to IP (PSK + aggressive mode)check IDi/IDr against configured peer

Decisions

Keepalive interval must be shorter than the smallest UDP mapping timeout on the path. strongSwan's charon.keep_alive defaults to 20 s; Cisco's NAT keepalive is 20 s; AWS NAT gateway drops idle UDP after 120 s. 20 s clears all of those. If the path has a 30 s timeout, drop to 10 s.

If IKE messages are large (many proposals, long cert chains), enable IKEv2 fragmentation (RFC 7383) rather than lowering MTU globally.

If identity must survive address changes, use certificates with IDi/IDr, not a PSK bound to an IP.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Calculate and validate VPN MTU.

Answer

Core answer (say this first). Assume a 1500-byte path MTU, IPv4 outer transport, and IPsec ESP in tunnel mode with NAT-T on UDP 4500 using AES-GCM-128. The inner MTU is the path MTU minus every byte the tunnel adds:

1500  path MTU
 -20  outer IPv4 header
  -8  UDP (NAT-T)
  -8  ESP header (SPI + sequence)
  -8  GCM explicit IV
  -1  pad length
  -1  next header
 -16  GCM ICV
----
1438  -> round down to 1436 for 4-byte alignment

Set the tunnel interface MTU to 1400. That 36-byte margin covers a path that is 1480 rather than 1500, or one extra header later. The inner host then advertises MSS 1360 (1400 − 40 for IPv4 TCP) or 1340 (1400 − 60 for IPv6 TCP).

Overhead by encapsulation (all against a 1500-byte path, IPv4 outer):

EncapsulationBytes addedInner MTU
GRE, no key20 + 41476
GRE + key20 + 4 + 41472
VXLAN20 + 8 UDP + 8 VXLAN + 14 inner Eth1450
IPsec ESP/GCM + NAT-T621438
VXLAN inside IPsec62 + 501388

Nesting is additive: subtract each layer's headers, not the largest one.

Trade-offs. Three ways to land on a number, and they fail differently.

  • Static MTU with margin: deterministic, works when ICMP is filtered. Cost: you leave throughput on the table, and if the real path is smaller than assumed you still black-hole.
  • PMTUD: discovers the true path MTU, no wasted margin. It only works if ICMP is allowed end to end: IPv4 type 3 code 4 (fragmentation needed, DF set) and ICMPv6 type 2 (packet too big). One filtered hop and it silently fails.
  • TCP MSS clamping: rewrite the MSS option on SYN/SYN-ACK at the tunnel edge. It fixes TCP only; UDP, QUIC and ICMP keep the full datagram size and still black-hole. Use it as a belt-and-braces layer, not the primary mechanism.

Failure modes and detection. The classic symptom is a PMTUD black hole: the handshake and small packets pass, then the connection stalls the moment a full-size segment is sent. TLS completes, then the transfer hangs. Detect it by probing the boundary with DF set:

ping -M do -s 1372 10.0.0.1   # 1372 + 28 = 1400, expect success
ping -M do -s 1400 10.0.0.1   # 1400 + 28 = 1428, expect 'message too long'

For IPv6 use ping -6 -M do -s 1352 (1352 + 48 = 1400). If the first succeeds and the second is dropped rather than rejected, ICMP is being filtered somewhere on the path. Confirm with tcpdump on both ends: you see repeated retransmits of the same full-size segment with no ICMP coming back. The operational cost is real: a black hole looks like an application bug, so it burns debugging time until someone checks MTU.

Re-run the probe after any route, tunnel-algorithm, or address-family change; a path that was 1500 can become 1480 or 1400 without notice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Diagnose a size-dependent VPN failure.

Answer

The 90-second answer

Small pings and TCP handshakes work, large transfers stall or retransmit: that pattern is a PMTU black hole, not a crypto or routing problem. The tunnel wraps each inner packet in an outer header, so a 1500-byte inner packet leaves as a 1554-byte outer packet on an ESP/AES-GCM tunnel. The router that cannot forward it should return ICMP Fragmentation Needed (IPv4 type 3 code 4) or ICMPv6 Packet Too Big (type 2). If that ICMP is filtered, rate-limited, or addressed to the tunnel endpoint and never relayed to the inner host, the sender keeps retransmitting the same too-big packet. TCP stalls; UDP and ICMP disappear silently.

So the work is: confirm the size threshold, find the real path MTU, check whether the ICMP is arriving, then either restore PMTUD or set a validated MTU. MSS clamping is a TCP-only band-aid, not the fix.

Overhead, and where the threshold lands

Encapsulation (IPv4 outer, no NAT-T)OverheadInner MTU on a 1500 path
IPsec ESP tunnel, AES-GCM20 + 8 + 8 + 2 + 16 = 541446
WireGuard20 + 32 = 521448
GRE20 + 4 = 241476
VXLAN20 + 8 + 8 = 361464

Add 8 for NAT-T (UDP), 20 more for an IPv6 outer header.

Trace it

# from the host behind the tunnel, DF set
ping -M do -s 1472 10.20.0.9   # inner 1500 B -> outer 1554 B -> no reply
ping -M do -s 1418 10.20.0.9   # inner 1446 B -> outer 1500 B -> reply
# threshold at inner 1446 = 1500 - 54: that is the ESP/AES-GCM overhead

Then look for the ICMP that should have come back:

tcpdump -ni any 'icmp[0]==3 and icmp[1]==4'   # IPv4 frag-needed
tcpdump -ni any 'icmp6 and ip6[40]==2'        # ICMPv6 Packet Too Big

Large packets leaving with no ICMP returning is the black hole.

Failure modes

  • ICMP filtered. A blanket "block ICMP" rule or a stateful firewall dropping the unsolicited Too Big message. Detect with the DF sweep above plus the tcpdump filter; cost is TCP retransmit-to-timeout and silent UDP loss.
  • ICMP stranded at the tunnel endpoint. The router generating it is on the outer path and addresses the tunnel endpoint, not the inner host. Capture on both sides: ICMP present on the outer, absent on the inner.
  • MSS clamp missing or wrong. TCP works after clamping, but QUIC, DNS-over-UDP, SIP and IPsec-in-IPsec still fail. Detect by running a large UDP probe after TCP is fixed.
  • Offload masking the real packet size. TSO/GSO makes a host capture show 64 KB "packets" the NIC segments to 1500 on the wire. Capture on a SPAN port, or ethtool -K eth0 tso off gso off and retest.
  • Outer fragmentation dropped. With outer DF clear the path fragments, but firewalls that drop non-first fragments or endpoints that fail reassembly kill it. Check netstat -s | grep -i reassembl and fragment counters.
  • Endpoint MTU mismatch. One side jumbo (9000), the other 1500.

Fix, and the trade-off

Restore PMTUD: permit ICMPv4 type 3 code 4 and ICMPv6 type 2 both directions and make the tunnel endpoint relay them inward. Correct for every protocol and adapts when the path changes; fails wherever ICMP is filtered.

Static inner MTU: ip link set dev tun0 mtu 1400, validated with a DF ping sweep at exactly that size. Deterministic and works with ICMP blocked, but must be the minimum across the path and revalidated when the path changes.

MSS clamp: iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu. Cheap, fixes TCP only; never the sole fix on a tunnel carrying UDP or QUIC.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Diagnose traffic that bypasses an apparently active IPsec tunnel.

Answer

What I'd say first

"Active" is ambiguous: an IKE SA up does not mean a child SA exists for this traffic. So I'd establish three things: direction, the exact prefix pair, and whether this is policy-based IPsec (crypto map / SPD) or route-based (VTI or XFRM interface). That last one decides the diagnosis.

Route-based: the route decides. The packet only enters the tunnel if the route points at the VTI. ip route get 10.2.2.9 returning dev eth0 instead of dev vti0 means it egresses cleartext and the SA is irrelevant. Policy-based: the SPD is consulted and first match wins, so a bypass entry above the protect entry, or a selector that no longer matches after NAT, sends it cleartext.

Core answer: bypass means the packet never matched a protect policy, matched a bypass/discard rule first, or was never routed into the tunnel. The SA being up says nothing about whether this packet matched.

Mechanism

Outbound, the kernel or router resolves the route, then consults the SPD for the packet's selectors. A protect match bundles it to the tunnel; no match, or an earlier bypass match, and it leaves as-is. Inbound is the mirror: the decapsulated inner packet must match an inbound policy or it is dropped. That looks like "tunnel up, traffic dead," not cleartext.

Artefacts

SymptomMechanismDetection
ESP counter flat, physical interface counter risingroute or SPD never matchedip route get <dst>; ip xfrm policy
#pkts no sa climbing (Cisco)no SA for that selectorshow crypto ipsec sa
Encaps rising, peer decaps flatpath/MTU, not bypasscompare both ends
Decaps rising, app deadinbound policy missingip xfrm policy dir in

Trade-offs

Capture versus counters. Capture is definitive, you see the bytes, but needs a tap and risks payload exposure; use a snaplen and a header filter. Counters are cheap and payload-free but aggregate: they tell you bypass happened, not which selector. Deciding criterion: if encaps increments but the peer's decaps is flat, it is path/MTU, not bypass; if encaps is flat and the physical interface counter rises, it is route/SPD.

Rekey versus policy fix: flushing SAs fixes a stale SA, but if a shadowing bypass rule or route is the cause it recurs within minutes. Rekey only after confirming SPD and route.

Failure modes

  1. Shadowing bypass rule: ordered SPD, first match wins; a wider bypass above the protect entry. Detect: ip xfrm policy order, or crypto map sequence numbers. Cost: silent cleartext for the whole range.
  2. Route preference: a more specific or default route via the physical interface beats the VTI. Detect: ip route get. Cost: all traffic to that prefix cleartext.
  3. NAT before policy: source translated to an address outside the selector. Detect: compare pre/post-NAT addresses; Cisco #pkts no sa climbing.
  4. Stale or wrong SA: SAD holds an SA for a different selector pair. Detect: ip -s xfrm state selectors against the policy. ESP sequence is 32-bit: 2^32 ≈ 4.3e9 packets, about 13 hours at 1 Gbps of 1400-byte packets, so a volume-based rekey fires first.
  5. Asymmetric policy: outbound protected, inbound policy missing. Detect: ip xfrm policy dir in. Drops, not cleartext.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Troubleshoot an established tunnel with no application connectivity.

Answer

Core answer

Assume the tunnel is up (IKE SA established, both peers reachable) and the complaint is one application flow failing. First 60 seconds: pin the scope. Which source IP, destination IP, protocol, port, and is it one direction or both? When did it last work? Then localize with one number: compare the sender's ESP encrypt counter against the receiver's decrypt counter for the same SPI. That single comparison splits the problem in half: below the tunnel or above it.

If encrypt increments and decrypt does not, packets leave the sender and die in transit (routing, NAT, MTU, policy drop). If both increment, the tunnel is doing its job and the fault is above it: routing to the app host, a firewall, or the listener. If neither increments, the sender isn't selecting the traffic at all: a selector or route problem.

Commands (strongSwan 5.9, Linux):

ipsec statusall          # SA state, bytes_i/bytes_o, rekey timers
ip xfrm state            # per-SA counters, SPI, selectors
ip xfrm policy           # what traffic is being matched

Cisco: show crypto ipsec sa gives #pkts encaps / #pkts decaps per SPI.

Counter table

sender encapsreceiver decapsdiagnosis
risingrisingtunnel fine: look above: route to host, host firewall, listener
risingflatin-transit loss: MTU black hole, NAT-T UDP 4500 dropped, policy drop at receiver
flatflatsender not selecting traffic: route/VRF, selector mismatch, SPD ordering

MTU arithmetic: the most common "tunnel up, app broken" cause. ESP tunnel mode with AES-GCM adds 20 (outer IP) + 8 (ESP) + 8 (IV) + 2 (trailer) + 16 (ICV) = 54 bytes. A 1500-byte path leaves 1446 for the inner packet. If the app sets DF and PMTUD is blocked by an ICMP-filtering firewall, the TCP handshake (small packets) succeeds and the first large transfer stalls: the classic black hole. Detect with ping -M do -s 1420 <peer> stepping down, or tracepath.

Trade-offs / deciding criteria

  • Capture on the gateway vs on the host: gateway capture shows whether the packet was encrypted and forwarded; host capture shows whether it arrived. Capture both ends of one flow before touching config: it's read-only and reversible.
  • Change config vs gather evidence: change one layer at a time, and only after the counter comparison tells you which half to work in. A config change without that evidence can mask the real fault.
  • Rekey vs restart: if counters are frozen but the SA shows established, check rekey timers (strongSwan CHILD_SA default 1h, IKE 4h). A failed rekey leaves a stale SA that still looks up.

Failure modes and detection

  • Asymmetric SA / routing: return traffic exits a different path and misses the SA. Detect: compare ip xfrm policy on both peers; check the return route.
  • Selector mismatch: proxy IDs must mirror. Detect: ipsec statusall shows the negotiated TS; a flat encaps counter with traffic present confirms it.
  • NAT-T mapping expiry: UDP 4500 keepalives stop, mapping drops. Detect: ipsec statusall shows NAT-T; check DPD (default 30s) and keepalive.
  • Stale DNS / proxy / app authz: tunnel counters rise on both ends but the app still fails. Check the listener with ss -lntp and the app's own auth logs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Walk me through how DMVPN builds a spoke-to-spoke tunnel with mGRE and NHRP, and when traffic still hairpins through the hub.

Answer

Clarify first: which DMVPN phase, whether spokes run mGRE or point-to-point GRE, and whether the tunnel is IPsec-protected. The answer changes materially.

DMVPN is three pieces glued together. mGRE gives the hub one tunnel interface that terminates many peers with no per-peer tunnel destination. NHRP is the address-resolution layer that maps a tunnel IP (10.0.0.3) to the NBMA address that actually reaches it (198.51.100.3). A routing protocol runs over the tunnel so spokes learn each other's prefixes. The hub is the NHRP next-hop server: every spoke registers its tunnel/NBMA pair with it and refreshes it, and the hub's NHRP table is the only place that knows all spokes.

Spoke-to-spoke is a resolution, not a routing decision. In phase 3:

  1. Spoke A (10.0.0.2, NBMA 203.0.113.2) sends a packet to 10.0.0.3. It has no /32 for that address, so it matches the summary route out Tunnel0 and GRE-encapsulates to the hub.
  2. The hub decapsulates, sees a spoke sending to another spoke's tunnel IP, and sends an NHRP redirect to A. It also forwards the packet to B: the first packet always hairpins.
  3. A sends an NHRP resolution request for 10.0.0.3 to the NHS. The hub forwards it to B, which replies directly to A with its NBMA address.
  4. A installs an NHRP mapping and a /32 route for 10.0.0.3 via Tunnel0 with NBMA next hop 198.51.100.3.
  5. Later packets are GRE-encapsulated straight to 198.51.100.3. The mapping ages out on the NHRP holdtime; when it does, the /32 disappears and the next flow hairpins again.

Cisco IOS configuration that makes this work:

! hub interface Tunnel0 ip address 10.0.0.1 255.255.255.0 ip nhrp network-id 100 ip nhrp map multicast dynamic ip nhrp redirect tunnel source GigabitEthernet0/0 tunnel mode gre multipoint tunnel protection ipsec profile DMVPN

! spoke interface Tunnel0 ip address 10.0.0.2 255.255.255.0 ip nhrp network-id 100 ip nhrp nhs 10.0.0.1 nbma 203.0.113.1 multicast ip nhrp shortcut tunnel source GigabitEthernet0/0 tunnel mode gre multipoint tunnel protection ipsec profile DMVPN

When traffic still hairpins:

ConditionWhyHow you see it
Phase 1 topologySpokes are point-to-point GRE to the hub; no spoke-to-spoke path existsshow interface tunnel0 shows a tunnel destination
Phase 2 with no specific routeSpoke has only a summary or default via the tunnel, so nothing triggers resolutionshow ip route 10.0.0.3 shows the summary, not a /32
ip nhrp redirect missing on hub, or ip nhrp shortcut missing on spokeHub never tells the spoke to resolve; spoke never installs the /32NHRP counters show no redirects or shortcuts
NHRP registration failingnetwork-id or authentication mismatch, or NHS unreachableshow ip nhrp empty or stale on the hub
Spoke behind NAT without the NHRP NAT extensionSpoke registers a private NBMA address no other spoke can reachHub's NHRP table shows an RFC 1918 NBMA address
Spoke-to-spoke NBMA path blockedUnderlay ACL or firewall, or spokes in different VRFs or address familiesResolution request sent, no reply
IPsec profile unusable for dynamic peersStatic peer or non-dynamic crypto map, or no matching profile on the spokeDirect tunnel never comes up; hub path still works
Destination genuinely behind the hubCentral service, or the hub is the only exitCorrect behaviour, not a fault

Detection: show ip nhrp on the spoke for the mapping and its state, show dmvpn on the hub for peer state and whether the path is direct or via the hub, and NHRP counters for resolution requests sent versus replies received. Check MTU too: mGRE overhead is the same either way, but the spoke-to-spoke underlay path can have a smaller MTU than the path to the hub, so a direct tunnel can expose a size-dependent failure that hairpinning was masking.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Secure a VXLAN overlay across an untrusted underlay.

Answer

Assumptions first. The underlay is untrusted: a provider L3VPN, a shared colo fabric, or a DC network where a compromised host can send arbitrary UDP. I control both VTEPs and the EVPN control plane; I trust nothing in between. The job is to keep tenant A's traffic out of tenant B's VRF and keep an on-path attacker from injecting or reading frames.

Core answer: VXLAN is encapsulation, not security. RFC 7348 defines an 8-byte header carried in UDP/4789 (IANA-assigned; early Linux and VMware used 8472). There is no authentication, no sequence number, no confidentiality. Anyone who can reach a VTEP's UDP/4789 can inject a frame with any VNI and any inner MAC. Security is layered on top, in three places.

Layer 1: control plane. EVPN (RFC 7432) over BGP is the control plane. Authenticate the BGP session with TCP-AO (RFC 5925), or TCP-MD5 where AO isn't available, and scope route exchange with route targets: tenant A's VRF imports only RT 65000:100, tenant B only 65000:200. A route leak is an RT imported into the wrong VRF: tenant A's /24 appears in tenant B's table. Detect it by diffing the VRF's RIB against the intended RT set; a mismatch is a leak, not a routing quirk.

Layer 2: data-plane source filtering. On each VTEP, an ACL that permits UDP/4789 only from the IPs of known peer VTEPs and drops everything else. That is what stops a spoofed VTEP: an attacker sending a VXLAN frame with a legitimate VTEP's source IP is dropped at ingress. Count the drops: a nonzero counter is the detection signal. Pair it with access-side anti-spoofing (IP source guard, dynamic ARP inspection) so a tenant host can't claim another tenant's MAC or IP.

Layer 3: cryptography, when required. If the underlay is genuinely untrusted and confidentiality or integrity matters, add IPsec ESP (RFC 4303) between VTEPs, or MACsec (802.1AE) on each link. The deciding criteria:

IPsecMACsec
ScopeEnd-to-end, VTEP to VTEPHop-by-hop, per link
Routed underlayWorksOnly if every hop runs it
OffloadOften software at scaleLine-rate in hardware
Overhead~50–73 bytes (ESP)~32 bytes (SecTAG + ICV)

MACsec is wrong when the underlay is a routed provider network you don't control: you can't run MKA (802.1X-2010) on someone else's routers. IPsec is wrong when you need 100G line rate without hardware offload; the VTEP CPU becomes the bottleneck.

MTU. VXLAN overhead is 50 bytes (14 outer Ethernet + 20 outer IP + 8 UDP + 8 VXLAN), 54 with an outer 802.1Q tag. On a 1500-byte underlay that leaves 1450 for the tenant. Add IPsec and you lose another ~50–73 bytes. Set the underlay to 1550–1600, or jumbo 9000, and verify with DF-bit pings end to end. Silent drops from an MTU mismatch look like random application timeouts: the classic symptom.

Failure modes and detection.

  • Spoofed VTEP: ingress ACL drop counter climbs. Alert on it.
  • Route leak: RT mismatch in the VRF RIB. Alarm on unexpected prefixes.
  • Replay: only meaningful at the IPsec layer (anti-replay window). VXLAN itself has no sequence number, so "replay" of raw VXLAN is just injection.
  • Underlay MITM: IPsec ESP auth failures, or MACsec MKA session drops.
  • Key rollover: IPsec SA rekey (default 1 hour / 4 GB on many stacks) or MACsec CAK rollover. A misconfigured rollover drops the tunnel: test it in a maintenance window, not in production.

Management. Keep VTEP management (SSH, gNMI) on an out-of-band network, not the underlay. Rotate IPsec/MACsec keys on a schedule: 24 hours is a common IPsec SA lifetime; shorter if the threat model demands it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Choose a tunnel and protection mechanism for an overlay.

Answer

Assumptions. Three regions plus one on-prem DC, ~10 Gbps aggregate, tenants need L3 isolation, and the underlay is provider networks plus a leased line I don't control. Traffic is latency-sensitive RPC, so per-packet cost matters.

Choice: VXLAN for encapsulation, WireGuard for protection. VXLAN gives a 24-bit VNI (16.7M segments), so tenant isolation is a header field rather than a VLAN tag, and it rides UDP over any underlay. WireGuard gives a fixed suite (Curve25519, ChaCha20-Poly1305, BLAKE2s) with no cipher negotiation to misconfigure, and a kernel datapath since Linux 5.6. I run WireGuard on the VTEP hosts and put VXLAN inside it, so the VNI is never visible on the wire.

Why not the alternatives.

optionwins whencost
VXLAN + WireGuardyou own both ends, Linux hosts, want simple cryptono cipher agility, no dynamic peer discovery: you need FRR or BIRD over wg0 for routing
IPsec/IKEv2 ESPinterop with Cisco/Juniper, NIC crypto offload, dynamic peerslarge policy config surface, IKE negotiation, DPD blackholes
TLS VPN (OpenVPN/OpenConnect)peers behind hostile middleboxes, per-user SSO authuserspace datapath, TCP-over-TCP head-of-line blocking if you tunnel over TCP

If the underlay is already encrypted (MACsec on the leased line, or a cloud provider's encrypted inter-region link) skip WireGuard. You pay roughly 30–40% throughput for a second layer that protects nothing.

MTU is where this breaks. VXLAN adds 50 bytes (outer IPv4 20 + UDP 8 + VXLAN 8 + inner Ethernet 14). WireGuard adds 60 for IPv4 (20 + 8 UDP + 32 header and tag). Total 110, so a 1500-byte underlay leaves 1390 for the inner payload.

# underlay MTU 1500
# wg0: 1500 - 60 (WireGuard over IPv4) = 1440
ip link set wg0 mtu 1440
# vxlan0: 1440 - 50 (VXLAN) = 1390
ip link add vxlan0 type vxlan id 42 dstport 4789 local 10.200.0.1 dev wg0
ip link set vxlan0 mtu 1390
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu

Set dstport 4789 explicitly: that is the IANA assignment, while Linux's historical default is 8472, and a mismatch is a silent blackhole. Note also that wg-quick defaults the interface MTU to 1420, which assumes an IPv6 underlay: set 1440 by hand for IPv4.

Failure modes and how I'd catch them.

  • MTU blackhole. PMTUD depends on ICMP type 3 code 4, which clouds and firewalls routinely drop. Small pings succeed while large transfers stall. Detect with ping -M do -s 1362 <peer> from inside the overlay (1390 − 20 IP − 8 ICMP). Fix with the MSS clamp above plus an explicit inner MTU.
  • Rekey storms. WireGuard rekeys at 120s and hard-rejects at 180s. Thousands of peers behind one NAT all handshake against a single listener. Detect via wg show latest-handshakes and the handshake rate on the listener. Mitigate with multiple listeners, and PersistentKeepalive = 25 only on NAT-bound peers.
  • VXLAN flood-and-learn. Without a control plane, unknown unicast and ARP flood to every VTEP, and broadcast scales with tenant count. Detect by watching per-VNI broadcast rate. Fix with EVPN over BGP, or a routed L3 overlay instead of L2 stretch.

In the room: VXLAN + WireGuard, inner MTU 1390, MSS clamped, EVPN for the control plane, and no second crypto layer if the underlay is already protected.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Connect two sites with overlapping address space.

Answer

Core answer (first 90 seconds)

Before picking a mechanism I'd pin down three things: how many hosts actually need to talk, whether any application embeds IP addresses in its payload (FTP, SIP, IPsec, DNS A records), and whether this interconnection is permanent. Those decide everything.

If it's a permanent merger and I control both sides, I readdress one site. It's a one-time cost (DHCP scopes, static assignments, DNS, firewall rules, monitoring) and afterwards everything is end-to-end clean: no ALGs, no tunnel MTU surprises, real addresses in every log. For a /16 that's weeks of coordinated work, but you pay once and stop thinking about it.

If readdressing isn't feasible (temporary project, a third party I don't control, or thousands of hosts) I do double NAT with a network-level static mapping. Each site's overlapping /16 is translated to a unique /16, and both sides translate. Static mapping is what makes return traffic work without a stateful NAT table.

Mechanism

Say both sites use 10.10.0.0/16. On router A: ip nat inside source static network 10.10.0.0 172.16.10.0 /16. On router B: ip nat inside source static network 10.10.0.0 172.16.20.0 /16. One command maps the whole /16, preserving host bits, so 10.10.1.5 becomes 172.16.10.5.

Trace, A host 10.10.1.5 to B host 10.10.1.7:

  • A host sends src 10.10.1.5, dst 172.16.20.7 (learned from split-horizon DNS).
  • Router A rewrites src to 172.16.10.5; on the tunnel: src 172.16.10.5, dst 172.16.20.7.
  • Router B rewrites dst to 10.10.1.7; delivers src 172.16.10.5, dst 10.10.1.7.
  • Return: B host sends to 172.16.10.5; router B rewrites src to 172.16.20.7; router A rewrites dst to 10.10.1.5.

Both directions are static, so there's no state to age out and no asymmetry problem. Routing: A needs a route for 172.16.20.0/16 over the tunnel, B for 172.16.10.0/16; the real 10.10.0.0/16 stays local on each side. A VRF keeps the two routing domains separate on shared gear, but VRF alone doesn't connect overlapping hosts: you still NAT at the boundary.

Readdress vs double NAT

Readdress one siteDouble NAT
Host changesevery host, DHCP/static, DNSnone
Time for a /16weeks to monthshours to days
Embedded IPs (FTP, SIP, IPsec)fixed at sourceneed ALG or app config
Troubleshootingreal end-to-end IPstwo address spaces, harder
MTUnonetunnel overhead, 24–80 bytes
Ongoing costone-timepermanent

Deciding rule: permanent and I own both sides → readdress. Temporary or third-party → NAT.

Failure modes and detection

  • FTP active mode or SIP: the payload carries 10.10.x.x and NAT doesn't rewrite it. Detect with a capture showing the embedded address after the control channel opens. Fix with an ALG or passive mode.
  • Missing split-horizon DNS: a client resolves the peer to 10.10.x.x, routes it locally, and the packet never leaves the site. Detect by seeing the connection hit its own subnet with no NAT translation entry.
  • Translated-range collision: 172.16.10.0/16 already in use elsewhere. Detect by checking the route table before cutover.
  • MTU black hole: GRE+IPsec overhead with PMTUD blocked. Detect with ping -s 1472 failing while 1400 succeeds.
  • Pool exhaustion if you use dynamic NAT instead of static network mapping. Detect with show ip nat statistics and translation-failure counters.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Prevent a tenant route leak in an L3VPN.

Answer

Core answer. In an MPLS L3VPN (RFC 4364), a tenant leak happens when a VRF imports a route it shouldn't. The RD does not isolate tenants: it only makes the VPN-IPv4 prefix unique in MP-BGP. Isolation is entirely the Route Target import/export policy. So: give every VRF a unique RD, give every tenant a unique export RT and an explicit import list naming only the RTs it is entitled to, never a wildcard, and verify by reading the VRF RIB, not the config.

Assumptions: single provider, MP-BGP VPNv4/VPNv6 with route reflectors, PE-CE is eBGP or OSPF/static, shared services (firewall, internet, DNS) live in their own VRFs.

Mechanism. On the egress PE the tenant route becomes a VPN-IPv4 route: RD + prefix, tagged with the export RT as an extended community. The route reflector carries it to every PE. On the ingress PE each VRF has an import RT list; a route is installed in that VRF's RIB only if its RT community matches an entry. Two ways this goes wrong:

  • Overlapping import: tenant A's VRF imports RT 65000:100, which tenant B also exports. B's prefixes land in A's RIB and FIB. Nothing looks wrong per-VRF; the collision is only visible in the matrix.
  • Transitive sharing: a shared-service VRF imports tenant RTs and re-exports them under a common RT that all tenants import. Now A reaches B through the shared VRF. This is the classic hub-and-spoke leak.

Controls, with numbers.

  • RD: unique per VRF per PE, e.g. 65000:1 … 65000:N or loopback:nn. If two VRFs on one PE share an RD and carry the same prefix, MP-BGP sees one VPN-IPv4 route and one tenant silently loses its route.
  • RT matrix: one export RT per tenant, import list explicit. Table below.
  • SOO (site-of-origin) extended community on PE-CE to reject routes that loop back.
  • maximum-prefix on the MP-BGP neighbor and PE-CE session, e.g. 1000 prefixes, warn at 80%: bounds a leak's blast radius.
  • Import default: on IOS-XR and Junos, a VRF with no import route-target/policy imports nothing. Verify on your platform; do not assume.

RT matrix (example):

VRFExport RTImport RTs
tenant-A65000:10065000:100, 65000:900 (shared)
tenant-B65000:20065000:200, 65000:900
shared-svc65000:90065000:100, 65000:200

shared-svc imports both tenant RTs but must not re-export them; its export is only 65000:900.

Trade-offs. Per-tenant RTs give clean isolation but scale the RT count and MP-BGP churn; a shared RT (all tenants in one "internet" VRF) is simpler and leaks by design. Hub-and-spoke with a single hub RT is easy to operate but only safe if the hub never re-exports spoke routes. Centralized RT policy on a route server is easier to audit than per-PE config, but one bad entry leaks to everyone. SOO is automatic and per-site; prefix filters are manual and drift.

Failure modes and detection.

  • Shared-service VRF exports a tenant RT → every tenant importing it sees that tenant. Detect: show bgp vpnv4 unicast vrf shared-svc shows a tenant RT in the export set.
  • Hub re-exports spoke routes → spoke-to-spoke reachability. Detect: canary /32 per tenant; alarm if it appears in another VRF's RIB.
  • Wildcard import (route-target import *) → total leak.
  • RD collision on one PE → silent route loss.

Canary: export a per-tenant /32 with the tenant RT; poll each VRF RIB (show route table tenant-B.inet.0) for foreign canaries; alert on any hit. That is the alarm: a RIB diff, not a config lint.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Deploy a full-tunnel default route without recursive failure.

Answer

Assume Linux, WireGuard, one physical uplink, and an endpoint at a fixed address: 203.0.113.7:51820. With the physical gateway at 192.168.1.1 on eth0. The failure I'm designing around is recursion: the tunnel's own encrypted packets are UDP to 203.0.113.7, and if the only route to that address is the tunnel's default, the kernel feeds the outer packet back into wg0 and the handshake never completes.

The fix is longest-prefix match. Install a host route to the endpoint through the physical gateway before you install the default through the tunnel:

ip route add 203.0.113.7/32 via 192.168.1.1 dev eth0
ip route add 0.0.0.0/0 dev wg0

The table now reads:

default dev wg0 scope link
203.0.113.7 via 192.168.1.1 dev eth0
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.50

A /32 always beats a /0, so the two lookups separate cleanly. Trace a packet to 8.8.8.8:443: the first lookup matches default dev wg0, so it is encrypted and the outer packet becomes 192.168.1.50:ephemeral → 203.0.113.7:51820. The second lookup, for that outer packet, matches the /32 and leaves via 192.168.1.1 on eth0. No recursion. Had you installed the default first, the outer packet would match default dev wg0 again and re-enter the tunnel. Do both in one ip -batch so there is never a window where the default exists without the pin.

wg-quick does the same job with policy routing instead of a static /32: it sets fwmark 51820 on the interface, adds ip rule add not fwmark 51820 table 51820 and ip rule add table main suppress_prefixlength 0, then puts the default in table 51820. Encapsulated packets carry the mark, skip the first rule, and fall through to main, where the endpoint route still lives, while everything else hits table 51820. The advantage is that the main table's default is never clobbered, so LAN and endpoint routes stay dynamic; the cost is that you need policy routing and the mark, and debugging is harder because ip route get alone does not show which rule fired.

When not to do this: if you only need internal subnets, split tunnel. Full tunnel pushes all your traffic, bulk downloads included, through the peer's bandwidth and adds its RTT to every flow.

Failure modes worth naming. If the endpoint is a hostname with rotating A records, a pinned /32 goes stale the moment the client resolves a different address: pin every resolved address, or re-add the route on each connect. IPv6 needs the same treatment: ::/0 dev wg0 plus a /128 to the endpoint, or v6 leaks out the physical path. DNS is a chicken-and-egg: if resolv.conf points at a resolver only reachable through the tunnel, resolving the endpoint hostname fails before the tunnel is up. Stage DNS after the tunnel, or keep a physical-path resolver for that one lookup. Captive portals cannot be reached once the default is the tunnel, so detect the portal and defer. On sleep/resume the physical gateway often changes, leaving the pinned /32 pointing at a dead next hop; re-apply on resume. And the default route alone is not a kill switch, when the tunnel drops, traffic falls back to the physical path. Add a firewall rule that drops egress not marked 51820 and not addressed to the endpoint.

Health: wg show wg0 latest-handshakes should advance at least every two minutes while the tunnel is passing traffic; ping the tunnel's internal gateway (10.0.0.1 in this example) for the data path. Rollback is wg-quick down wg0, which removes the rules and routes, or ip route replace default via 192.168.1.1 dev eth0 if you installed them by hand.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Threat-model full versus split remote-access VPN.

Answer

Assumptions: remote-access VPN for a workforce on untrusted home/hotel networks; corporate resources in a few RFC1918 ranges plus SaaS; you control the gateway and can push routes and DNS.

Core answer. The decision isn't "which is more secure": it's where you enforce policy. Full tunnel makes the corporate gateway the single egress for every packet, so DNS, egress filtering, DLP and logging apply uniformly, at the cost of hairpinning all user bandwidth through the gateway. Split tunnel sends only corporate-destined traffic through the tunnel and lets everything else go direct, which offloads the gateway but moves enforcement onto the endpoint and its local network. Default to full tunnel unless gateway capacity or latency forces split; if you split, treat the endpoint as an untrusted bridge.

Mechanism. Full tunnel installs a default route via the tunnel interface: OpenVPN redirect-gateway def1, WireGuard AllowedIPs = 0.0.0.0/0, ::/0. Every packet, DNS included, exits at the gateway, so the corporate resolver answers internal names and egress policy sees all flows. Split tunnel keeps the physical default route and adds only corporate prefixes via the tunnel: WireGuard AllowedIPs = 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. The endpoint is now logically inside the corporate network and physically on the home LAN at once. That dual position is the threat: malware on the endpoint can reach local peers, a hostile LAN can reach the endpoint, and the corporate side still sees the endpoint as a trusted internal host. A pivot. Full tunnel doesn't remove the physical adjacency, but it removes the endpoint's ability to reach arbitrary Internet hosts directly, so exfiltration has to pass the gateway.

Full tunnelSplit tunnel
Egress pathGateway for all trafficGateway for corporate prefixes only
DNSCorporate resolver for everythingLocal/DoH unless explicitly pinned
Gateway loadAll user bandwidthCorporate traffic only
Endpoint roleInspected clientTrusted internal host on a hostile LAN

Capacity arithmetic. 500 remote users, full tunnel, each averaging 2 Mbps of non-corporate traffic (video, updates, browsing) = 1 Gbps of gateway egress that split tunnel would have sent direct. Size the gateway and its Internet circuit for peak concurrent sessions, not the average.

Failure modes and detection.

  • IPv6 leak: split tunnel pushes only IPv4 routes; home ISPs hand out native IPv6, so IPv6 traffic goes direct. Detect: ip -6 route on the endpoint shows a default via the physical NIC, or compare the egress IP seen by an IPv6-only destination against the corporate egress.
  • DNS leak: browser DoH or the local resolver answers instead of the pushed one. Detect: dig TXT o-o.myaddr.l.google.com @8.8.8.8 versus the corporate resolver, or query an internal-only name and see whether it resolves.
  • Route overlap: home LAN and corporate both use 192.168.1.0/24; the on-link route wins and corporate hosts become unreachable. Detect: ip route get 192.168.1.10 returns the physical interface.
  • SaaS range drift: split-tunnel include lists go stale as providers rotate ranges. Detect: monitor the provider's published endpoint feed and alert on diff.
  • Tunnel loss: split tunnel fails quietly for corporate traffic while Internet keeps working; full tunnel fails loudly. Detect: heartbeat to an internal host, alert on loss.

When not to use. Don't split if you can't maintain the destination list or enforce endpoint posture: the include list becomes the security boundary. Don't full-tunnel if the gateway or circuit can't absorb the hairpin, or if voice/video latency matters: hairpinning adds RTT and jitter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design leak-proof always-on remote access.

Answer

Clarify, then answer. "Leak-proof" means no packet that should be protected leaves a non-tunnel interface, not at boot, not mid-reconnect, not after a route change, not for IPv6, not for DNS. The threat isn't the tunnel failing; it's the tunnel failing and the OS silently falling back to the physical NIC.

Assumptions: managed laptop fleet, one tenant, WireGuard as the tunnel, endpoints are a small set of static anycast IPs, Linux/macOS/Windows clients. Change any of those and the design shifts: I'll flag where.

The design is three layers, and the ordering is the whole point:

  1. A fail-closed egress firewall installed before the tunnel interface exists and removed after it's gone.
  2. Routes and DNS bound to the tunnel interface, with the resolver reachable only through it.
  3. On-demand reconnect with a bounded handshake budget.

Invariant: the only egress permitted outside wg0 is DHCP and UDP to the endpoint IPs.

Layer 1: firewall, and why not routes.

The cheap kill switch is route-based. wg-quick on Linux does exactly this: ip rule add not fwmark 51820 table 51820 plus ip rule add table main suppress_prefixlength 0, which suppresses the main table's default route so traffic falls through to the WireGuard table. It's free and it works, until it doesn't. suppress_prefixlength 0 only suppresses prefix length 0, so any more specific route in main (a /24 for the office LAN, a route another VPN client installed, a link-local route) still wins and leaks. It's also IPv4-only unless you add the v6 rules.

So use a firewall with policy drop:

NFT
table inet wgkill {
  chain out {
    type filter hook output priority filter; policy drop;
    oifname "lo" accept
    oifname "wg0" accept
    udp dport { 67, 547 } accept          # DHCPv4/v6 bootstrap
    ip  daddr { 203.0.113.10, 203.0.113.11 } udp dport 51820 accept
    ip6 daddr { 2001:db8::10, 2001:db8::11 } udp dport 51820 accept
  }
}

Everything else is dropped, including DNS to the DHCP-provided resolver, which is the point. Pin the resolver to an address inside the tunnel (10.0.0.53) so name resolution can't happen off-tunnel.

Layer 2: ordering.

The firewall must be loaded before the NIC can send. On Linux, a systemd unit ordered Before=network-pre.target. On Windows, WireGuard's WFP filters (BlockUntunneledTraffic = true in the tunnel config) are installed by the service at boot. On Apple platforms you don't write this: NEVPNProtocol.includeAllNetworks (iOS 14+/macOS 11+) does it in the kernel, with excludeLocalNetworks to carve out the LAN. Android's always-on VPN plus "Block connections without VPN" is the same idea.

Layer 3: reconnect.

WireGuard retries a handshake every 5 s for up to 90 s (REKEY_TIMEOUT / REKEY_ATTEMPT_TIME), then stops until there's traffic. PersistentKeepalive = 25 keeps NAT mappings alive. The firewall doesn't care whether the handshake succeeded: it only ever allowed the endpoint.

Trace: cold boot.

t (s)eventegress permitted
0.0firewall loaded, NIC upDHCP only
0.4DHCP lease, DNS pinned to 10.0.0.53DHCP only
0.6wg0 created, handshake sentendpoint UDP
0.9handshake donewg0
47.0tunnel dropsendpoint UDP
47.5rehandshakeendpoint UDP
48.0restoredwg0

The window that matters is 0.0–0.9. Order the firewall unit after network-online.target instead and that window is ~1.2 s on a cold boot (hypothetical: measure on your image), long enough for a browser's first DNS query.

Trade-offs.

  • Route-based kill switch: free, nothing to maintain, fails open on specific routes. Fine for a single-purpose appliance, not a laptop.
  • OS-native always-on: enforced below your app, but you lose the exception list. includeAllNetworks without excludeLocalNetworks breaks printers and AirPlay.
  • Split tunnel: cheaper. Full tunnel backhauls every packet to the PoP, so a Sydney user on a us-east-1 PoP goes from ~15 ms to ~180 ms RTT. But every excluded prefix is a leak surface you now have to firewall.

Failure modes.

  • DNS leak on drop: resolver reverts to DHCP. Detect with a canary name only the internal resolver answers; alert if it resolves externally.
  • Captive portal: fail-closed means the user can't reach the portal. You need an explicit, user-initiated, time-boxed portal mode opening only the portal IP for ~5 minutes. Without it, users disable the VPN.
  • Endpoint rotation: pinning IPs breaks when the anycast set changes. Detect via fleet-wide handshake-failure rate.
  • Sleep/wake: a NetworkManager reconnect can flush nftables. Probe after resume.
  • IPv6: a v4-only ruleset leaks v6. Dual-stack canary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design zero-trust controls around a remote-access VPN.

Answer

First, what I'd clarify: is this a TLS or IPsec concentrator, and do users need raw L3 reachability to legacy apps, or is everything HTTP? That decides whether the VPN stays at all. I'll assume an IPsec/TLS remote-access concentrator fronting a mix, and the goal is that a valid tunnel grants reachability to a policy proxy: never to the app itself.

The core move is to demote the VPN from a trust boundary to a transport. Three things get bound together at connect: the user, the device, and the session.

User auth: WebAuthn/FIDO2 security key or passkey. Not push-based MFA: push is relayable in real time by an adversary-in-the-middle proxy and fatigable. Device auth: a TPM-backed, non-exportable key, presented as an IKEv2 machine certificate or a client cert in the TLS handshake. The private key can't be copied off the machine, so a stolen config file is inert.

Posture is evaluated by the MDM/EDR control plane (Intune, Jamf, CrowdStrike) not by the client self-reporting, because self-report is spoofable. Check disk encryption (FileVault/BitLocker), OS patch level, EDR agent healthy and checking in, screen lock. Fail posture → quarantine VLAN with only remediation endpoints reachable.

Session bounding: the concentrator issues a short-lived session, say 15 minutes, with a token bound to the device key via DPoP or mTLS, so a stolen token is useless on another machine. Posture is re-evaluated on a timer, not just at connect.

Least privilege: don't push a full-tunnel route table. Push only the routes the user's group needs, and put the user in a dedicated segment behind the concentrator. Then require app-level auth, SSO plus mTLS, to reach the app. The VPN gives you a path to the proxy; the proxy decides.

Trade-off: full tunnel vs split tunnel. Full tunnel routes everything through the concentrator: easier to inspect, but you pay bandwidth and hairpin cloud traffic back through your DC. Split tunnel is faster, but the endpoint sits on two networks and can bridge them; mitigate with host firewall rules that block forwarding. The bigger alternative is dropping the VPN: ZTNA with single-packet authorization (Cloudflare Access, Zscaler Private Access) or a WireGuard mesh (Tailscale) gives per-app access without L3 reachability. Choose the VPN only if you need raw L3 to legacy apps.

Failure modes, what the control does, and how you detect it:

FailureControl responseDetection
Stolen credential + relayed MFADevice key missing, handshake failsAuth success without a device cert
Cloned config / exported certKey non-exportable, clone can't complete handshakeSame cert from two source IPs at once
Unmanaged devicePosture fails → quarantine VLANMDM enrollment-gap report
EDR disabled mid-sessionContinuous re-check → session terminatedEDR "agent stopped" event correlated with an active session
Role removedToken TTL expires (≤15 min) or push revocationResource hit logged after the role change
Session token stolenDPoP/mTLS binding rejectsToken used from a different key thumbprint
Concurrent loginPolicy kills the prior sessionTwo live sessions, same identity
Revocation service unreachableFail closed for high-value appsOCSP/CRL fetch errors
Emergency recoveryBreak-glass account, monitoredBreak-glass login alert

A session trace: user presents FIDO2 key → device cert validated against TPM attestation → MDM reports FileVault on, EDR healthy → concentrator pushes three routes and a 15-minute DPoP-bound token → user hits the app proxy, which demands SSO + mTLS → at minute 10 the EDR agent stops, the re-check fails, the concentrator tears the tunnel and the token is revoked. That last step is the one people skip: without continuous posture and short TTLs, a compromised endpoint keeps its access until the user disconnects.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Validate VPN rekey under load.

Answer

Assumptions. IKEv2, ESP tunnel mode, Linux XFRM with a strongSwan-style daemon. Rekey is driven by both a time lifetime and a byte/sequence lifetime. "Under load" means the data path is saturated while the control plane rekeys: the interesting failures only appear when the two compete for CPU and for the same selector.

The answer in 90 seconds. A rekey test passes when one sustained bidirectional flow crosses at least three rekey cycles with zero packet loss, zero anti-replay drops, and the new Child SA carrying traffic before the old one's hard lifetime expires. So the test is one long flow plus instrumentation, not a list of knobs. Run iperf3 both directions for 3× the Child SA lifetime, log ip xfrm state/ip xfrm policy and the daemon log with timestamps, and assert three things: the new SA's first packet timestamp precedes the old SA's last packet; the old SA's byte counter stops climbing within the overlap window; no replay or outbound-error counter moves. Everything else (PFS, NAT, clock skew) is a variation you add once the baseline is green.

Why it behaves this way. The soft lifetime fires a CREATE_CHILD_SA exchange; the new SA is installed while the old one is still valid, so both match the same traffic selector. The kernel then picks one, normally the newest, and the old SA's counters should freeze. If they keep climbing, the policy or route is still pinned to the old SPI, and you get a silent black hole the moment the old SA is deleted. That is the single most common rekey bug, and it is invisible unless you watch per-SA counters rather than interface counters.

Trade-offs. PFS (a fresh DH per rekey) costs CPU per exchange; on one tunnel it is noise, on a hub with thousands of spokes rekeying on the same wall-clock second it is the spike. Time-based lifetimes are fine at 1 Gbps; byte-based lifetimes are what save you at 10 Gbps. RFC 7296 has the original IKE_SA initiator drive rekeying to reduce collisions, if you configure both sides to initiate, you are relying on collision handling and will see duplicate SAs.

Failure modes and how you see them.

FailureDetection signalCost
Rekey never completes (peer down, proposal mismatch)old SA expires with no successor; retransmitted CREATE_CHILD_SA, no matching proposaloutage until IKE re-establishes
Both peers initiatetwo Child SAs for one selector; collision resolution deletes oneduplicate DH, transient churn
Selector still pinned to old SPIold SA byte counter climbs after new SA installedblack hole at old-SA deletion
Sequence exhaustion before rekeyoutbound ESP errors, seq near 2^32drops until rekey
Anti-replay after rekeyreplay counter increments on receiveloss that looks like network loss
NAT mapping expires while idlerekey to UDP 4500 unansweredtunnel down until keepalive

Arithmetic that decides your lifetime. A 32-bit ESP sequence number must be rekeyed before 2^32 packets (RFC 4303). At 1 Gbps with 1400-byte packets that is ~89k pps, so ~13.4 hours; at 10 Gbps it is ~1.3 hours. 2^32 packets × 1400 B ≈ 6 TB. So a 1-hour time lifetime is safe at 1 Gbps and marginal at 10 Gbps: set a byte lifetime (e.g. rekey at 100 GB) and let it win. Rekey at ~80% of the hard lifetime with ±10% jitter so a hub's spokes don't all fire together.

Hypothetical trace, 1-hour Child SA, 1 Gbps flow:

t=0.0s     flow up, SA_A spi=0xc0a1
t=2880s    soft lifetime (80%) fires on peer1 -> CREATE_CHILD_SA
t=2880.2s  peer2 replies; SA_B spi=0xc0b2 installed, both match selector
t=2880.3s  first ESP on SA_B; SA_A byte counter frozen  <- assert this
t=2881s    peer1 sends DELETE for SA_A; peer2 acks

Add netem delay/loss/reorder and NAT-T once this is green: a rekey that works on a clean LAN fails when the CREATE_CHILD_SA response is dropped and retransmitted with exponential backoff. Clock skew is mostly a non-issue: IKEv2 lifetimes are relative seconds, so skew shows up as one peer rekeying earlier, not as a failure; it matters for certificate validity, not for rekey.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design liveness and failover for a site-to-site VPN.

Answer

Assumptions. Two sites, IPsec tunnel mode, IKEv2, one or more Child SAs over an internet or MPLS underlay. We control both ends and can run a routing protocol over the tunnel. Requirement: a dead tunnel stops carrying traffic within a bounded time, without flapping when the underlay is merely congested.

Core answer. Liveness is three independent layers; don't collapse them.

  1. IKE SA liveness. IKEv2 has no separate DPD timer: liveness is an empty INFORMATIONAL exchange (RFC 7296 §2.4). "DPD" as a named feature is IKEv1 (RFC 3706). The give-up time is the implementation's retransmission schedule, not a fixed RFC number: exponential backoff, bounded tries. The shape is what matters: with a 500 ms initial timer doubling, eight retransmissions span 0.5+1+2+4+8+16+32+64 = 127.5 s. Shorten it and every shortening multiplies false positives under loss.

  2. Data-path liveness. The IKE SA can be alive while ESP is black-holed: routing change, PMTU black hole, one-way loss. Watch ESP byte and packet counters per Child SA: flat counters while the route says the tunnel is up means a black hole, not a liveness loss. BFD (RFC 5880) over the tunnel gives sub-second detection: defaults are 1 s TX/RX with detect multiplier 3 → 3 s; 300 ms × 3 → 900 ms if the underlay can take it. Run BFD to the tunnel's inner address so the probes are encrypted and actually traverse the ESP path.

  3. Routing failover. Withdraw or deprefer the route: BGP withdraw or local-pref drop, or a static route tracked to tunnel state. Do it atomically so there is never a window with two default paths.

Worked failover. Primary fibre cut, backup MPLS, BFD 300 ms × 3, FRR:

bfd
 peer 10.255.0.2
  transmit-interval 300
  receive-interval 300
  detect-multiplier 3
!
router bgp 65001
 neighbor 10.255.0.2 remote-as 65002
 neighbor 10.255.0.2 bfd
tevent
0.0 sfibre cut
0.9 sBFD misses 3 × 300 ms, peer declared down
0.9 sBGP session down, /24 withdrawn
1.4 sremote FIB installs the backup path
~1.5 straffic flowing

Black-hole window ≈ 1.5 s. The same failure detected by IKEv2 retransmission alone is ~127 s: roughly 80× worse. That gap is the reason to run BFD rather than trust DPD.

Hysteresis. Down after N consecutive misses (3), up only after M successes (5) plus a hold-down before re-advertising (30 s). Without the up-side hysteresis you flap on every congestion burst. Note the asymmetry: BFD's multiplier is the down side; the up side is yours to set.

NAT. If either peer is behind NAT the mapping expires on idle; RFC 7296 §2.23 gives 20 s as the default NAT keepalive. If the mapping lifetime is shorter than the keepalive interval the tunnel dies silently: keep the keepalive shorter than the mapping.

Trade-offs. Aggressive detection (500 ms × 3 ≈ 1.5 s) fails over fast but false-positives on a congested link and triggers a failover storm; the IKEv2 default (~1–2 min) is stable but black-holes traffic for that whole window. Decide by what the application tolerates: a voice path wants BFD at ~900 ms, a batch replication link can live with the default.

Failure modes to test. One-way data loss (BFD passes, ESP drops), IKE-only block (UDP 500/4500 filtered, ESP allowed), remote LAN loss (tunnel up, remote subnet unreachable), CPU pressure on the head-end (probe replies delayed, false failover), and partition (both ends believe they are up).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design high availability for VPN gateways.

Answer

Assumptions I'd state up front: site-to-site IKEv2 (RFC 7296) gateways terminating a few hundred to a few thousand tunnels in one region, peers are third-party devices I don't control, and the requirement is that established tunnels survive a single gateway failure with sub-10-second disruption.

Core answer. Run active/standby behind a floating VIP, synchronize IKE and Child SA state to the standby, and detect failure faster than the peers' own dead-peer detection. Active/active only pays off when tunnels are sharded per node (each peer pinned to one gateway) or the traffic is stateless. A shared VIP with both nodes answering ESP does not work: the peer keys its outbound SA to one SPI and one endpoint, so a second responder is just a black hole.

State sync is the whole game. The peer's ESP packets carry an SPI it negotiated with the primary. A standby that never received that SA drops every packet as "unknown SPI," and the tunnel stays dead until the peer rekeys, which it only does when its own DPD timer fires, commonly 30s or more. So failover time is max(detection, peer DPD) unless you sync. RFC 6311 defines the IKEv2 HA synchronization protocol for exactly this; strongSwan implements it in its ha plugin, and Cisco ASA stateful failover syncs IPsec SAs the same way.

StateSync it?If the standby lacks it
IKE SA keys + SPIsyespeer's IKE requests get no response; full rekey
Child SA keys + SPIsyesESP dropped as unknown SPI until peer DPD fires
Anti-replay windowyeslagging window drops in-flight packets as replays; leading window accepts real replays
NAT-T source port (UDP 4500)yespeer behind NAT is dropped after failover
Config versionyesstandby may enforce a different policy than the SA was built with

Anti-replay deserves its own line: RFC 4303 recommends a 64-packet window (minimum 32). Sync the window position, not just the keys, or you trade dropped packets for accepted duplicates.

Detection. VRRP (RFC 5798) with the default 1s advertisement takes roughly 3s to declare the master down. BFD (RFC 5880) at 300ms × 3 gives ~1s. Use BFD for the data path and VRRP for the VIP.

Worked trace (2000 tunnels, BFD 300ms × 3):

t=0.000  primary NIC fails
t=0.900  BFD declares down (3 x 300ms)
t=0.910  standby promotes, gratuitous ARP for VIP
t=0.950  peer ESP arrives, SPI 0xA1B2C3D4, seq 1042
         standby has the SA, window high-water 1041 -> accepted
t=1.000  tunnel continues, no rekey

Without sync, the same packet is dropped as unknown SPI, the peer's DPD fires at t=30s, IKE rekeys, and the tunnel is back around t=31s: a 30× difference from the same hardware.

Failure modes. Split brain: both nodes claim the VIP, the peer sees ARP flapping and duplicate ESP. Fence with out-of-band power control or a quorum device; a heartbeat alone cannot break the tie. Rekey during failover: if the primary died mid-rekey, the standby may hold the old SA while the peer holds both. Make sync transactional, or accept both SPIs for a grace period. NAT rebinding: the peer's UDP 4500 source port changes; the standby must have the current port or it drops the tunnel (MOBIKE, RFC 4555, handles this in-band).

Capacity. 2000 tunnels × 2 SAs × ~1 KB of state is ~4 MB: trivial. The real cost is the sync channel: with a 1-hour Child SA lifetime (a common default), 2000 tunnels rekey at ~0.6/s, so a few KB/s of sync traffic. Size the standby for the full tunnel count, not half, since it must hold every SA the primary holds.

When not to do this: if peers are cloud-managed and rekey quickly on their own (AWS Site-to-Site VPN gives you two tunnels per connection), a stateless active/active pair with per-tunnel sharding is simpler and avoids the sync channel entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Capacity-plan VPN gateways.

Answer

What I'd say first

Capacity-planning a VPN gateway starts with four inputs, not a bandwidth number: peer/SA count, the packet-size distribution, the rekey policy, and whether HA failover must preserve SAs. The reason is that a gateway saturates on packets per second and crypto operations per second long before it saturates on bits per second. A 10 Gbps link carrying 1400-byte payloads is ~860 kpps; the same link carrying 64-byte payloads is ~10 Mpps. Same bits, ~12x the work.

Why pps dominates

ESP tunnel mode with NAT-T adds roughly 60 bytes per packet: 20 IPv4, 8 UDP, 8 ESP header, 8 explicit IV, 16 GCM ICV, ~2 pad/next-header. A 64-byte payload becomes ~124 bytes on the wire, so 1 Gbps / (124 x 8) is about 1.0 Mpps. Every one of those packets costs a crypto operation plus the per-packet software path (skb alloc, xfrm lookup, conntrack, qdisc). At 1400-byte payloads the same 1 Gbps is ~86 kpps: 12x fewer crypto ops for the same bandwidth. That is why a gateway that "does 10 Gbps" on a datasheet can fall over at 1 Gbps of VoIP.

Rekey rate is the second axis

Steady-state handshake load is peers divided by SA lifetime.

  • WireGuard: REKEY_AFTER_TIME is 120 s, so 10,000 peers means ~83 handshakes/s continuously.
  • IKEv2 with strongSwan's default CHILD_SA lifetime of 3600 s: 10,000 peers means ~2.8 rekeys/s.

That is a ~30x difference in asymmetric-crypto load. X25519 is ~50 us, so 83/s is nothing in steady state, but on HA failover all 10,000 peers re-handshake at once, and that burst is what takes the box down.

IPsec/IKEv2WireGuard
Rekey defaultCHILD_SA 3600 s (strongSwan)120 s
Handshakes/s at 10k peers~2.8~83
Per-packet overhead~60 B (NAT-T, GCM)~60 B
Crypto offloadNIC/ASIC availablekernel only
HA SA syncmature cluster state syncstateless; peers re-handshake

Trade-offs

  • Software vs hardware crypto: AES-GCM with AES-NI runs ~1-3 GB/s per core; without AES-NI (older ARM, some virtualized hosts) it drops to tens of MB/s, and ChaCha20-Poly1305 becomes the right choice. Check lscpu for the aes flag before assuming.
  • IPsec vs WireGuard: IPsec gives hardware offload, IKEv2 flexibility and mature HA state sync; WireGuard gives a simpler data path and much higher rekey churn. Pick IPsec when you need offload or interop; WireGuard when you control both ends and want the smaller code path.
  • Scale-up vs scale-out: both protocols pin a flow to one gateway, so scale-out needs flow affinity (ECMP with consistent hashing, or anycast). Scale-up is simpler until a single box's pps ceiling is the limit.

Failure modes and how to see them

  • pps saturation: ethtool -S rx_no_buffer / rx_dropped climbing, /proc/net/softnet_stat backlog column rising.
  • Rekey storm after failover: IKE SA count spike, handshake p99 latency.
  • MTU black hole: large packets dropped, small ones pass. ping -M do -s 1400.
  • Conntrack table full: nf_conntrack: table full, dropping packet in dmesg.
  • NUMA mismatch: crypto and NIC queues on different sockets, ~1.5-2x latency.

What I'd report

Sustainable capacity at the point where p99 latency, drop, or CPU crosses threshold, with headroom for one-node failure and growth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design VPN observability and audit.

Answer

Start by pinning which VPN and what the audit is for. Assume IKEv2 site-to-site between two gateways plus remote-access clients, NAT in the path, and a compliance requirement to answer "who connected, from where, to what, when" for a year. The design is three telemetry planes sharing one correlation ID per session: control (IKE SA state and negotiation), data (ESP counters per Child SA), and identity (user/device → tunnel → selector). The audit log is identity joined to the other two; the ops dashboard is control plus data. No key material enters any plane.

PlaneRecordDecision it enables
ControlIKE_SA_INIT / IKE_AUTH / CREATE_CHILD_SA / INFORMATIONAL, notify type, proposal, IKE SPI, state-transition timestampsWhy a tunnel won't come up: NO_PROPOSAL_CHOSEN = crypto mismatch, AUTHENTICATION_FAILED = cert/PSK, no reply at all = UDP 500/4500 filtered
Controlrekey and delete events, Child SA SPI, selectors, lifetimeSeparates a clean rekey from a tunnel that died and never returned
Databytes/packets in and out per Child SA, sampledA flatline means traffic stopped even while IKE still says ESTABLISHED
Datadrop counters by reason: replay, auth-fail, fragment/MTU, SPD no-matchEach reason maps to a different fix
Identityuser/device ref, outer address (hashed), inner selector, session start/endThe audit record itself

A rekey trace shows why the split matters. At the Child SA lifetime the gateway sends CREATE_CHILD_SA with a new SPI; the peer replies; the old SA is deleted. You log child_rekey old_spi=0x… new_spi=0x…. If the peer never replies, the old SA expires and ESP drops: you see child_expired followed by bytes flatlining. That two-line sequence is the difference between "rekeyed fine" and "tunnel down," and it is invisible if you only log the final state.

Failure modes and the thresholds that fire them:

  • IKE not ESTABLISHED within 30 s of the first packet → alert. Causes: UDP 500/4500 filtered, PSK/cert mismatch, proposal mismatch.
  • AUTHENTICATION_FAILED rate above ~5/min from one peer → brute force or a client with a stale cert.
  • Outer source address changes on an established IKE SPI → NAT rebind; without MOBIKE/UPDATE_SA_ADDRESSES the SA dies.
  • Fragment/MTU drops rising while ICMP still works → PMTU black hole; the app probe fails while ping succeeds.
  • WireGuard: wg show latest-handshake age past 180 s (REJECT_AFTER_TIME) means the tunnel is dead; rekey normally happens at 120 s.

Trade-offs worth stating out loud. Metadata plus counters versus full packet capture: capture is ground truth but a privacy liability and enormous volume, so default to metadata and capture on demand for incidents. Hashing outer addresses: a keyed HMAC keeps the log joinable to firewall and DHCP records, a plain hash is unjoinable, and a plain address is PII. Rotate the key on a schedule. Sampling counters is cheap but misses microbursts; per-packet accounting is exact and expensive.

Retention arithmetic: 5,000 tunnels rekeying hourly at ~4 lines each is 480k lines/day; at ~300 B/line that is ~144 MB/day, ~52 GB/year. Keep 90 days hot in Loki or Elasticsearch and a year cold in object storage: it fits the compliance window without a large bill.

Curated: · Written: · Reviewed:

Difficulty: Hard