Container isolation from the syscall up
What namespaces, capabilities, seccomp and user namespaces check inside the kernel, and which boundary three real container escapes crossed.
A container is not an object the kernel knows about. There is no struct container, no container id in the scheduler, no syscall that creates one. What a runtime such as runc or crun builds is a process whose task_struct points at a different set of namespaces, carries a reduced credential, and drags a chain of BPF programs along on every system call. Each of those is a separate kernel mechanism with its own data structure and its own check, written by different people in different decades. Isolation is the sum of those checks, and an escape is always a path that none of them looks at.
That framing matters when you assess a cluster. "Is this workload isolated?" has no useful answer. "Which check stands between this process and that host resource, and what does the check actually compare?" does. This article walks the four mechanisms down to the fields they read, pinned to the Linux v7.2 tag, then takes three well documented escapes and names the boundary each one crossed: CVE-2019-5736 and CVE-2024-21626 in runc, and CVE-2022-0185 in the kernel's filesystem context code.
The lab
Every command and output in this article was run on the machine described below, as a normal user (uid 1000) with SELinux enforcing. Kernel source references point at the v7.2 tag so that the code you read is the code that ran. Kubernetes behaviour is taken from the v1.37 documentation and the containerd v2.4.2 source; I did not run a cluster for this article, and the sections that rely on Kubernetes say so.
| Component | Version | Role in the lab |
|---|---|---|
| Distribution | Fedora Linux 43 Workstation | Host |
| Kernel | 7.2.13-100.fc43.x86_64 | All namespace, capability and seccomp checks |
| util-linux | 2.41.6 | unshare, nsenter, lsns |
| libcap | 2.76 | capsh --decode |
| Podman | 5.8.9, rootless, cgroup v2 | Container runs |
| crun | 1.28 | OCI runtime under Podman |
| containers-common | 0.67.2 | Podman default seccomp profile |
| container-selinux | 2.251.0 | SELinux policy for container_t |
| iproute2 | 6.14.0 | Network namespace ownership test |
| GCC | 15.3.1 | Raw seccomp filter program |
| Image | registry.fedoraproject.org/fedora:43 | Container userland |
What the kernel keeps per task
Start with what the kernel stores. A task reaches its namespaces through task->nsproxy, a reference-counted bundle of pointers defined in include/linux/nsproxy.h1. Two namespaces are missing from it on purpose: the user namespace hangs off the credential, and the PID namespace a task lives in is fixed at creation, so nsproxy only stores the one its children will get.
struct nsproxy {
refcount_t count;
struct uts_namespace *uts_ns;
struct ipc_namespace *ipc_ns;
struct mnt_namespace *mnt_ns;
struct pid_namespace *pid_ns_for_children;
struct net *net_ns;
struct time_namespace *time_ns;
struct time_namespace *time_ns_for_children;
struct cgroup_namespace *cgroup_ns;
};The second pointer is task->cred. In include/linux/cred.h2 a struct cred holds the five capability sets as kernel_cap_t values (a single u64 at this tag) next to struct user_namespace *user_ns, commented as the namespace "the caps and keyrings are relative to". That comment is the whole design of user namespaces in one line: a capability bit means nothing until you know which user namespace it was granted in.
kernel_cap_t cap_inheritable; /* caps our children can inherit */
kernel_cap_t cap_permitted; /* caps we're permitted */
kernel_cap_t cap_effective; /* caps we can actually use */
kernel_cap_t cap_bset; /* capability bounding set */
kernel_cap_t cap_ambient; /* Ambient capability set */
...
struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */The third is task->seccomp.filter, the head of a singly linked list of struct seccomp_filter nodes in kernel/seccomp.c3. The fourth, which this article treats only where it changes an outcome, is the LSM label, and it is not a separate task pointer. SELinux keeps the task's SID in the credential's security blob: selinux_cred() in security/selinux/include/objsec.h returns cred->security plus SELinux's offset as a struct cred_security_struct, whose sid field is the current label4. The label therefore travels with task->cred, next to the capability sets, and changes when the credential is replaced at execve.
Those four mechanisms decide what a task may do. They are not all the state a runtime sets up. struct task_struct in include/linux/sched.h5 also holds fs, a struct fs_struct with the root and working directory that pivot_root and chdir change; files, the struct files_struct file table whose descriptors the runtime inherits, closes or marks close-on-exec; and cgroups, the struct css_set that places the task in its cgroups. Behind task->mm sits one more reference, the exe_file that /proc/<pid>/exe exposes. No namespace lookup and no credential check inspects a descriptor already in the file table, a working directory already in fs_struct, or the executable already in exe_file. Each keeps pointing at the object it was set to, whatever namespace the task later moves into. Both runc escapes below crossed through that state, not through one of the four mechanisms, and the kernel escape needed none of it.
Namespaces isolate names, not objects
namespaces(7) lists eight types and the CLONE_NEW* flag that creates each6. The clean way to read the list is: each namespace replaces one global lookup table. The mount namespace replaces the mount tree that path resolution walks. The PID namespace replaces the table that turns a number into a task. The network namespace replaces the set of devices, routes and sockets. None of them changes what happens once you already hold a reference to an object.
| Namespace | Flag | Global table it replaces | /proc link since |
|---|---|---|---|
| Mount | CLONE_NEWNS | Mount tree used by path lookup | 3.8 |
| PID | CLONE_NEWPID | Number to task mapping | 3.8 |
| Network | CLONE_NEWNET | Devices, routes, ports, sockets | 3.0 |
| IPC | CLONE_NEWIPC | System V IPC, POSIX message queues | 3.0 |
| UTS | CLONE_NEWUTS | Hostname and NIS domain name | 3.0 |
| User | CLONE_NEWUSER | UID and GID mapping, capability scope | 3.8 |
| Cgroup | CLONE_NEWCGROUP | Visible cgroup root | 4.6 |
| Time | CLONE_NEWTIME | Boot and monotonic clock offsets | 5.6 |
Each task exposes its namespaces under /proc/<pid>/ns/ as links whose content is type:[inode]; two processes share a namespace exactly when stat(2) returns the same device and inode for the link6. On the lab host, the shell sees the initial namespaces:
$ ls -l /proc/self/ns/ | awk '{print $9,$10,$11}'
cgroup -> cgroup:[4026531835]
ipc -> ipc:[4026531839]
mnt -> mnt:[4026531832]
net -> net:[4026531833]
pid -> pid:[4026531836]
pid_for_children -> pid:[4026531836]
time -> time:[4026531834]
time_for_children -> time:[4026531834]
user -> user:[4026531837]
uts -> uts:[4026531838]The property that matters for security is visible in the kernel's implementation of those /proc links. They are not symlinks that store a path. For a file descriptor link, proc_fd_link() in fs/proc/fd.c7 looks up the struct file behind the descriptor and copies its f_path, which is a pair of struct vfsmount and struct dentry pointers. proc_pid_get_link() then hands that path to nd_jump_link() in fs/namei.c8, which does this:
int nd_jump_link(const struct path *path)
{
int error = -ELOOP;
struct nameidata *nd = current->nameidata;
if (unlikely(nd->flags & LOOKUP_NO_MAGICLINKS))
goto err;
error = -EXDEV;
if (unlikely(nd->flags & LOOKUP_NO_XDEV)) {
if (nd->path.mnt != path->mnt)
goto err;
}
/* Not currently safe for scoped-lookups. */
if (unlikely(nd->flags & LOOKUP_IS_SCOPED))
goto err;
path_put(&nd->path);
nd->path = *path;
nd->inode = nd->path.dentry->d_inode;
nd->state |= ND_JUMPED;
return 0;
...Path resolution simply replaces its current position with the object's own mount and dentry. The calling task's mount namespace and root directory are never consulted. openat2(2) calls these "magic links" and says it plainly: "a magic link inside /proc may refer to an object outside the container"9. That sentence is the root cause of two of the three escapes below. A mount namespace hides names; a file descriptor or an exe link is not a name.
You can see this without any vulnerability. Podman's --preserve-fds passes extra descriptors into the container on purpose. Open a host directory as descriptor 3, pass it in, and walk through it. I disabled SELinux labelling for the first run so that only namespaces are in play:
$ mkdir -p /tmp/fdlab && echo "written on the host" > /tmp/fdlab/host-file
$ exec 3</tmp/fdlab
$ podman run --rm --preserve-fds=1 --security-opt label=disable \
registry.fedoraproject.org/fedora:43 sh -c \
'readlink /proc/self/fd/3; cd /proc/self/fd/3 && pwd -P; cat host-file'
/tmp/fdlab
pwd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
written on the hostThe container's shell has a working directory on the host filesystem, and the error line shows where that becomes visible. It is not the system call that fails. SYSCALL_DEFINE2(getcwd) in fs/d_path.c returns ENOENT only when the working directory has been unlinked (d_unlinked()). For a directory that prepend_path() cannot reach from the task's root it succeeds, and puts the string (unreachable) in front of the path it returns10. The failure comes one layer up. getcwd(3) records that glibc 2.27 and later rejects such a non-absolute result with ENOENT11, and that is the error bash reports for pwd -P. Go's wrappers follow the same rule: Getwd() in golang.org/x/sys/unix returns ENOENT whenever the first byte of the syscall's result is not /12. runc 1.1.12 builds its breakout check on that wrapper error, as we will see, not on an error from the kernel. Run the same command with SELinux labelling on and the result changes:
$ podman run --rm --preserve-fds=1 registry.fedoraproject.org/fedora:43 \
sh -c 'readlink /proc/self/fd/3; cd /proc/self/fd/3 && cat host-file'
/null
sh: line 1: cd: /proc/self/fd/3: Not a directoryThat /null is not Podman's doing. When execve moves a task into a new SELinux domain, selinux_bprm_committing_creds() in security/selinux/hooks.c13 calls flush_unauthorized_files(), which checks every inherited descriptor against the new label and replaces each one the new domain may not use with a descriptor on SELinux's own null device. The container process (container_t) has no permission on a file labelled for the user's temporary directory, so the descriptor is swapped before the first instruction of the container's shell runs. Be precise about the scope of this hook. Besides the controlling tty, flush_unauthorized_files() walks only the file table, through iterate_fd(). It never looks at the task's fs_struct, so a working directory that already points into the host survives the domain transition, and a path resolved before execve was resolved before the hook ran. The lab shows the descriptor case only. Where SELinux stops the runc escapes below, it does so through the ordinary type enforcement check on each later open, write or exec of a host-labelled file, not through this flush.
User namespaces decide where a capability counts
Every other namespace has an owner: the user namespace that was current when it was created. user_namespaces(7) states the rule that makes the whole design work: privileged operations on a non-user namespace "require that the process has the necessary capabilities in the user namespace that owns the nonuser namespace"14. The check is cap_capable() in security/commoncap.c15, which at v7.2 delegates to a helper whose loop is short enough to quote whole:
for (;;) {
/* Do we have the necessary capabilities? */
if (likely(ns == cred_ns))
return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
/*
* If we're already at a lower level than we're looking for,
* we're done searching.
*/
if (ns->level <= cred_ns->level)
return -EPERM;
/*
* The owner of the user namespace in the parent of the
* user namespace has all caps.
*/
if ((ns->parent == cred_ns) && uid_eq(ns->owner, cred->euid))
return 0;
/*
* If you have a capability in a parent user ns, then you have
* it over all children user namespaces as well.
*/
ns = ns->parent;
}target_ns is the user namespace that owns the resource: the network namespace for CAP_NET_ADMIN, the mount namespace for a mount, the initial namespace for loading a module. The walk climbs from the resource's owner towards the root. A capability bit in cap_effective only counts if the walk reaches the caller's own user namespace. A process that is root in a child namespace therefore has every capability over things its namespace owns and none over anything owned by an ancestor. Root inside the container is a real root, of a very small kingdom.
The lab makes the walk concrete. unshare --map-root-user creates a user namespace and maps uid 0 inside to uid 1000 outside. The new process has a full effective set, 41 bits for capabilities 0 to 40 (CAP_LAST_CAP is CAP_CHECKPOINT_RESTORE, 40, in include/uapi/linux/capability.h16). Yet it cannot add a link to the host network namespace, because that namespace is owned by the initial user namespace. Give it its own network namespace and the same command succeeds:
$ unshare --user --map-root-user --mount --pid --fork --mount-proc bash -c \
'id -u; cat /proc/self/uid_map; grep -E "^Cap(Prm|Eff|Bnd)" /proc/self/status'
0
0 1000 1
CapPrm: 000001ffffffffff
CapEff: 000001ffffffffff
CapBnd: 000001ffffffffff
$ unshare --user --map-root-user ip link add lab0 type dummy
RTNETLINK answers: Operation not permitted
$ unshare --user --map-root-user --net sh -c \
'ip link add lab0 type dummy && ip -br link show lab0'
lab0 DOWN a2:b1:f1:c4:38:96 <BROADCAST,NOARP>
$ unshare --user --map-root-user bash -c 'hostname lab-a'
hostname: you must be root to change the host name
$ unshare --user --map-root-user --uts bash -c 'hostname lab-a && hostname'
lab-aHow did an unprivileged user get CAP_SYS_ADMIN to create those other namespaces? Look at the order inside ksys_unshare() in kernel/fork.c17. It calls unshare_userns() first, which builds a new credential in a new user namespace, and only then unshare_nsproxy_namespaces(). That function, in kernel/nsproxy.c18, checks ns_capable(user_ns, CAP_SYS_ADMIN) where user_ns is the new credential's namespace. The caller has every capability there by construction, so the check passes. This is deliberate and correct, and it is also the reason that a single unshare(CLONE_NEWUSER | CLONE_NEWNS) from an unprivileged process puts large parts of the kernel's privileged code within reach.
The ID map is a small sorted array
Each user namespace carries a uid_map, a gid_map and a projid_map. In include/linux/user_namespace.h19 a mapping is an array of struct uid_gid_extent { u32 first; u32 lower_first; u32 count; }. struct uid_gid_map is sized, per its comment, to fit one 64-byte cache line: up to UID_GID_MAP_MAX_BASE_EXTENTS (5) extents live inline in the union, and beyond that the kernel allocates separate forward and reverse arrays, sorted, up to UID_GID_MAP_MAX_EXTENTS (340). map_id_range_down() in kernel/user_namespace.c20 scans linearly when there are five or fewer extents and calls bsearch() otherwise. The 340 limit is the same one user_namespaces(7) documents as the line limit of the map file since Linux 4.1614.
The file format is the extent: inside-start, outside-start, length. A rootless Podman container on the lab host has two extents, one that maps container root onto my own uid and one that maps container uids 1 to 65536 onto the subordinate range from /etc/subuid:
$ podman run --rm registry.fedoraproject.org/fedora:43 cat /proc/self/uid_map
0 1000 1
1 524288 65536The map is written once. A second write fails with EPERM, and an unprivileged writer may only map its own effective ID14. Every inode permission check compares a kuid_t, the global ID after translation, so a file owned by host uid 0 stays owned by "overflow uid" from inside the namespace, and writing to it fails the ordinary DAC check. That one fact, more than any capability, is what user namespaces buy you against runtime escapes.
Capabilities: the bounding set and the inheritable gap
capabilities(7) gives the transformation that runs on every execve21, and the code that implements it is cap_bprm_creds_from_file() in security/commoncap.c15:
P'(ambient) = (file is privileged) ? 0 : P(ambient)
P'(permitted) = (P(inheritable) & F(inheritable)) |
(F(permitted) & P(bounding)) | P'(ambient)
P'(effective) = F(effective) ? P'(permitted) : P'(ambient)
P'(inheritable) = P(inheritable) [i.e., unchanged]
P'(bounding) = P(bounding) [i.e., unchanged]Read it from the container's point of view. The bounding set is never widened by execve, and it masks the F(permitted) term: a file's permitted capabilities can only add bits that are already in the bounding set. It does not mask the inheritable term. capabilities(7) is explicit: "If a thread maintains a capability in its inheritable set that is not in its bounding set, then it can still gain that capability in its permitted set by executing a file that has the capability in its inheritable set." The same page notes that removing a capability from the bounding set "does not remove it from the thread's inheritable set"21. The ceiling for every program the container will ever run, setuid binaries included, is therefore the bounding set plus the inheritable set, and through P'(ambient) the ambient set, which can never exceed the inheritable set. A runtime fixes that ceiling to the bounding set only when it also starts the container with an empty inheritable and ambient set.
The inheritable set is not a theoretical input. Moby's advisory GHSA-2mm7-x5h6-5pvq, CVE-2022-24769, fixed in Docker Engine 20.10.14, describes containers that "were incorrectly started with non-empty inheritable Linux process capabilities", which let programs with inheritable file capabilities raise them into the permitted set during execve, so that otherwise unprivileged users inside the container gained them22. For Docker's case the advisory states that "the container's bounding set provides an upper bound on the capabilities that can be assumed". The capabilities(7) sentence above is why that bound depends on what the runtime placed in the inheritable set, and is not something the kernel enforces on its own. A well-behaved runtime keeps CapInh and CapAmb empty. The permitted and effective sets are what a process happens to hold right now. When you audit a pod, read CapBnd together with CapInh and CapAmb, not CapEff alone.
Then there is no_new_privs. When the bit is set, check_unsafe_exec() in fs/exec.c23 marks the exec with LSM_UNSAFE_NO_NEW_PRIVS, and cap_bprm_creds_from_file() responds by intersecting the new permitted set with the old one and refusing the setuid change of effective IDs. Kubernetes exposes this bit as allowPrivilegeEscalation: false. It costs nothing at run time and removes the whole class of "exec something setuid inside the container".
Default sets are where runtimes quietly differ. containerd's default OCI spec grants 14 capabilities (defaultUnixCaps() in pkg/oci/spec.go at v2.4.224), including CAP_NET_RAW, CAP_MKNOD and CAP_AUDIT_WRITE. Podman on the lab host grants 11, and the live process confirms it:
$ podman run --rm registry.fedoraproject.org/fedora:43 \
grep -E "^Cap(Prm|Eff|Bnd)|NoNewPrivs|Seccomp" /proc/self/status
CapPrm: 00000000800405fb
CapEff: 00000000800405fb
CapBnd: 00000000800405fb
NoNewPrivs: 0
Seccomp: 2
Seccomp_filters: 1
$ capsh --decode=00000000800405fb
0x00000000800405fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_sys_chroot,cap_setfcap| Capability | containerd v2.4.2 default | Podman 5.8.9 default | Baseline may add | Restricted may add |
|---|---|---|---|---|
CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_FOWNER, CAP_FSETID | yes | yes | yes | no |
CAP_SETUID, CAP_SETGID, CAP_SETPCAP, CAP_SETFCAP | yes | yes | yes | no |
CAP_KILL, CAP_SYS_CHROOT | yes | yes | yes | no |
CAP_NET_BIND_SERVICE | yes | yes | yes | yes |
CAP_MKNOD, CAP_AUDIT_WRITE | yes | no | yes | no |
CAP_NET_RAW | yes | no | no | no |
The Baseline standard restricts what a pod may add through capabilities.add; it does not remove anything the runtime grants by default25. So a Baseline pod on containerd still holds CAP_NET_RAW, which capabilities(7) describes as the right to use raw and packet sockets21, although Baseline would reject a pod that asked for it explicitly. Only Restricted closes this, by requiring drop: ["ALL"] and allowing NET_BIND_SERVICE back alone. My recommendation is not subtle: drop all, add back by name, and treat any request for CAP_SYS_ADMIN as a request for root. capabilities(7) calls that capability overloaded and "the new root" for good reason.
Seccomp: a filter over six registers
Namespaces and capabilities decide whether an operation is permitted. Seccomp decides whether the kernel code that would make that decision is entered at all. The kernel's documentation is careful about the difference: "System call filtering isn't a sandbox. It provides a clearly defined mechanism for minimizing the exposed kernel surface"26.
A filter is a classic BPF program that receives a pointer to struct seccomp_data and returns one of the action values defined above it in include/uapi/linux/seccomp.h27:
...
#define SECCOMP_RET_KILL_PROCESS 0x80000000U /* kill the process */
#define SECCOMP_RET_KILL_THREAD 0x00000000U /* kill the thread */
#define SECCOMP_RET_KILL SECCOMP_RET_KILL_THREAD
#define SECCOMP_RET_TRAP 0x00030000U /* disallow and force a SIGSYS */
#define SECCOMP_RET_ERRNO 0x00050000U /* returns an errno */
#define SECCOMP_RET_USER_NOTIF 0x7fc00000U /* notifies userspace */
#define SECCOMP_RET_TRACE 0x7ff00000U /* pass to a tracer or disallow */
#define SECCOMP_RET_LOG 0x7ffc0000U /* allow after logging */
#define SECCOMP_RET_ALLOW 0x7fff0000U /* allow */
...
struct seccomp_data {
int nr;
__u32 arch;
__u64 instruction_pointer;
__u64 args[6];
};
...Those are the only inputs: the syscall number, the audit architecture, the instruction pointer and six raw register values. The filter cannot follow a pointer, which the kernel documentation presents as a feature because it makes the check immune to time-of-check, time-of-use races on user memory26. The consequence for policy is that seccomp can block open but cannot tell which path is being opened, and it can inspect the flags argument of clone but not the structure that clone3 receives through a pointer. That is why containerd's profile answers clone3 with ENOSYS instead of trying to filter it, while it filters the namespace flags of clone, which sit in a register.
Evaluation happens in seccomp_run_filters()3. It walks the list from the newest filter through f->prev, runs every program, and keeps the result with the lowest action value, compared through ACTION_ONLY(), which casts the masked value to s32. The cast is why SECCOMP_RET_KILL_PROCESS, 0x80000000, is the most negative value and always wins, followed by KILL_THREAD at zero. Filters can be added but never removed, and since every filter runs and the most restrictive answer wins, a process can only ever narrow its own policy. seccomp(2) documents the same ordering28.
Two implementation details matter at scale. First, seccomp_attach_filter() caps the total program length on any path at MAX_INSNS_PER_PATH, defined as (1 << 18) / sizeof(struct sock_filter); a sock_filter is 8 bytes, so the cap is 32,768 instructions, with a penalty of four instructions charged per filter. Second, since the action cache landed, seccomp_cache_prepare_bitmap() emulates each new filter once per syscall number with a fixed architecture and records in a bitmap every syscall the filter allows regardless of its arguments. On the hot path seccomp_cache_check_allow() tests that bit and returns SECCOMP_RET_ALLOW without running any BPF. Allowlist profiles, which allow most syscalls unconditionally, are therefore close to free for the common syscalls. Argument-dependent rules are not cached and still run the program.
Installing a filter requires either CAP_SYS_ADMIN in the caller's user namespace or the no_new_privs bit28. Otherwise a filter that returns ERRNO for a setuid helper could make that privileged program fail in a way its author never expected. The small program below builds a filter by hand. It kills any non x86-64 caller, refuses the x32 syscall range (seccomp(2) warns that arch alone does not distinguish x32 from x86-64), turns unshare into EPERM, and allows the rest:
#define _GNU_SOURCE
#include <errno.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <sched.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
static struct sock_filter filter[] = {
/* Load seccomp_data.arch and kill anything that is not native x86-64. */
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
/* Load seccomp_data.nr and reject x32 numbers. */
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 0x40000000, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ENOSYS),
/* unshare(2) fails with EPERM, everything else is allowed. */
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_unshare, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
int main(int argc, char **argv) {
struct sock_fprog prog = { .len = sizeof(filter) / sizeof(filter[0]), .filter = filter };
int set_nnp = argc > 1 && strcmp(argv[1], "nnp") == 0;
if (set_nnp && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
perror("prctl(PR_SET_NO_NEW_PRIVS)");
return 1;
}
if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog) != 0) {
perror("seccomp(SECCOMP_SET_MODE_FILTER)");
return 1;
}
if (unshare(CLONE_NEWUSER) != 0) {
perror("unshare(CLONE_NEWUSER)");
}
execlp("grep", "grep", "-E", "^(NoNewPrivs|Seccomp)", "/proc/self/status", (char *)NULL);
perror("execlp");
return 1;
}$ gcc -O2 -Wall -o /tmp/seclab/deny_unshare /tmp/seclab/deny_unshare.c
$ /tmp/seclab/deny_unshare
seccomp(SECCOMP_SET_MODE_FILTER): Permission denied
$ /tmp/seclab/deny_unshare nnp
unshare(CLONE_NEWUSER): Operation not permitted
NoNewPrivs: 1
Seccomp: 2
Seccomp_filters: 1Seccomp: 2 is SECCOMP_MODE_FILTER and Seccomp_filters counts attached programs, both from proc_pid_status(5)29. The filter survived the execve into grep, as seccomp(2) documents.
RuntimeDefault is not one profile
Kubernetes lets a pod ask for seccompProfile.type: RuntimeDefault, and the kubelet can apply it to every pod that does not choose with --seccomp-default or seccompDefault in its configuration. That defaulting has been stable since v1.27 and is still opt-in per node; without it, a pod with no profile runs Unconfined, and a privileged container always runs Unconfined30. The Restricted standard requires RuntimeDefault or Localhost explicitly25.
What RuntimeDefault means is up to the runtime, and the difference is not cosmetic. containerd's profile in contrib/seccomp/seccomp_default.go at v2.4.231 allows unshare, setns, mount, fsopen, fsconfig and the namespace flags of clone only when CAP_SYS_ADMIN is in the container's bounding set, and bpf only with CAP_SYS_ADMIN or CAP_BPF; otherwise clone is allowed only with all CLONE_NEW* bits clear, and clone3 returns ENOSYS. The profile that ships in containers-common 0.67.2 for Podman, read from /usr/share/containers/seccomp.json on the lab host, allows unshare, mount, fsopen, fsconfig, keyctl and clone unconditionally and leaves the decision to the kernel. The lab shows the consequence. Inside a default Podman container, without CAP_SYS_ADMIN, a nested user and mount namespace is one command away:
$ podman run --rm registry.fedoraproject.org/fedora:43 sh -c \
'unshare --mount true; echo plain_mntns_rc=$?;
unshare --user --map-root-user --mount sh -c \
"mount -t tmpfs none /mnt && echo nested-tmpfs-ok"'
unshare: unshare failed: Operation not permitted
plain_mntns_rc=1
nested-tmpfs-okThe first unshare fails in unshare_nsproxy_namespaces(), a kernel capability check. The second succeeds for the reason given earlier: the new user namespace is created first, and the mount namespace check is made against it. Under containerd's profile the same unshare call would not reach the kernel, because the bounding set lacks CAP_SYS_ADMIN. I read that from the containerd source rather than running it, since this lab has no containerd node. Neither choice is wrong in isolation. Podman's design favours nested rootless tools; containerd's favours a smaller kernel surface. On a multi-tenant Kubernetes node I want containerd's behaviour, and the next escape shows why.
User namespaces in pods
KEP-127 adds pod.spec.hostUsers: when it is false, the kubelet asks the runtime to create a user namespace for the pod32. The Kubernetes documentation marks the feature stable since v1.36, with the UserNamespacesSupport gate locked on33. The current release at the time of writing is v1.37. The requirements are concrete and worth checking node by node, because a node that misses one fails pod creation instead of silently falling back:
- Linux 6.3 or later, because tmpfs, which backs projected service account tokens and Secrets, gained idmapped mount support in that release; every filesystem a pod volume uses must support idmapped mounts, and NFS does not33.
- An OCI runtime of runc 1.2 or later or crun 1.9 or later, and a CRI implementation of containerd 2.0 or later or CRI-O 1.25 or later33.
- Each pod gets a range of host IDs that does not overlap any other pod's; the size is
userNamespaces.idsPerPodin the kubelet configuration since v1.33, must be a multiple of 65536, and defaults to 6553633. hostUsers: falsecannot be combined withhostNetwork,hostPID,hostIPCorvolumeDevices33.
The KEP lists the CVEs it mitigates, and calls CVE-2019-5736 "completely mitigated"32. The reason is the ID map. With hostUsers: false, uid 0 in the container is some uid in the pod's private range on the host, owns nothing on the host filesystem, and holds no capability over any namespace the host owns. The Pod Security admission code takes the same view: for a pod with a user namespace it stops checking runAsNonRoot and runAsUser even under Restricted, because root inside "is never mapped to a privileged user on the host"33.
One configuration interacts badly with this. The obvious hardening against user namespace bugs is to set user.max_user_namespaces to 0 on the node. namespaces(7) documents the sysctls under /proc/sys/user as per-user limits that "apply to all users, including UID 0", with clone and unshare failing with ENOSPC once the limit is reached6. That includes the runtime creating the pod's namespace. You can have that sysctl or hostUsers: false, not both. I prefer the second plus a runtime seccomp profile that gates unshare on CAP_SYS_ADMIN: the pod gets a user namespace from the runtime, and the workload cannot make more of its own.
Three escapes and the boundary each crossed
| CVE | Component | What was crossed | What would have stopped it |
|---|---|---|---|
| CVE-2019-5736 | runc up to 1.0-rc6 | /proc/<pid>/exe magic link to the host runtime binary | User namespace with host root unmapped; SELinux container_t; fixed runc |
| CVE-2022-0185 | Linux kernel from 5.1-rc1, legacy_parse_param() | No namespace: the shared kernel's own parser | Seccomp gating unshare on CAP_SYS_ADMIN; LSM policy denying user namespace creation; patched kernel |
| CVE-2024-21626 | runc 1.0.0-rc93 to 1.1.11 | Leaked directory descriptor into the host mount tree | Fixed runc 1.1.12; SELinux type enforcement on host-labelled files; working directory / only |
CVE-2019-5736: the runtime's own executable
NVD describes it as runc through 1.0-rc6 letting a process running as root in a container "overwrite the host runc binary (and consequently obtain host root access)", either from an attacker-controlled image or through docker exec into a container the attacker could write to; NVD scores it 8.6 under CVSS 3.134. The disclosure on oss-security credits Adam Iwaniuk and Borys Popławski35.
Unit 42's write-up gives the sequence36. The attacker replaces a binary in the container, for example /bin/sh, with a script whose interpreter line is #!/proc/self/exe. When an operator runs docker exec and runc's child process enters the container and executes that file, the kernel's script loader resolves the interpreter through /proc/self/exe, which is a magic link to the executable of the current process: the runc binary on the host. A second process in the container opens /proc/<runc-pid>/exe. While runc is still running the kernel refuses to open its executable for writing; open(2) lists this as ETXTBSY, and the check is still there at v7.2, where fs/exec.c calls exe_file_deny_write_access()3723. The attacker waits for runc to exit, reopens the held file for writing, and overwrites the host binary. The next invocation of runc runs attacker code as host root.
Map that onto the task state. The mount namespace did its job: the container could not name the host binary. The magic link bypassed naming entirely: /proc/<runc-pid>/exe resolves to the exe_file of runc's mm_struct, and nd_jump_link() jumps to it as shown above. The credential check was the last line, and it failed for a structural reason: the process in the container was uid 0 in the initial user namespace, and the binary was owned by uid 0 in the initial user namespace. DAC said yes. Capabilities were irrelevant. Seccomp was irrelevant, because open and write are allowed by every useful profile.
runc's fix, commit 0a8e4117, titled "nsenter: clone /proc/self/exe to avoid exposing host binary to container", adds libcontainer/nsenter/cloned_binary.c38. ensure_cloned_binary() runs early in nsexec(), copies the runc binary into a memfd_create(2) file with sendfile, applies F_SEAL_SEAL, F_SEAL_SHRINK, F_SEAL_GROW and F_SEAL_WRITE, and re-executes from it. From then on /proc/self/exe resolves to a sealed anonymous file that cannot be written, so the magic link still exists but leads to an object that cannot be harmed. Unit 42 notes the cost: the copy is charged to the container's memory cgroup36.
The other mitigations are more interesting than the patch, because they are the general ones. The oss-security post says the bug was blocked where "the host root is not mapped into the container's user namespace", and by SELinux where container processes run as container_t35. Both work at the credential layer, below the magic link: a user namespace makes the DAC check fail, SELinux makes the label check fail. Neither depends on knowing the bug in advance. The Kubernetes response at the time recommended running containers as a non-zero uid39, which works for the same reason but has to be enforced per workload. hostUsers: false makes it a property of the node.
CVE-2022-0185: the kernel itself is the boundary
The second escape is a kernel bug, and it is the one that shows the limits of namespaces most clearly. The report on oss-security places it in fs/fs_context.c:legacy_parse_param(), introduced in 5.1-rc140. NVD describes a heap-based buffer overflow reachable by an unprivileged user when unprivileged user namespaces are enabled, "otherwise needs namespaced CAP_SYS_ADMIN privilege", with CVSS 3.1 score 8.441.
The new mount API lets user space build a superblock configuration with fsopen() and feed it options one by one with fsconfig(). A filesystem that had not been converted to the new API got legacy_init_fs_context(), and its options were concatenated by legacy_parse_param() into a single page-sized buffer allocated with kmalloc(PAGE_SIZE, GFP_KERNEL). Here is the check as it stood at v5.1642:
struct legacy_fs_context *ctx = fc->fs_private;
unsigned int size = ctx->data_size;
size_t len = 0;
...
if (len > PAGE_SIZE - 2 - size)
return invalf(fc, "VFS: Legacy: Cumulative options too large");
...
if (!ctx->legacy_data) {
ctx->legacy_data = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!ctx->legacy_data)
return -ENOMEM;
}
ctx->legacy_data[size++] = ',';
len = strlen(param->key);
memcpy(ctx->legacy_data + size, param->key, len);PAGE_SIZE - 2 - size is computed in unsigned arithmetic. Once earlier options have pushed size to 4095, the expression wraps to a very large value, the check passes for any len, and the following memcpy writes past the end of the 4,096-byte allocation40. The fix, commit 722d948, rewrites the comparison as if (size + len + 2 > PAGE_SIZE) so nothing is subtracted43.
Now the boundary question. fsopen() checks ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN) at v5.1644: capability over the caller's mount namespace, not over the host. As shown in the lab, unshare(CLONE_NEWUSER | CLONE_NEWNS) gives any unprivileged process exactly that. The report itself names the call40. From there, an options string written to a mount context that only exists inside a throwaway namespace corrupts the heap of the one kernel every container on the node shares. No namespace was crossed, because none was in the way. Namespaces change what the kernel's lookups return; they do nothing for a bug inside the kernel's own code.
What would have stopped it in a container is a layer that removes the entry point, and two of the four mechanisms can do that. The first is seccomp. A profile that refuses unshare without CAP_SYS_ADMIN in the bounding set, which is containerd's RuntimeDefault, stops the path before ksys_unshare() runs. A pod running Unconfined, which is still the Kubernetes default on a node without seccompDefault, does not.
The second is the LSM. At v7.2 create_user_ns() in kernel/user_namespace.c calls security_create_user_ns() before the new namespace is allocated20, and security/selinux/hooks.c registers selinux_userns_create() on that hook: an avc_has_perm() check of the user_namespace { create } permission of the task's SID against itself13. AppArmor registers apparmor_userns_create() on the same hook45, which has been in the kernel since Linux 6.1. A policy that withholds the permission makes unshare(CLONE_NEWUSER) fail, so fsopen() is never reached with namespaced privilege. The Fedora policy in this lab does not withhold it. container-selinux 2.251.0 contains allow container_domain self:user_namespace create;, and container_t is a container_domain46, which is why the nested-tmpfs-ok run above succeeded under SELinux enforcing. The two gates also differ in who controls them. In Kubernetes a pod spec selects its seccomp profile, and RuntimeDefault ships with the runtime. For the LSM a pod spec can only pick a label or a profile; whether that label may create a user namespace is decided by the policy installed on the node.
This is my main argument for treating seccomp as mandatory rather than optional hardening. Kernel bugs are the escapes that namespaces, capabilities and DAC cannot see, because the caller holds every privilege the check asks for. Only an entry-point control shrinks the kernel code a container can reach, and of the two, seccomp is the one the workload owner can require and verify from the pod spec.
A footnote on the code itself: at v7.2 fs/fs_context.c no longer contains a legacy path. alloc_fs_context() calls fc->fs_type->init_fs_context() unconditionally47, so every filesystem now parses options through the new API. That retires this particular parser. It does not retire the pattern of reaching namespaced-privileged kernel code through a fresh user namespace.
CVE-2024-21626: a descriptor that stayed open
The runc advisory GHSA-xr7r-f8xq-vfvv48 covers runc 1.0.0-rc93 through 1.1.11, fixed in 1.1.12, and NVD records a CVSS 3.1 score of 8.649. Several internal file descriptors leaked into runc init, among them a handle to the host's /sys/fs/cgroup.
The four attacks in the advisory are variations on one primitive. In attack 1 an image sets process.cwd to /proc/self/fd/7/, so the container's first process starts with a working directory in the host's mount tree. In attack 2 a process inside the container replaces the directory an operator will pass to runc exec --cwd with a symlink to the same place, then reads /proc/<exec-pid>/cwd. Attacks 3a and 3b use paths like /proc/self/fd/7/../../../bin/bash to execute a host binary and overwrite it through /proc/self/exe, the same move as CVE-2019-573648.
The boundary crossed is the one the --preserve-fds lab showed. A descriptor carries a struct file whose f_path points into the host's mount tree. setns() and pivot_root() change the task's namespace and root, but they do not touch the file table, and a magic link through /proc/self/fd jumps straight to f_path. Before 1.1.12, runc also did not check that chdir had left the process inside the container48.
The fix has four parts: verify after chdir that the working directory lookup does not fail with ENOENT, close all internal descriptors right before execve at the end of runc init, mark the /sys/fs/cgroup handle O_CLOEXEC, and mark every non-stdio descriptor O_CLOEXEC before running runc init48. The advisory describes the first check in terms of os.Getwd. The shipped verifyCwd() in libcontainer/init_linux.go calls unix.Getwd() instead, and its comment gives the reason: os.Getwd() can fall back to stat(".") through $PWD, which fails differently when the directory is inaccessible. The same comment states the mechanism described above, that the syscall prefixes (unreachable) and the wrapper turns it into ENOENT50. The check is therefore the same wrapper failure our lab produced from pwd -P, not a kernel error. The advisory recommends close_range(3, UINT_MAX, CLOSE_RANGE_CLOEXEC) to other runtimes as protection against future leaks48. It also notes there is no practical workaround for attack 3b short of not using runc exec, which in Kubernetes means kubectl exec on an unpatched node.
SELinux mitigates this one too, but not through the descriptor flush from the lab. In attacks 1 and 2 the escape lives in the working directory, which flush_unauthorized_files() does not inspect, and the leaked handle is a /sys/fs/cgroup directory that the policy lets the container read. On the lab host ls -Zd /sys/fs/cgroup prints system_u:object_r:cgroup_t:s0 /sys/fs/cgroup, and container.te in container-selinux 2.251.0 applies fs_list_cgroup_dirs() and fs_read_cgroup_files() to container_domain46; in Fedora's filesystem.if these expand to list_dirs_pattern() on cgroup_t and read_files_pattern() on the cgroup_type attribute51. A walk through that handle is permitted, so type enforcement has to catch the step after it. Attacks 3a and 3b resolve their path inside runc init before the final execve. What stops them is type enforcement on the next step: every open, write or exec of a host file reached through the escaped working directory is checked against the label of that file, and a container_t process has no access to host-labelled content. Red Hat's assessment of this CVE gives exactly that reason, saying that SELinux in enforcing mode "prevents the container processes from accessing host content"52. It is the same layer that stopped CVE-2019-5736, where the oss-security post credits the container_t label35. A user namespace narrows what attacks 3a and 3b can overwrite, since host binaries owned by host root fail the DAC check, but it does not stop attack 1 from reading what the mapped uid can read. That is the honest answer to "do user namespaces fix runc bugs": they turn a host root compromise into a host compromise of an unprivileged uid with no other files, which is a large reduction but not zero.
What to require of a node and a pod
Taken together, the three escapes say something specific. Two runtime bugs went through object references that namespaces never inspect, and the controls that held were the ones at the credential layer: an unmapped root, a mandatory access control label. One kernel bug needed no crossing at all, and the control that held was the one that removed the syscall path. None of them would have been enough alone, so each control below is worth stating as the mechanism it acts on and the escape it would have changed. A control that cannot be tied to either is one I do not count.
A current runtime is the only control that addresses the runc bugs at their source. Since 1.1.12 runc closes its internal descriptors and marks the rest close-on-exec, so the file table that reaches the container's first instruction holds nothing from the host, and it refuses a working directory that the Getwd wrapper reports as unreachable48. Everything else in this section exists for the next bug of the same shape. That is also why the runtime version has to be read from the binary the node actually executes, not assumed from the distribution release.
Dropping all capabilities and setting allowPrivilegeEscalation: false, both required by the Restricted Pod Security Standard25, act on the credential. An empty bounding, inheritable and ambient set leaves cap_capable_helper() nothing to find at any level of the walk, and no_new_privs makes cap_bprm_creds_from_file() refuse to grow the permitted set at execve. Neither would have stopped the escapes above. CVE-2019-5736 and CVE-2024-21626 needed only a uid that matched the owner of host files, and CVE-2022-0185 took its capability from a user namespace it created. Their value is in what an attacker holds after the first step of any escape, and in keeping CAP_SYS_ADMIN out of the bounding set, which is the condition containerd's seccomp profile tests.
RuntimeDefault, required by Restricted, and seccompDefault on the kubelet act on the seccomp entry gate, the BPF program that runs before the syscall body. On containerd that gate is what would have kept unshare and therefore CVE-2022-0185 out of reach. Without seccompDefault, a pod that names no profile runs Unconfined and the gate is absent30. On a runtime whose profile allows unshare unconditionally, as Podman's does in this lab, the gate exists but does not cover this path, and only an LSM policy that denies user_namespace { create } would.
hostUsers: false acts on the kuid comparison in the DAC check. It is the control that turns the overwrite of a root-owned host binary, in CVE-2019-5736 and in attacks 3a and 3b of CVE-2024-21626, into a failed write, because host root is a uid the pod's map does not contain. Its prerequisites belong to the node, not the pod: Linux 6.3 or later, runc 1.2 or crun 1.9 or later, and a CRI implementation of containerd 2.0 or CRI-O 1.25 or later33. SELinux enforcing, with containers in container_t, acts on the label check of every later open, write and exec, and in both runc escapes it held independently of the patch level3552.
These controls live in two places. The pod-level ones, the Pod Security admission labels on each namespace, the securityContext of every workload and hostUsers, are Kubernetes API objects: they belong in Git and are reconciled by Argo CD like everything else, so that a weaker setting appears in a pull request instead of on a node. The node-level ones, the kubelet configuration with seccompDefault, the container runtime and its version, the kernel and its LSM policy, are properties of the node pool. Argo CD does not reconcile them; they are set where the nodes are provisioned, in Terraform for the cluster's node pools, and checked on the node itself.
Checked from inside a workload, each of these leaves a trace in /proc/self/status, and each line reports kernel state rather than intent29. CapBnd is the cap_bset of the task's credential, so a decoded value without cap_sys_admin is the precondition containerd's profile depends on, and CapInh and CapAmb at zero mean that no execve can raise a bit around the bounding set. NoNewPrivs: 1 is the flag check_unsafe_exec() reads. Seccomp: 2 with a non-zero Seccomp_filters says that a filter list hangs off the task, though not which profile it holds; whether that list or an LSM closes the CVE-2022-0185 path shows only when an unshare --user --map-root-user --mount true inside the workload fails, as the Podman lab above shows it succeeding. /proc/self/uid_map shows whether container uid 0 is host uid 0. That is the level at which isolation can actually be verified, and the only level at which an assessment report about it means anything.
Kaynaklar
- include/linux/nsproxy.h (Linux v7.2) Linux kernel source
- include/linux/cred.h (Linux v7.2) Linux kernel source
- kernel/seccomp.c (Linux v7.2) Linux kernel source
- security/selinux/include/objsec.h (Linux v7.2) Linux kernel source
- include/linux/sched.h (Linux v7.2) Linux kernel source
- namespaces(7) Linux man-pages project
- fs/proc/fd.c (Linux v7.2) Linux kernel source
- fs/namei.c (Linux v7.2) Linux kernel source
- openat2(2) Linux man-pages project
- fs/d_path.c (Linux v7.2) Linux kernel source
- getcwd(3) Linux man-pages project
- unix/syscall_linux.go (golang.org/x/sys v0.38.0) Go project
- security/selinux/hooks.c (Linux v7.2) Linux kernel source
- user_namespaces(7) Linux man-pages project
- security/commoncap.c (Linux v7.2) Linux kernel source
- include/uapi/linux/capability.h (Linux v7.2) Linux kernel source
- kernel/fork.c (Linux v7.2) Linux kernel source
- kernel/nsproxy.c (Linux v7.2) Linux kernel source
- include/linux/user_namespace.h (Linux v7.2) Linux kernel source
- kernel/user_namespace.c (Linux v7.2) Linux kernel source
- capabilities(7) Linux man-pages project
- GHSA-2mm7-x5h6-5pvq: Default inheritable capabilities for linux container should be empty (CVE-2022-24769) Moby project security advisories, GitHub
- fs/exec.c (Linux v7.2) Linux kernel source
- pkg/oci/spec.go (containerd v2.4.2) containerd project
- Pod Security Standards Kubernetes documentation
- Seccomp BPF (SECure COMPuting with filters), Documentation/userspace-api/seccomp_filter.rst (Linux v7.2) Linux kernel documentation
- include/uapi/linux/seccomp.h (Linux v7.2) Linux kernel source
- seccomp(2) Linux man-pages project
- proc_pid_status(5) Linux man-pages project
- Restrict a Container's Syscalls with seccomp Kubernetes documentation
- contrib/seccomp/seccomp_default.go (containerd v2.4.2) containerd project
- KEP-127: Support User Namespaces in pods Kubernetes enhancements
- User Namespaces Kubernetes documentation
- CVE-2019-5736 NIST National Vulnerability Database
- CVE-2019-5736: runc container breakout (all versions) oss-security mailing list
- Breaking out of Docker via runC: Explaining CVE-2019-5736 Palo Alto Networks Unit 42
- open(2) Linux man-pages project
- nsenter: clone /proc/self/exe to avoid exposing host binary to container (commit 0a8e4117) runc project
- Runc and CVE-2019-5736 Kubernetes blog
- Linux kernel: Heap buffer overflow in fs_context.c since version 5.1 oss-security mailing list
- CVE-2022-0185 NIST National Vulnerability Database
- fs/fs_context.c (Linux v5.16) Linux kernel source
- vfs: fs_context: fix up param length parsing in legacy_parse_param (commit 722d948) Linux kernel source
- fs/fsopen.c (Linux v5.16) Linux kernel source
- security/apparmor/lsm.c (Linux v7.2) Linux kernel source
- container.te (container-selinux v2.251.0) containers project
- fs/fs_context.c (Linux v7.2) Linux kernel source
- GHSA-xr7r-f8xq-vfvv: several container breakouts due to internally leaked fds runc security advisories, GitHub
- CVE-2024-21626 NIST National Vulnerability Database
- libcontainer/init_linux.go, verifyCwd() (runc v1.1.12) runc project
- policy/modules/kernel/filesystem.if (selinux-policy v43.10) Fedora SELinux project
- CVE-2024-21626 Red Hat Customer Portal