Intro

Cilium provides node-to-node encryption using either IPsec or WireGuard, with some tradeoffs in network performance. While this feature seems quite stable on a small cluster with 4 or 5 nodes, I had an issue running it on a production Kubernetes cluster with thousands of worker nodes due to a race condition between XFRM and cilium-agents. This post covers what the problem was, why Cilium node-to-node encryption was causing such an issue, and how I patched upstream Cilium (cilium/cilium#44701) to mitigate it. The fix is in Cilium 1.19.4 and later, and in 1.20.0 and later.

Background: IPsec

IPsec is short for “Internet Protocol Security”. It contains a group of protocols that secure IP traffic by encrypting and decrypting each IP packet within a session. It also provides protection against replay attacks. In general, IPsec can run in two modes: transport mode and tunnel mode. In transport mode, only the payload of the IP packet is encrypted. In tunnel mode, on the other hand, the entire IP packet is encrypted and inserted into a new IP packet with a new IP header. Cilium IPsec node-to-node encryption uses tunnel mode.

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ----
|               Security Parameters Index (SPI)                 | ^Int.
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
|                      Sequence Number                          | |ered
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ----
|                    Payload Data* (variable)                   | |   ^
~                                                               ~ |   |
|                                                               | |Conf.
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
|               |     Padding (0-255 bytes)                     | |ered*
+-+-+-+-+-+-+-+-+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |   |
|                               |  Pad Length   | Next Header   | v   v
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ------
|         Integrity Check Value-ICV   (variable)                |
~                                                               ~
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

ESP packet format, from RFC4303

The protocol identifier is 50 (IPPROTO_ESP). ESP adds a new header and a trailer to each packet.

Here is a brief explanation of each field:

  • SPI: A 32-bit security index
  • Sequence Number: An unsigned 32-bit field that contains a counter value that increases by one for each packet sent. The sender MUST increment this field for every transmitted packet. This number must never cycle: before it would wrap past 0xffff_ffff, a new SA, with a new encryption key, has to be set up. Otherwise the Linux kernel drops the packet instead of wrapping to 0. With Extended Sequence Number (ESN) enabled, the counter becomes a 64-bit unsigned value. Cilium enables ESN on its XFRM states (flag esn in the full ip xfrm state output).

Background: XFRM

XFRM is the Linux kernel’s IPsec framework. The name is short for “transform”, because it transforms packet contents based on XFRM policies. The kernel’s IPsec implementation is built on XFRM, which mangles incoming and outgoing packets. Each cilium-agent uses this framework to achieve node-to-node IPsec encryption. XFRM is a policy-based framework: it checks whether a certain flow should be processed or whether it can bypass IPsec processing.

Reading ip xfrm

The output in this section is from my home lab cluster with 3 worker nodes running Cilium 1.20.5 in VXLAN tunnel mode with IPsec. Commands run inside the cilium-agent container, which runs in the host network namespace. Below, Node A is 10.100.0.10 and Node B is 10.100.0.12.

An XFRM policy decides which packets get encrypted and how. Here are three XFRM policies from Node A.

node-a $ ip xfrm policy   (trimmed)
src 10.100.0.10/32 dst 10.100.0.12/32
	dir out priority 0
	mark 0xceaa3e00/0xffffff00
	tmpl src 10.100.0.10 dst 10.100.0.12
		proto esp spi 0x00000003 reqid 1 mode tunnel
src 0.0.0.0/0 dst 0.0.0.0/0
	dir in priority 0
	tmpl src 0.0.0.0 dst 0.0.0.0
		proto esp reqid 0 mode tunnel
		level use
src 0.0.0.0/0 dst 0.0.0.0/0
	dir out action block priority 100
	mark 0xe00/0xf00

What does each field mean?

  • src / dst and mark decide whether a packet matches. Both have to match.
  • dir out means outgoing packets. The other directions are in (packets for the node itself) and fwd (packets the node forwards, e.g. to a pod).
  • priority: when several policies match, the lowest number wins.
  • tmpl says what to do with a match: ESP in tunnel mode between 10.100.0.10 and 10.100.0.12, with SPI 3.

The mark is how Cilium’s BPF code tells XFRM what to do. 0xceaa3e00 is the peer’s node ID (0xceaa, Node A’s local ID for Node B), the key ID (3, the same number as the SPI) and an encrypt flag (0xe00). Outgoing packets without such a mark, like most host traffic, match none of the OUT policies and leave unencrypted.

The policy says what to do with a packet, but not which key to encrypt it with. That key lives in the state: a per-pair key, which Cilium derives separately for each direction between two nodes. For a packet that matches the policy, the kernel picks the state with the same addresses and SPI whose mark also matches the packet, and encrypts with that state’s per-pair key:

node-a $ ip xfrm state    (keys redacted, trimmed)
src 10.100.0.10 dst 10.100.0.12
	proto esp spi 0x00000003 reqid 1 mode tunnel
	mark 0xceaa3e00/0xffffff00 output-mark 0xe00/0xffffff00
	aead rfc4106(gcm(aes)) <redacted> 128
src 10.100.0.12 dst 10.100.0.10
	proto esp spi 0x00000003 reqid 1 mode tunnel
	mark 0xceaa0d00/0xffff0f00 output-mark 0xd00/0xffffff00
	aead rfc4106(gcm(aes)) <redacted> 128

The first is the OUT state the policy above uses. The second is the IN state for packets from Node B. It has a decrypt flag (0xd00) instead, and its mask ignores the key ID. For each peer, the agent creates OUT and IN states, each with its own per-pair key derived from the shared key in the cilium-ipsec-keys Secret, both IPs and both boot IDs (deriveNodeIPsecKey).

In tunnel mode, which is what Cilium node-to-node encryption uses, ESP wraps the whole packet. The kernel puts a new IP header in front, using the template’s src and dst, followed by an ESP header with the SPI and a sequence number. The original packet and an ESP trailer are encrypted with the state’s per-pair key, and an ICV at the end lets the receiver detect any change. The receiver uses the SPI from the ESP header, together with the destination address, to find its IN state.

On Node A the packet that reaches XFRM is already VXLAN, so the new outer header carries the same node IPs as the VXLAN packet inside it.

What ESP tunnel mode does to the packetTop: the packet that reaches XFRM on Node A, a VXLAN packet: IP header 10.100.0.10 to 10.100.0.12 with UDP, UDP port 8472, VXLAN header, and the inner Ethernet frame carrying the pod's packet. The template (esp, tunnel mode, 10.100.0.10 to 10.100.0.12, spi 3) and the per-pair key from the matching state turn it into the bottom packet: a new outer IP header 10.100.0.10 to 10.100.0.12 with protocol 50 (ESP), an ESP header with SPI 3 and a sequence number, an IV, the whole VXLAN packet encrypted, an encrypted trailer with padding and next header 4, and a 16-byte ICV. The original packet and trailer are encrypted with the state's per-pair key; everything from the ESP header to the trailer is protected by the ICV.What reaches XFRM on Node A (a VXLAN packet)IP header10.100.0.10 → 10.100.0.12, UDPUDPport 8472VXLANinner Ethernet frame(the pod's packet)tmpl: esp, tunnel, 10.100.0.10 → 10.100.0.12, spi 3+ the per-pair key from the matching stateOn the wire (ESP, tunnel mode)new IP header10.100.0.10 → .12proto 50 (ESP)ESP headerSPI 3seq no.IVthe whole VXLAN packet(encrypted)trailerpadding,next hdr 4ICV16 bytesencrypted with the state's per-pair keyprotected by the ICV
Not to scale. Next header 4 means the decrypted payload is an IPv4 packet. Click to enlarge.

Background: How does Cilium derive XFRM policies and states

Needless to say, all cilium-agents need to learn about a new key ID from other nodes. The sender must read the peer’s key ID from its CiliumNode custom resource. Below is an example from the lab cluster (node names shortened) showing how Cilium advertises each node’s SPI.

$ kubectl get ciliumnodes -o custom-columns=NAME:.metadata.name,KEYID:.spec.encryption.key,BOOTID:.spec.bootid
NAME     KEYID   BOOTID
node-a   3       bcaab198-0832-4963-ae12-192647952e92
node-b   3       a5b68764-942f-4217-b106-fae8510fcc9f
node-c   3       27e23007-3c58-4f64-b408-c5908414c359

Two of its fields matter for IPsec:

  • spec.encryption.key is the key ID (SPI) the peer is using. The agent stores it in a BPF map, the node map, and the datapath reads it for every packet to that peer.
  • spec.bootid is an input to the per-pair keys. When a peer’s boot ID changes, the agent replaces that peer’s states.

So how do two nodes end up with matching states? Neither node ever sends a key to the other. Every agent reads the same shared key from the cilium-ipsec-keys Secret and derives the per-pair key for each direction of each node pair on its own (getNodeIPsecKey, computeNodeIPsecKey). The per-pair key is a SHA-256 hash of the shared key, the sender’s IP, the receiver’s IP, the sender’s boot ID and the receiver’s boot ID, cut to the shared key’s length.

For Node A (IP a, boot ID x) and Node B (IP b, boot ID y):

Node ANode B
OUT statekey(a, b, x, y)key(b, a, y, x)
IN statekey(b, a, y, x)key(a, b, x, y)

Node A knows its own IP and boot ID and reads Node B’s from Node B’s CiliumNode, and Node B does the same the other way round. So Node A’s OUT state and Node B’s IN state get the same per-pair key, and so do Node B’s OUT state and Node A’s IN state, while each direction has a per-pair key of its own.

Problem 1: the N² CiliumNode storm

Now we know that whenever a Cilium IPsec key rotation happens, every cilium-agent needs to:

  1. update its own CiliumNode’s spec.encryption.key
  2. watch the other CiliumNodes’ updates, derive the new per-pair keys, and create new XFRM states and policies for the new SPI

Every agent updates its CiliumNode, and every agent watches all of those updates, which causes N² watch events. This is fine on a relatively small cluster. However, on a cluster with more than a thousand nodes, this can easily flood the Kubernetes API server and cause an outage: a 1,000-node cluster creates about 1M events.

The simplest fix is to disable the key watcher and rotate the shared key with a rolling restart of the cilium-agent DaemonSet. (The key watcher, which watches the cilium-ipsec-keys Secret, is enabled by default. The problem with it here is that we have no control over how many watch updates a key rotation causes at once.) I just needed to make sure that ipsec-key-rotation-duration, which decides how long the old and new SPIs can coexist, is longer than the cilium-agent rolling restart.

This definitely eased the load on the Kubernetes API server. However, it didn’t fix the more critical issue.

Problem 2: drops during the rollout

Disabling the key watcher and doing a rolling restart of the cilium-agent DaemonSet definitely helped relieve the load on the Kubernetes API server during key rotation. However, I was still seeing tons of packet drops in XFRM during key rotation.

During key rotation, Cilium makes sure that the old SPI and the new SPI can coexist. The sender picks which SPI to use for each packet in get_min_encrypt_key():

/* bpf/lib/ipsec.h, cilium/cilium @ ad40b0b (lines 19 and 35-61, #ifdef ENABLE_IPSEC removed)
 * Copyright Authors of Cilium. GPL-2.0-only OR BSD-2-Clause. */
#define MAX_KEY_INDEX 15

static __always_inline __u8 get_min_encrypt_key(__u8 peer_key __maybe_unused)
{
	__u8 local_key = 0;
	__u32 encrypt_key = 0;
	const struct encrypt_config *cfg;

	cfg = map_lookup_elem(&cilium_encrypt_state, &encrypt_key);
	/* Having no key info for a context is the same as no encryption */
	if (cfg)
		local_key = cfg->encrypt_key;

	/* If both ends can encrypt/decrypt use smaller of the two this
	 * way both ends will have keys installed assuming key IDs are
	 * always increasing. However, we have to handle roll-over case
	 * and to do this safely we assume keys are no more than one ahead.
	 * We expect user/control-place to accomplish this. Notice zero
	 * will always be returned if either local or peer have the zero
	 * key indicating no encryption.
	 */
	if (peer_key == MAX_KEY_INDEX)
		return local_key == 1 ? peer_key : local_key;
	if (local_key == MAX_KEY_INDEX)
		return peer_key == 1 ? local_key : peer_key;
	return local_key < peer_key ? local_key : peer_key;
}
  • local_key is this node’s current key ID. There is only one, stored as the only entry of the cilium_encrypt_state BPF map.
  • peer_key is the key ID the peer advertises in its CiliumNode (spec.encryption.key). The agent copies it into the node map (node.go, node_ids.go).
  • The function returns the smaller of the two. Key IDs go from 1 to 15 and wrap back to 1, so between 15 and 1 it picks 15.
  • The comment states the assumption: the two nodes are never more than one key ID apart.

For a rotation from key ID 3 to key ID 4:

  • A=3, B=3: both directions use 3.
  • A=4, B=3: both directions still use 3. Both nodes have SPI 3 states, because those live in the kernel and survive the agent restart.
  • A=4, B=4: both directions use 4, which needs SPI 4 states on both sides.
Key rotation from key ID 3 to 4 with one node still on key ID 3: no dropsNode A has restarted and advertises key ID 4; its old SPI 3 states are still in the kernel. Node B has not restarted yet and advertises key ID 3. A sends to B with min(4, 3) = 3, so SPI 3. B sends to A with min(3, 4) = 3, so SPI 3. Both nodes have SPI 3 states, so both directions work.✓ Fine: one node is still on the old key ID (3 → 4)Node A, restartedadvertises key ID 4old SPI 3 states are stillin the kernelNode B, not restarted yetadvertises key ID 3SPI 3 statesA → B: min(4, 3) = 3, SPI 3 ✓B → A: min(3, 4) = 3, SPI 3 ✓Both directions use SPI 3, and both nodes still have SPI 3 states.The old states stay until ipsec-key-rotation-duration reclaims them.
During the rollout, a node on key ID 4 and a node still on key ID 3 agree on SPI 3. Click to enlarge.

Above is the happy path: Node B is still on key ID 3, so both directions use SPI 3, and both nodes still have XFRM states for it. Both nodes A and B are able to encrypt and decrypt the traffic.

Sequence of the key rotation race, before the fixThree timelines: Node A, kube-apiserver, Node B. At the start A is on key ID 3 and B, restarted earlier, is on key ID 4 with its SPI 4 states ready. B sends ESP with SPI 3 because min(4, 3) = 3, and A decrypts it. Step 1: A's agent restarts with key ID 4 and sets cilium_encrypt_state to 4. Step 2: A updates its CiliumNode to key ID 4 through the kube-apiserver. Step 3: the apiserver sends a watch event to every node, including B. Step 4: B writes A to SPI 4 in its node map and now picks min(4, 4) = 4. Step 5: B sends ESP with SPI 4, and A drops it in XFRM because it has no IN state from B for SPI 4 yet (XfrmInNoStates). This repeats for every packet in the drop window, while A's agent is still inserting XFRM states one peer at a time and hasn't reached B. Step 6: A's agent reaches B and creates the IN state from B for SPI 4. Step 7: B's next ESP packet with SPI 4 is decrypted. The window lasts from step 2 to step 6 and grows with the number of nodes.Node Akube-apiserverNode Bon key ID 3on key ID 4 (restarted earlier)ESP, SPI 3 ✓ (min(4, 3) = 3)① agent restarts with key ID 4cilium_encrypt_state = 4② CiliumNode A: key ID 4A's agent is still insertingXFRM states, one peer at a time,and hasn't reached B yet③ watch event (to every node)④ node map: A → SPI 4to A: min(4, 4) = 4⑤ ESP, SPI 4ESP, SPI 4dropped in A's XFRM:no IN state from B for SPI 4(XfrmInNoStates)drop window⑥ agent gets to Bcreates IN state from B, SPI 4⑦ ESP, SPI 4 ✓ decryptedKubernetes APIpackets on the wireThe window runs from ② to ⑥. A has N−1 peers to get through, so it grows with cluster size.
The failing case, before the fix. Time runs downward. Cilium counts these drops in cilium_ipsec_xfrm_error (type inbound, error no_state). Click to enlarge.

A restarted cilium-agent advertised its new SPI in its CiliumNode immediately. When Node A from the diagram above prematurely advertises its SPI before it inserts the new IN states that handle traffic from Node B, packets are dropped until the agent actually creates the IN state from B. This XFRM state creation window gets larger when there are more nodes in the cluster.

The fix

To fix this race, the agent has to wait until the XFRM states and policies for the new SPI are programmed before it advertises that SPI in its CiliumNode. The main insight is that cilium_encrypt_state is a pinned BPF map, so it survives a cilium-agent restart. By comparing the SPI in that map with the SPI in the cilium-ipsec-keys Secret, the agent can tell whether this restart is part of a key rotation.

If the SPI in the Secret is the next one after the SPI in the BPF map, a rotation is in progress:

// ongoingRotation returns true if there is an ongoing key rotation, which is the
// case when both the current [*agent.spi] and pending [*agent.pendingSPI] are valid,
// and the pending SPI is the next one.
func (a *agent) ongoingRotation() bool {
	if a.spi == 0 || a.pendingSPI == 0 {
		return false
	}
	return a.pendingSPI == a.spi%linux_defaults.IPsecMaxKeyVersion+1
}

IPsecMaxKeyVersion is 15, so this also covers the wrap from 15 back to 1.

During a rotation, Start() keeps advertising the old SPI from the BPF map and holds the new one in pendingSPI. Before the fix, it loaded the shared key and switched to the new SPI right away:

 func (a *agent) Start(cell.HookContext) error {
 	...
-	var err error
-	a.authKeySize, a.spi, err = a.loadIPSecKeysFile(a.config.IPsecKeyFile)
+	v, err := a.encryptMap.Lookup(encrypt.EncryptKey{Key: 0})
 	if err != nil {
 		return err
 	}
-	if err := a.setIPSecSPI(a.spi); err != nil {
+	a.spi = v.KeyID
+
+	a.authKeySize, a.pendingSPI, err = a.loadIPSecKeysFile(a.config.IPsecKeyFile)
+	if err != nil {
 		return err
 	}
 
+	if !a.ongoingRotation() {
+		if err := a.setIPSecSPI(a.pendingSPI); err != nil {
+			return err
+		}
+	}
+
 	a.localNode.Update(func(n *node.LocalNode) {
 		n.EncryptionKey = a.spi
 	})

setIPSecSPI() writes the BPF map and also sets a.spi. So when a restart isn’t a rotation (first boot, the same key ID, or any other jump), the agent publishes the new SPI right away, as before. During a rotation that call is skipped, and both the BPF map and the CiliumNode keep the old SPI.

The new SPI is published later by a one-shot job in StartBackgroundJobs(). It waits until the datapath is initialized (Orchestrator.DatapathInitialized()), then calls publishPendingSPI():

if a.ongoingRotation() {
	a.jobs.Add(job.OneShot("deferred-spi-update", func(ctx context.Context, _ cell.Health) error {
		select {
		case <-dpInitialized:
		case <-ctx.Done():
			return ctx.Err()
		}

		a.log.Info("Datapath initialized, publishing updated SPI",
			logfields.OldSPI, a.spi,
			logfields.SPI, a.pendingSPI,
		)
		if err := a.publishPendingSPI(handler); err != nil {
			return err
		}
		if err := a.startKeyfileWatcher(handler); err != nil {
			return fmt.Errorf("failed to start IPsec keyfile watcher: %w", err)
		}
		return nil
	}))
}

publishPendingSPI() does three things, in the order that closes the race: program XFRM for every known peer, then advertise the new SPI, then start using it.

// publishPendingSPI publishes the pending SPI to the datapath and CiliumNode.
//
//  1. AllNodeValidateImplementation will eventually call nodeUpdate(), which is
//     responsible for updating the IPSec policies and states for all the different
//     EPs with ipsec.UpsertIPsecEndpoint(). We do this before advertising the new
//     SPI to ensure our ingress XFRM states are ready before peers start sending
//     traffic encrypted with the new key.
//
//  2. Update the IPSec key identity in the local node. This will set
//     addrs.ipsecKeyIdentity in the node package, and eventually trigger an
//     update to publish the updated information to k8s/kvstore.
//
//  3. Push SPI update into BPF datapath now that XFRM state is configured.
func (a *agent) publishPendingSPI(handler node.Handler) error {
	handler.AllNodeValidateImplementation()

	a.localNode.Update(func(n *node.LocalNode) {
		n.EncryptionKey = a.pendingSPI
	})

	if err := a.setIPSecSPI(a.pendingSPI); err != nil {
		return fmt.Errorf("failed to set IPsec SPI: %w", err)
	}

	a.pendingSPI = 0
	return nil
}

In the sequence diagram above, this moves step ② after step ⑥: Node A advertises key ID 4 only once it can decrypt SPI 4 from every peer it knows, so Node B switches without dropping anything. The key watcher path now calls the same publishPendingSPI(), so both ways of rotating the shared key follow the same order. The full change is in commit ad40b0b.

Wrapping up

During a key rotation, a restarted cilium-agent used to advertise its new key ID too early, before it had created the XFRM IN states for it. Peers that had already switched to the new key ID then sent packets it couldn’t decrypt yet. The fix keeps advertising the old key ID during a rotation and publishes the new one only after XFRM is programmed for every known peer.

After rolling out the fix, our weekly key rotations no longer cause XFRM errors: the inbound no_state drops are gone, and applications no longer see network issues while a new shared key rolls out.

References