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 esnin the fullip xfrm stateoutput).
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/dstandmarkdecide whether a packet matches. Both have to match.dir outmeans outgoing packets. The other directions arein(packets for the node itself) andfwd(packets the node forwards, e.g. to a pod).priority: when several policies match, the lowest number wins.tmplsays 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.
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.keyis 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.bootidis 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 A | Node B | |
|---|---|---|
| OUT state | key(a, b, x, y) | key(b, a, y, x) |
| IN state | key(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:
- update its own CiliumNode’s
spec.encryption.key - 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_keyis this node’s current key ID. There is only one, stored as the only entry of thecilium_encrypt_stateBPF map.peer_keyis 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.
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.
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
ip-xfrm(8)- Linux kernel docs: XFRM proc counters
- Nftables - Netfilter and VPN/IPsec packet flow (Thermalcircle)
- RFC 4301: Security Architecture for the Internet Protocol
- RFC 4303: IP Encapsulating Security Payload (ESP)
- Cilium docs: IPsec transparent encryption (key rotation, troubleshooting)
bpf/lib/ipsec.h(get_min_encrypt_key)pkg/datapath/linux/ipsec/ipsec_linux.go- #44701, #44335, #45630