26. The jailer

The jail around wick: seven boundaries and what crosses them Seven nested boundaries around the wick box, outermost first. A cgroup with three limits written on its edge: memory.max 268435456, pids.max 64, cpu.max 50000 100000. A user namespace whose uid map sends uid 0 to the invoking user. A network namespace that is empty: no interface but a loopback that is down. A mount namespace whose root holds a handful of names. A pid namespace in which wick is pid 1. A second, nested user namespace in which wick has the target uid and no capability. And the seccomp filter, the innermost boundary: three allowed system calls, ioctl, write and futex, pass down through it to the host kernel line below; a fourth, getppid, stops at the filter and ends the process with SIGSYS. Outside every boundary, at the left, is /dev/kvm, reached by a bind mount into the jail, and at the right the host client wick ctl, which reaches the API socket run/api.sock, a path in the jail root and not a network address. Below the figure, for comparison, hearth is one box with no boundaries: the trusted computing base is the image. cgroup: memory.max 268435456 pids.max 64 · cpu.max 50000 100000 user ns: uid_map 0 you 1 net ns: empty, lo is down mount ns: a handful of names pid ns: wick is pid 1 user ns: uid_map 1000 0 1 seccomp: kill_process wick API · VMM · vCPU /dev/kvm outside wick ctl on the host bind mount into the jail run/api.sock a path, not an address ioctl write futex getppid: SIGSYS host kernel: KVM, files, sockets for comparison hearth one box, no boundaries the TCB is the image

Why this layer exists

Chapter 25 made wick the program a hostile guest talks to. Its three device models read descriptors, packets and headers that the guest wrote (4,218 lines of code, in chapter 25’s count), in a process that holds /dev/kvm, the guest’s memory, a disk’s file, a TAP and a listening socket. Chapters 24 and 25 tested that code as hard as they could, and a security boundary has to assume the testing missed something: a guest finds a bug in the block device’s request parser and runs code as wick. This chapter asks what that code then holds.

Without more work, it holds everything the user who started wick holds: that user’s files, any socket, any process of that user to ptrace or kill, the ability to exec a shell, and a disk to fill. Two programs answer. The jailer, wick-jailer, assumes the VMM is compromised and takes away what it can reach, from outside, before the VMM runs: it builds a jail (a set of walls, each one a kernel mechanism chapter 15 defined) and execs wick inside it. The filter is what wick does to itself from inside, once it has done everything that needs wide access: it puts a seccomp-BPF allowlist on every thread, so that what is left of the host kernel’s system call surface (hundreds of calls; chapter 15 counted 472 in riscv64’s table) is a list of 35 names, some with their arguments checked, and no call that makes a thread. The jail removes places; the filter removes questions.

The pieces reappear. hearth has no jailer, and the chapter ends on why that is not an omission. Chapter 27 makes the same filter cover a paused and a restored guest, and adds to the list what that needs: the kick, KVM_KVMCLOCK_CTRL and fourteen reads of KVM’s state, and one openat that can only make a new file.

Mechanism

Sources: the Linux tree at tag v7.2.8 (the pinned tree the book has quoted since chapter 15; the hosts run 7.2.5 on talos and 6.18.51 on straylight, so a quotation says what the code at that tag says, and a behaviour claimed below was observed on talos or on straylight, as the text says); the seccompiler crate at 0.5.0, the version wick/Cargo.lock pins; Firecracker at tag v1.15.1 (docs/jailer.md, docs/seccomp.md, docs/seccompiler.md, src/seccompiler/build.rs and src/seccompiler/src/lib.rs, fetched raw at the tag); and the manual pages user_namespaces(7), pivot_root(2), chroot(2), mount_namespaces(7), pid_namespaces(7), seccomp(2), PR_SET_NO_NEW_PRIVS(2const), network_namespaces(7), proc_pid_root(5) and ptrace(2), fetched from man7.org with sift fetch on 2026-10-02 and quoted with their URLs. Chapter 15 defined namespace, user namespace, cgroup, capabilities and seccomp; this chapter uses them as defined there.

The order: build with capability, run with none

A process that builds a jail needs the power to make mounts, namespaces and cgroups. A process that runs inside one must have none of it. The two never overlap in time: the jailer has the power and exists only until it execs; the VMM exists only after. That is why a jailer is a program of its own and not a function wick calls on itself. wick-jailer has two forms, and which one runs is decided by its effective uid.

The unprivileged form is the lab’s. It runs as an ordinary user, and the power comes from a user namespace of its own: inside it the jailer is uid 0 with a full set of capabilities, over the namespaces that user namespace owns. The cgroup comes from a delegated systemd scope. Nothing is installed with privilege and nothing needs sudo. The root form, run as root, is Firecracker’s: it needs no user namespace, joins a network namespace someone prepared (--netns), and drops to a uid with a real setresuid. labs/ch26/root-form.sh runs it once, on straylight, with doas; the Lab section shows its output.

The steps, in the order the code takes them (the Walkthrough has each one):

  1. Validate every argument and path before anything is created: the id ([A-Za-z0-9-]{1,64}), the exec file (a regular file), the base directory, every bind source and destination, every cgroup file name. The jailer runs with more privilege than what it jails (in the root form, as root), so what it is told is checked as if it came from the jailed program.
  2. If any limit was asked for, make a cgroup <own cgroup>/<id>, move into it and write the limits.
  3. unshare a user namespace (unprivileged form), a mount namespace, a pid namespace and a network namespace, and write the uid and gid maps. Then open, in the new mount namespace, the directories and the files the jail will be built from: the base is walked from / without following a link and wick/<id>/root is made through it.
  4. fork. The parent waits, forwards a termination signal as SIGKILL, and reports how the child ended. The child is pid 1 of the new pid namespace; its first acts are to ask for SIGKILL if the parent dies and to take its standard input from /dev/null.
  5. In the child: make the root directory a mount point, make the mount points in it, bind the files the VMM needs and /dev/kvm (a bind mount makes an existing file or directory appear at a second path, in this mount namespace only), mount a fresh /proc.
  6. pivot_root into the new root, detach and remove the old one.
  7. Enter a second user namespace in which the VMM’s uid maps onto the first one’s root (unprivileged form), or setresgid and setresuid (root form).
  8. Close every descriptor above 2, set NO_NEW_PRIVS, exec the VMM with an empty environment. The VMM then starts, and when InstanceStart arrives it makes its vCPU thread, parked, puts its own filter on every thread and lets the vCPU run. (pivot_root, delegation and NO_NEW_PRIVS are defined where their sections come.)

cgroup v2: three limits, and a rule about processes

Version 2’s one rule that shapes the jailer is that a cgroup that has processes of its own cannot hand a controller to its children:

// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:507-513
No Internal Process Constraint
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Non-root cgroups can distribute domain resources to their children
only when they don't have any processes of their own.  In other words,
only domain cgroups which don't contain any processes can have domain
controllers enabled in their "cgroup.subtree_control" files.

So the jailer cannot make a child cgroup with limits and leave itself in the parent: it makes the child, moves itself in (the parent is then empty), and only then writes +cpu +memory +pids to the parent’s cgroup.subtree_control, which is what makes the child’s limit files exist. The permission to do any of this as an ordinary user is delegation:

// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:543-547
A cgroup can be delegated in two ways.  First, to a less privileged
user by granting write access of the directory and its "cgroup.procs",
"cgroup.threads" and "cgroup.subtree_control" files to the user.
Second, if the "nsdelegate" mount option is set, automatically to a
cgroup namespace on namespace creation.
// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:559-565
The end results are equivalent for both delegation types.  Once
delegated, the user can build sub-hierarchy under the directory,
organize processes inside it as it sees fit and further distribute the
resources it received from the parent.  The limits and other settings
of all resource controllers are hierarchical and regardless of what
happens in the delegated sub-hierarchy, nothing can escape the
resource restrictions imposed by the parent.

systemd-run --user --scope -p Delegate=yes makes a scope whose directory the user may write to. make doctor checks that the command works (its line is cgroup-scope), and with /dev/kvm, /dev/net/tun and unshare -Urn true that is all it checks of the jailer’s prerequisites: whether the scope holds the controllers the limits need, and whether a user namespace may mount a procfs or call pivot_root, only a run of the lab shows. What a delegated scope holds depends on the host’s systemd and kernel. systemd-run --user --scope -p Delegate=yes --quiet -- cat …/cgroup.controllers printed cpu memory pids on talos (kernel 7.2.5) and cpu io memory pids on straylight (6.18.51), 2026-10-02; the three the jailer enables are in both. Whether unprivileged user namespaces are allowed at all is a distribution’s choice as well, and the lab hosts both allow them; on a host whose policy restricts what a user namespace may do, make doctor can pass (it only runs unshare -Urn true) while the jailer’s first mount fails with a jailer: FAIL line that names the step.

The three limits the lab writes, each from the kernel’s own description:

// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:1376-1384
  memory.max
    A read-write single value file which exists on non-root
    cgroups.  The default is "max".

    Memory usage hard limit.  This is the main mechanism to limit
    memory usage of a cgroup.  If a cgroup's memory usage reaches
    this limit and can't be reduced, the OOM killer is invoked in
    the cgroup. Under certain circumstances, the usage may go
    over the limit temporarily.
// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:1193-1205
  cpu.max
    A read-write two value file which exists on non-root cgroups.
    The default is "max 100000".

    The maximum bandwidth limit.  It's in the following format::

      $MAX $PERIOD

    which indicates that the group may consume up to $MAX in each
    $PERIOD duration.  "max" for $MAX indicates no limit.  If only
    one number is written, $MAX is updated.

    This file affects only processes under the fair-class scheduler.
// linux v7.2.8, Documentation/admin-guide/cgroup-v2.rst:2404-2417
PID
---

The process number controller is used to allow a cgroup to stop any
new tasks from being fork()'d or clone()'d after a specified limit is
reached.

The number of tasks in a cgroup can be exhausted in ways which other
controllers cannot prevent, thus warranting its own controller.  For
example, a fork bomb is likely to exhaust the number of tasks before
hitting memory restrictions.

Note that PIDs used in this controller refer to TIDs, process IDs as
used by the kernel.

memory.max 268435456 is 256 MiB: the guest’s 128 MiB of RAM, which wick maps as anonymous memory and the kernel charges to the cgroup as the guest touches it, and the VMM’s own heap and stacks, with room. pids.max 64 counts tasks, threads included (the kernel’s text above: “PIDs used in this controller refer to TIDs”), and wick has four with the jailer’s parent (the parent, the VMM thread, the API thread and the vCPU thread). cpu.max 50000 100000 is a bandwidth, 50 ms of CPU time in every 100 ms period: half a core for everything in the cgroup, the guest’s vCPU included. Exercise (e) sets pids.max to 2 and shows what the process does when clone is refused.

The jailer writes a limit with a file opened for writing and never created: the kernel makes the interface files when it makes the cgroup, so a limit file the kernel does not have, a typo or a controller not enabled, is an error naming the file, and not an empty file the jailer made itself. The file name must be a controller’s file, cpu.*, memory.* or pids.*, the three controllers the jailer enables (an io.* file is refused, because the jailer never enables io, so the write would fail on both hosts after the cgroup was made, whatever the delegation; a cgroup.procs would move a process, as root any process of the host, into the jail’s cgroup, and cgroup.kill would kill it), with no / and no ..; the value is one printable line.

The user namespace and its map

A user namespace’s map is the translation between the uid and gid a process sees and the ones the kernel keeps underneath. The jailer writes it with three writes to files under /proc/self, and the order is not negotiable: setgroups to deny first (without it an unprivileged writer may not write gid_map), then the two maps. The rules for who may write what, from the manual:

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
In order for a process to write to the /proc/pid/uid_map
(/proc/pid/gid_map) file, all of the following permission
requirements must be met:

•  The writing process must have the CAP_SETUID (CAP_SETGID)
   capability in the user namespace of the process pid.

•  The writing process must either be in the user namespace of the
   process pid or be in the parent user namespace of the process
   pid.

•  The mapped user IDs (group IDs) must in turn have a mapping in
   the parent user namespace.

•  If updating /proc/pid/uid_map to create a mapping that maps UID
   0 in the parent namespace, then one of the following must be
   true:

   (a)  if writing process is in the parent user namespace, then
        it must have the CAP_SETFCAP capability in that user
        namespace; or

   (b)  if the writing process is in the child user namespace,
        then the process that created the user namespace must have
        had the CAP_SETFCAP capability when the namespace was
        created.

A process without privilege is in the second case of the manual’s list of what a write may contain:

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
•  One of the following two cases applies:

   (a)  Either the writing process has the CAP_SETUID (CAP_SETGID)
        capability in the parent user namespace.

        •  No further restrictions apply: the process can make
           mappings to arbitrary user IDs (group IDs) in the
           parent user namespace.

   (b)  Or otherwise all of the following restrictions apply:

        •  The data written to uid_map (gid_map) must consist of a
           single line that maps the writing process's effective
           user ID (group ID) in the parent user namespace to a
           user ID (group ID) in the user namespace.

        •  The writing process must have the same effective user
           ID as the process that created the user namespace.

one line, mapping its own uid to an id in the namespace, and nothing else. The jailer maps its own uid to 0, 0 <uid> 1. That is not what gives it power: unshare hands the caller a full set of capabilities in the new namespace whatever the map says (the manual, below), and an exec of any non-zero uid takes them away again. The map to 0 is there for two reasons that are about naming. The second namespace’s map has to name an outside id, and the id it names is this namespace’s 0 (the last section). And the jail’s files, which the user made, read as owned by root inside the first namespace, as a jail’s files do.

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
The child process created by clone(2) with the CLONE_NEWUSER flag
starts out with a complete set of capabilities in the new user
namespace.  Likewise, a process that creates a new user namespace
using unshare(2) or joins an existing user namespace using
setns(2) gains a full set of capabilities in that namespace.  On
the other hand, that process has no capabilities in the parent (in
the case of clone(2)) or previous (in the case of unshare(2) and
setns(2)) user namespace, even if the new namespace is created or
joined by the root user (i.e., a process with user ID 0 in the
root namespace).

The one mapped id is the whole population of the namespace: the invoking user is the only id that exists outside it, and every file the jailer makes, being that user’s, is owned inside by uid 0 (or, in the second namespace, by the target uid).

The network namespace

A new network namespace holds one interface, the loopback, down, and no address and no route. That is what the jailer’s unshare makes, and it is observed here (talos, 2026-10-02, unshare --user --map-root-user --net with ip -o link show, ip -o addr show and ip route show; the second and third print nothing):

# unshare --user --map-root-user --net ip -o link show
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000\    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

Two things follow, and the second is the reason the lab’s capture has no network line. First, a jailed VMM has no network unless one is handed to it: wick attaches to a TAP that exists (chapter 25), and making one takes CAP_NET_ADMIN over the network namespace, which the VMM does not have after the exec and the jailer’s empty namespace has no TAP in it. The root form takes the namespace as a path, --netns /run/netns/hp26, setnses into it before it does anything else, and finds tap0 there; the Lab section’s root-form run does. Second, the API socket and the vsock socket are unaffected: they are paths in a directory, run/api.sock and run/v.sock under the jail’s root, not network addresses, and a Unix socket connects through the file system and not through a network namespace (the namespace isolates the abstract socket names, network_namespaces(7), which wick does not use).

The mount namespace, pivot_root, and a root of four names

The jail’s root is a directory the jailer makes, <base>/wick/<id>/root, holding dev, proc, run and the VMM’s binary, and whatever the operator binds into it. Nothing else exists for the VMM: no /etc, no /home, no shell, no libraries (wick is a static executable, wick/Makefile), no other device node. A chroot would not do this. The manual for it says so in terms:

// chroot(2), https://man7.org/linux/man-pages/man2/chroot.2.html, fetched 2026-10-02
This call changes an ingredient in the pathname resolution process
and does nothing else.  In particular, it is not intended to be
used for any kind of security purpose, neither to fully sandbox a
process nor to restrict filesystem system calls.  In the past,
chroot() has been used by daemons to restrict themselves prior to
passing paths supplied by untrusted users to system calls such as
open(2).  However, if a folder is moved out of the chroot
directory, an attacker can exploit that to get out of the chroot
directory as well.  The easiest way to do that is to chdir(2) to
the to-be-moved directory, wait for it to be moved out, then open
a path like ../../../etc/passwd.

chroot changes how a path is resolved and nothing else: the old root is still a mount in the namespace, and a process that can reach it (a descriptor it kept, a directory moved out) is back in it. pivot_root changes the mount: the old root mount moves to a directory under the new one, and the jailer then unmounts it, so there is no old root left in the namespace to reach.

// pivot_root(2), https://man7.org/linux/man-pages/man2/pivot_root.2.html, fetched 2026-10-02
pivot_root() changes the root mount in the mount namespace of the
calling process.  More precisely, it moves the root mount to the
directory put_old and makes new_root the new root mount.  The
calling process must have the CAP_SYS_ADMIN capability in the user
namespace that owns the caller's mount namespace.
// pivot_root(2), https://man7.org/linux/man-pages/man2/pivot_root.2.html, fetched 2026-10-02
•  new_root and put_old must be directories.

•  new_root and put_old must not be on the same mount as the
   current root.

•  put_old must be at or underneath new_root; that is, adding some
   nonnegative number of "/.." suffixes to the pathname pointed to
   by put_old must yield the same directory as new_root.

•  new_root must be a path to a mount point, but can't be "/".  A
   path that is not already a mount point can be converted into
   one by bind mounting the path onto itself.

•  The propagation type of the parent mount of new_root and the
   parent mount of the current root directory must not be
   MS_SHARED; similarly, if put_old is an existing mount point,
   its propagation type must not be MS_SHARED.  These restrictions
   ensure that pivot_root() never propagates any changes to
   another mount namespace.

The jailer takes these conditions one by one. It makes / private first (MS_REC | MS_PRIVATE), which is the condition above and also what keeps every mount it makes from being seen by the namespace it came from. It binds the root directory onto itself, because new_root must be a mount point and a plain directory is not (a plain directory is what the lab wants: the API socket is then visible from the host at <root>/run/api.sock). It makes old for put_old.

The jail is built through descriptors. The base directory is walked from / one component at a time with O_NOFOLLOW, and wick/<id>/root is made in it with mkdirat (a root that exists is an error); in the root form the base, wick and <id> must each be owned by root and not writable by group or others (wick is checked before the id is made in it), and the root is given to the program’s uid through its descriptor. A link planted at wick or at the id is an error, and nothing is made through it. Every mount point under the root, the fixed directories, the exec file’s, every bind’s and /dev/kvm’s, is made the same way, and the mount is made on /proc/self/fd/N of the descriptor the walk returned; every source is opened once, with O_PATH, before the building starts, and bound from its descriptor. All of these descriptors are opened after the unshare of the mount namespace, because a descriptor made before it names a mount of the old namespace, which this one cannot bind or mount on. Binding a file read-only is two calls, and the second is subtle: the bind first, then a remount that adds MS_RDONLY, and the remount has to keep the flags the source’s mount already has, because in a less privileged namespace the kernel locks them:

// mount_namespaces(7), https://man7.org/linux/man-pages/man7/mount_namespaces.7.html, fetched 2026-10-02
[5]  The mount(2) flags MS_RDONLY, MS_NOSUID, MS_NOEXEC, and the
     "atime" flags (MS_NOATIME, MS_NODIRATIME, MS_RELATIME)
     settings become locked when propagated from a more privileged
     to a less privileged mount namespace, and may not be changed
     in the less privileged mount namespace.
// linux v7.2.8, fs/namespace.c:3256-3281
static bool can_change_locked_flags(struct mount *mnt, unsigned int mnt_flags)
{
    unsigned int fl = mnt->mnt.mnt_flags;

    if ((fl & MNT_LOCK_READONLY) &&
        !(mnt_flags & MNT_READONLY))
        return false;

    if ((fl & MNT_LOCK_NODEV) &&
        !(mnt_flags & MNT_NODEV))
        return false;

    if ((fl & MNT_LOCK_NOSUID) &&
        !(mnt_flags & MNT_NOSUID))
        return false;

    if ((fl & MNT_LOCK_NOEXEC) &&
        !(mnt_flags & MNT_NOEXEC))
        return false;

    if ((fl & MNT_LOCK_ATIME) &&
        ((fl & MNT_ATIME_MASK) != (mnt_flags & MNT_ATIME_MASK)))
        return false;

    return true;
}

The jailer reads the target’s flags with statvfs and repeats nosuid, nodev, noexec, noatime and nodiratime in the remount; a remount that dropped one would be EPERM. The same remount adds flags: a bound data file or directory is nosuid, nodev and noexec, the program’s own file nosuid and nodev (it must run), and a device node nosuid and noexec (it must be a device). /dev/kvm is bound, not made: mknod is refused to a process without CAP_MKNOD in the initial namespace (the probe wick/examples/jail-probe.rs, which wick/tests/jailer.rs jails, calls it from inside the jail and gets EPERM), and a bind mount of the existing device node is allowed. Destinations may not overlap (a read-only bind under a later read-write one would be hidden, and a mount point below a read-write directory bind would be made inside the host’s directory), and nothing is bound in dev, proc, run or old but /dev/net/tun.

The last mount before the pivot is a fresh procfs, mounted for the new pid namespace, so that /proc inside shows the jail’s pids and not the host’s. It is mounted before the pivot. The reason is a rule in the kernel’s mount code, which Exercise (a) tests:

// linux v7.2.8, fs/namespace.c:6415-6443
static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags)
{
    const unsigned long required_iflags = SB_I_NOEXEC | SB_I_NODEV;
    struct mnt_namespace *ns = current->nsproxy->mnt_ns;
    unsigned long s_iflags;

    if (ns->user_ns == &init_user_ns)
        return false;

    /* Can this filesystem be too revealing? */
    if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED))
        return false;

    s_iflags = sb->s_iflags;
    if ((s_iflags & required_iflags) != required_iflags) {
        WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
              required_iflags);
        return true;
    }

    /*
     * Restricted variants don't need an already visible mount because they
     * don't expose the full filesystem view.
     */
    if (s_iflags & SB_I_RESTRICTED_VARIANT)
        return false;

    return !mnt_already_visible(ns, sb, new_mnt_flags);
}

mount_too_revealing is asked for procfs in a user-namespace-owned mount namespace, and answers yes unless mnt_already_visible finds a procfs mount in this very namespace that is “fully visible” (its own comment, below, defines that as having no locked child mounts that cover anything except an empty directory). On the lab hosts the host’s own /proc is such a mount before the pivot; inside a container whose /proc has masked mounts over non-empty paths there may be none even then, and the mount is refused at its first try. After the old root is detached, none is left, and the mount is refused.

// linux v7.2.8, fs/namespace.c:6393-6395
        /* This mount is not fully visible if there are any
         * locked child mounts that cover anything except for
         * empty directories.

The pid namespace

unshare(CLONE_NEWPID) does not move the caller; its children are born in the new namespace (chapter 15 showed this with unshare -f), so the jailer forks, and the child is pid 1 there. Two properties matter. The jailed VMM sees nothing of the host’s processes: /proc lists one pid, and a kill has nothing to name. And the VMM is the namespace’s init:

// pid_namespaces(7), https://man7.org/linux/man-pages/man7/pid_namespaces.7.html, fetched 2026-10-02
The first process created in a new namespace (i.e., the process
created using clone(2) with the CLONE_NEWPID flag, or the first
child created by a process after a call to unshare(2) using the
CLONE_NEWPID flag) has the PID 1, and is the "init" process for
the namespace (see init(1)).  This process becomes the parent of
any child processes that are orphaned because a process that
resides in this PID namespace terminated (see below for further
details).

The same page says what happens to the rest of the namespace when its init ends: the kernel terminates every process in it with SIGKILL. If wick ends, the jail ends with it. The other direction is the jailer’s, and it has two parts. First, PR_SET_PDEATHSIG with SIGKILL: the kernel kills the VMM if the jailer’s parent process dies. A child cannot ask for that safely by itself, because the parent may die before the request is made, so the parent holds the write end of a pipe that nothing writes to; the child closes its own copy, makes the request, and then looks at the pipe, where a hangup means the parent was already gone. Whenever the parent dies, the child is told. (A change of uid clears the request, so the root form makes it again just before the exec.) Second, the signals an operator sends: the jailed pid 1 ignores SIGTERM, SIGINT and SIGHUP from outside its namespace, so the jailer forwards each to the child as SIGKILL, which cannot be ignored. A jail has no state to save: the guest goes with it, and what the guest wrote is in the disk file already. The jailed program’s standard input is /dev/null, not the operator’s terminal, and its core-file limit is zero: the jailer’s own memory is nothing, but the VMM’s is its guest’s, and a process killed by the filter would otherwise write guest RAM to the host’s core store. From the host, one process has two ids, and NSpid in its /proc/PID/status lists them, the host’s first: that is why the lab’s capture says jail: NSpid depth 2, one pid namespace below the host’s.

The second user namespace, and what removes the capabilities

After the pivot the jailer is still uid 0 with every capability in its user namespace, and the VMM is about to run. The jailer’s last step before the exec is a second user namespace: unshare(CLONE_NEWUSER) again, with the map <uid> 0 1, so that the VMM’s uid is the target uid in the new one, and the old one sees it as its own root. A process that is not uid 0 in its namespace loses every capability at exec, and the manual says so:

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
Note that a call to execve(2) will cause a process's capabilities
to be recalculated in the usual way (see capabilities(7)).
Consequently, unless the process has a user ID of 0 within the
namespace, or the executable file has a nonempty inheritable
capabilities mask, the process will lose all capabilities.  See
the discussion of user and group ID mappings, below.

(The second namespace’s map, <uid> 0 1, names the first namespace’s own uid 0 as the outside id, which is the case the fourth rule of the earlier list covers, since Linux 5.12: the process that created the namespace must have had CAP_SETFCAP when it did, and the jailer, root of the first namespace, has it.) The kernel’s side of that sentence, in cap_bprm_creds_from_file:

// linux v7.2.8, security/commoncap.c:935-937
    root_uid = make_kuid(new->user_ns, 0);

    handle_privileged_root(bprm, has_fcap, &effective, root_uid);
// linux v7.2.8, security/commoncap.c:970-974
    /*
     * Now that we've computed pA', update pP' to give:
     *   pP' = (X & fP) | (pI & fI) | pA'
     */
    new->cap_permitted = cap_combine(new->cap_permitted, new->cap_ambient);

root_uid is this namespace’s uid 0, as the kernel’s uid; handle_privileged_root gives a process whose uid is that one a permitted set from the bounding set; any other uid gets only what the file’s capabilities and its own inheritable and ambient sets give (pP' = (X & fP) | (pI & fI) | pA'), and for a static executable with no file capabilities that is nothing. Exercise (b) tests this, and the result is not the one the order of the steps suggests: a process in a user namespace that maps its uid straight to a non-root id keeps every capability it already has until the exec, so the jailer’s own mounts and its pivot work, and the VMM has none afterward either way. The second namespace is not what removes the capabilities; the exec of a non-zero uid is.

What the second namespace changes is who owns the jail’s other namespaces, and that can be observed. Privileged operations on a namespace need capabilities in the user namespace that owns it:

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
When a nonuser namespace is created, it is owned by the user
namespace in which the creating process was a member at the time
of the creation of the namespace.  Privileged operations on
resources governed by the nonuser namespace require that the
process has the necessary capabilities in the user namespace that
owns the nonuser namespace.

The mount, pid and network namespaces of the jail are owned by the first user namespace, the one the jailer made. A VMM that ran in the first namespace would be a process of that namespace; with the first map straight to the target uid it would hold no capabilities after its exec, and with the shipped map, which sends the user to 0, an exec’d uid-0 program would keep every one it has. A VMM in the second is a process of a user namespace that is a child of the owner, and its capabilities, were it ever to hold any (by a kernel bug; neither design has a legitimate way), would reach only what its own namespace owns, and the jail’s namespaces are not that. The NS_GET_USERNS ioctl names the owner of a namespace, and the kernel refuses to name it to a process whose own user namespace is below the owner’s:

// user_namespaces(7), https://man7.org/linux/man-pages/man7/user_namespaces.7.html, fetched 2026-10-02
The NS_GET_USERNS ioctl(2) operation can be used to discover the
user namespace that owns a nonuser namespace; see ioctl_nsfs(2).

wick/examples/jail-probe.rs, jailed, calls it on /proc/self/ns/mnt, pid and net: with the second namespace each is EPERM (the owner is an ancestor); with the first map straight to the target uid and no second namespace, each returns the caller’s own user namespace (Exercise (b) shows both runs). wick/tests/jailer.rs asserts the first. So the second namespace is a second wall behind a wall that already holds, and what it adds is exactly this: capabilities that the VMM might somehow obtain do not apply to the jail.

NO_NEW_PRIVS

prctl(PR_SET_NO_NEW_PRIVS, 1) sets a bit that a process cannot clear again and that its children inherit; after it, execve can no longer give the process more than it has:

// PR_SET_NO_NEW_PRIVS(2const), https://man7.org/linux/man-pages/man2/PR_SET_NO_NEW_PRIVS.2const.html, fetched 2026-10-02
Set the calling thread's no_new_privs attribute.  With
no_new_privs set to 1, execve(2) promises not to grant privileges
to do anything that could not have been done without the execve(2)
call (for example, rendering the set-user-ID and set-group-ID mode
bits, and file capabilities non-functional).

Once set, the no_new_privs attribute cannot be unset.  The setting
of this attribute is inherited by children created by fork(2) and
clone(2), and preserved across execve(2).

The kernel’s side is the downgrade in cap_bprm_creds_from_file, where a flag set by that bit makes a change of uid or a gain of capabilities at exec count for nothing:

// linux v7.2.8, security/commoncap.c:943-961
    /* Don't let someone trace a set[ug]id/setpcap binary with the revised
     * credentials unless they have the appropriate permit.
     *
     * In addition, if NO_NEW_PRIVS, then ensure we get no new privs.
     */
    id_changed = !uid_eq(new->euid, old->euid) || !in_group_p(new->egid);

    if ((id_changed || __cap_gained(permitted, new, old)) &&
        ((bprm->unsafe & ~LSM_UNSAFE_PTRACE) ||
         !ptracer_capable(current, new->user_ns))) {
        /* downgrade; they get no more than they had, and maybe less */
        if (!ns_capable(new->user_ns, CAP_SETUID) ||
            (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS)) {
            new->euid = new->uid;
            new->egid = new->gid;
        }
        new->cap_permitted = cap_intersect(new->cap_permitted,
                           old->cap_permitted);
    }

The jailer sets it just before the exec. It is also the price of installing a filter without privilege:

// linux v7.2.8, Documentation/userspace-api/seccomp_filter.rst:71-75
    Prior to use, the task must call ``prctl(PR_SET_NO_NEW_PRIVS, 1)`` or
    run with ``CAP_SYS_ADMIN`` privileges in its namespace.  If these are not
    true, ``-EACCES`` will be returned.  This requirement ensures that filter
    programs cannot be applied to child processes with greater privileges
    than the task that installed them.

so the VMM’s own install sets it again (the seccompiler call does, lines below). The lab’s capture shows jail: NoNewPrivs 1, and the bit is the jailer’s: it is 1 with the filter off too (the IMPL=mine run below), and jail: Seccomp is what the filter changes.

seccomp-BPF: a program, an allowlist, one list for every thread

A seccomp filter is a small program the kernel runs on every system call a thread makes, over data about the call:

// linux v7.2.8, Documentation/userspace-api/seccomp_filter.rst:16-28
Seccomp filtering provides a means for a process to specify a filter for
incoming system calls.  The filter is expressed as a Berkeley Packet
Filter (BPF) program, as with socket filters, except that the data
operated on is related to the system call being made: system call
number and the system call arguments.  This allows for expressive
filtering of system calls using a filter program language with a long
history of being exposed to userland and a straightforward data set.

Additionally, BPF makes it impossible for users of seccomp to fall prey
to time-of-check-time-of-use (TOCTOU) attacks that are common in system
call interposition frameworks.  BPF programs may not dereference
pointers which constrains all filters to solely evaluating the system
call arguments directly.

Two of those sentences carry the design. “The data operated on is related to the system call being made: system call number and the system call arguments”: a filter sees six integers, and “BPF programs may not dereference pointers”, so a filter cannot read a path or a buffer, and there is no check-then-use gap between what it saw and what the call uses. And the kernel’s own description of its limit:

// linux v7.2.8, Documentation/userspace-api/seccomp_filter.rst:33-41
System call filtering isn't a sandbox.  It provides a clearly defined
mechanism for minimizing the exposed kernel surface.  It is meant to be
a tool for sandbox developers to use.  Beyond that, policy for logical
behavior and information flow should be managed with a combination of
other system hardening techniques and, potentially, an LSM of your
choosing.  Expressive, dynamic filters provide further options down this
path (avoiding pathological sizes or selecting which of the multiplexed
system calls in socketcall() is allowed, for instance) which could be
construed, incorrectly, as a more complete sandboxing solution.

An allowlist is a filter whose default is to kill, with the names that may pass listed. wick’s says "match_action": "allow" and "mismatch_action": "kill_process":

// seccomp(2), https://man7.org/linux/man-pages/man2/seccomp.2.html, fetched 2026-10-02
SECCOMP_RET_KILL_PROCESS (since Linux 4.14)
       This value results in immediate termination of the process,
       with a core dump.  The system call is not executed.  By
       contrast with SECCOMP_RET_KILL_THREAD below, all threads in
       the thread group are terminated.  (For a discussion of
       thread groups, see the description of the CLONE_THREAD flag
       in clone(2).)

       The process terminates as though killed by a SIGSYS signal.
       Even if a signal handler has been registered for SIGSYS,
       the handler will be ignored in this case and the process
       always terminates.  To a parent process that is waiting on
       this process (using waitpid(2) or similar), the returned
       wstatus will indicate that its child was terminated as
       though by a SIGSYS signal.

kill_process and not kill_thread: a thread that makes a call off the list ends the whole process, so a compromised thread cannot leave the others running with its state. A handler for SIGSYS is not run and cannot catch it. A shell sees status 159, 128 plus 31, and the jailer prints jailer: child killed by signal 31 and exits with the same number. That kill would dump the process’s memory, the guest’s RAM included, so wick sets its core-file limit to zero before it does anything else. A panic ends the same way everywhere, through a hook wick installs before it makes a thread: the default hook prints the message, and the process leaves with _exit(101), the status an unwinding panic gives. The release profile’s abort would signal the process instead, and in the jail wick is pid 1 of its namespace, which ignores a signal it sends itself: the panic would not end the process by SIGABRT there (under the filter it would end at getpid with SIGSYS, as below). The hook needs exit_group, and gettid for the thread id in the message, both on the list. Any other abort (an allocation failure, a double panic, glibc’s own) is a policy kill under the filter: glibc’s abort calls gettid, which passes, and then getpid, which is off the list, and the kernel ends the process with SIGSYS at that call (strace of wick --probe-seccomp --probe-call abort ends gettid(), getpid(), +++ killed by SIGSYS (core dumped) +++; the same probe with --no-seccomp dies of SIGABRT, status 134). The tgkill that would follow could name only SIGRTMIN, which the list allows for the kick and for nothing else. wick also removes RUST_BACKTRACE from its own environment at startup, because a backtrace opens files and would turn the panic into a SIGSYS (the jailer’s empty environment does the same inside a jail).

The crate that compiles a JSON description of a filter into that program and installs it is seccompiler 0.5.0, the rust-vmm crate, in pure Rust. It is not Firecracker’s: at v1.15.1 Firecracker ships a seccompiler of its own in its tree, whose src/seccompiler/build.rs ends in println!("cargo::rustc-link-lib=seccomp") and whose lib.rs calls seccomp_init, seccomp_rule_add and seccomp_export_bpf of libseccomp. Firecracker compiles its default filters at build time and a filter given to its --seccomp-filter is one already compiled with seccompiler-bin. wick embeds the JSON and compiles it with the pure-Rust crate in main, at startup, before a socket is bound; its --seccomp-filter takes JSON, and the same flag name means a different input. Firecracker’s, in its own words and files:

// firecracker v1.15.1, docs/seccomp.md:24-26
At build time, the default target-specific JSON file is compiled into the
serialized binary file, using seccompiler-bin, and gets embedded in the
Firecracker binary.
// firecracker v1.15.1, docs/seccomp.md:59-60
Via Firecracker's optional `--seccomp-filter` parameter, one can supply the path
to a custom filter file compiled with seccompiler-bin.
// firecracker v1.15.1, docs/seccompiler.md:5-7
Seccompiler-bin is a tool that compiles seccomp filters expressed as JSON files
into serialized, binary BPF code that is directly consumed by Firecracker, at
build or launch time. The binary filters are serialized using bitcode format.
// firecracker v1.15.1, src/seccompiler/build.rs:4-7
fn main() {
    println!("cargo::rustc-link-search=/usr/local/lib");
    println!("cargo::rustc-link-lib=seccomp");
}
// firecracker v1.15.1, src/seccompiler/src/lib.rs:95-100
            let r = seccomp_init(default_action);
            if r.is_null() {
                return Err(CompilationError::LibSeccompContext);
            }
            r
        };

The install call of the crate wick uses:

// seccompiler 0.5.0, src/lib.rs:316-326
/// Apply a BPF filter to the all threads in the process via the TSYNC feature. Please read the
/// man page for seccomp (`man 2 seccomp`) for more information.
///
/// # Arguments
///
/// * `bpf_filter` - A reference to the [`BpfProgram`] to be installed.
///
/// [`BpfProgram`]: type.BpfProgram.html
pub fn apply_filter_all_threads(bpf_filter: BpfProgramRef) -> Result<()> {
    apply_filter_with_flags(bpf_filter, libc::SECCOMP_FILTER_FLAG_TSYNC)
}
// seccompiler 0.5.0, src/lib.rs:336-377
fn apply_filter_with_flags(bpf_filter: BpfProgramRef, flags: libc::c_ulong) -> Result<()> {
    // If the program is empty, don't install the filter.
    if bpf_filter.is_empty() {
        return Err(Error::EmptyFilter);
    }

    // SAFETY:
    // Safe because syscall arguments are valid.
    let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
    if rc != 0 {
        return Err(Error::Prctl(io::Error::last_os_error()));
    }

    let bpf_prog = sock_fprog {
        len: bpf_filter.len() as u16,
        filter: bpf_filter.as_ptr(),
    };
    let bpf_prog_ptr = &bpf_prog as *const sock_fprog;

    // SAFETY:
    // Safe because the kernel performs a `copy_from_user` on the filter and leaves the memory
    // untouched. We can therefore use a reference to the BpfProgram, without needing ownership.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_seccomp,
            libc::SECCOMP_SET_MODE_FILTER,
            flags,
            bpf_prog_ptr,
        )
    };

    #[allow(clippy::comparison_chain)]
    // Per manpage, if TSYNC fails, retcode is >0 and equals the pid of the thread that caused the
    // failure. Otherwise, error code is -1 and errno is set.
    if rc < 0 {
        return Err(Error::Seccomp(io::Error::last_os_error()));
    } else if rc > 0 {
        return Err(Error::ThreadSync(rc));
    }

    Ok(())
}

apply_filter_all_threads is SECCOMP_FILTER_FLAG_TSYNC:

// seccomp(2), https://man7.org/linux/man-pages/man2/seccomp.2.html, fetched 2026-10-02
       SECCOMP_FILTER_FLAG_TSYNC
              When adding a new filter, synchronize all other
              threads of the calling process to the same seccomp
              filter tree.  A "filter tree" is the ordered list of
              filters attached to a thread.  (Attaching identical
              filters in separate seccomp() calls results in
              different filters from this perspective.)

so the filter lands on every thread that exists: the API thread, the VMM thread that calls it, and the vCPU thread, which InstanceStart has made already and parked. The crate sets NO_NEW_PRIVS itself first. One list for every thread is a choice that Firecracker does not make. Its filters “are loaded in the Firecracker process, on a per-thread basis”:

// firecracker v1.15.1, docs/seccomp.md:7-12
The filters are loaded in the Firecracker process, on a per-thread basis, as
follows:

- VMM (main) - right before executing guest code on the VCPU threads;
- API - right before launching the HTTP server;
- VCPUs - right before executing guest code.

with a list for each of the three threads, installed at three moments, and none of the lists has clone in it, because the threads exist before their filters do. wick does the same for the same reason, and has one list and one install. The reason is the one that matters most in this section. A filter sees a call’s six integers, and clone3 takes a pointer to a structure whose flags the filter cannot read: a list that allows clone3 allows a compromised VMM to start threads without end (to pids.max) and to make user, mount, pid and network namespaces in which it holds every capability, whatever the rest of the list says. So no thread, process or namespace can be made after the filter: the vCPU thread is made first, parked, the filter goes on, and the thread is released, and clone, clone3, fork, vfork, unshare and setns are not on the list (a unit test pins that, and wick --probe-call clone3 dies of SIGSYS). Pausing a guest, which chapter 27 builds, therefore parks the vCPU thread and never ends and remakes it. The cost of one list is exact: the API thread is allowed everything the vCPU thread is, ioctl of KVM_RUN included, because the list is a union; the saving is one install, one place to be wrong, and a list that a trace can derive without first deciding which thread a call belongs to. The JSON’s comments say which thread makes each call, so the per-thread list can be read off it, and the cost can be paid down later without changing the install.

What ioctl rules can and cannot say

ioctl is a multiplexer: its second argument selects one of thousands of operations, and the first is any descriptor. Allowed bare, it would permit KVM_CREATE_VM on /dev/kvm, which a compromised VMM would use to make a second machine of its own. So the JSON has one rule for each request number the running VMM makes (index 1, eq, the number), and the numbers are KVM_RUN 0xae80, FIONBIO 0x5421, and fifteen that a pause and a snapshot make (chapter 27: fourteen reads of the machine’s state and KVM_KVMCLOCK_CTRL): seventeen rules. Exercise (d) takes the rules away and shows what is gained.

An argument rule is still not a capability system, and the reasons are in the first quotation: a filter sees integers. It sees the request number and not the descriptor’s kind: 0xae80 is allowed whatever the descriptor is, a vCPU or /dev/kvm or a socket; the kernel then judges it, and the filter has no part in it. It could name the descriptor’s number, but those are not stable between runs. It cannot see the structure a request points to, so KVM_SET_USER_MEMORY_REGION, were it listed, would be allowed for any region at all. The mitigation is in what is not on the list: one openat, whose rule passes only a write-only create-new with mode 0600 (chapter 27’s snapshot files), so no descriptor for a file that exists or for a device (socket for AF_UNIX, accept4 and fcntl for a duplicate of an eventfd do make descriptors, and recvmsg, which could receive one over a socket, is not listed); no execve; no mount; no clone and no unshare; and, in mmap and mprotect, no PROT_EXEC, the one argument rule that stops the data a VMM can write from becoming code it can run.

What Firecracker’s jailer does that this one does not

Firecracker’s docs/jailer.md at v1.15.1 opens with what it is for:

// firecracker v1.15.1, docs/jailer.md:5-10
The jailer is a program designed to isolate the Firecracker process in order to
enhance Firecracker's security posture. It is meant to address the security
needs of Firecracker only and is not intended to work with other binaries.
Additionally, each jailer binary should be used with a statically linked
Firecracker binary (with the default musl toolchain) of the same version.
Experimental gnu builds are not supported.

and lists what it does, in order:

// firecracker v1.15.1, docs/jailer.md:111-161
After starting, the Jailer goes through the following operations:

- Validate **all provided paths** and the VM ID.
- Close all open file descriptors based on `/proc/<jailer-pid>/fd` except input,
  output and error.
- Cleanup all environment variables received from the parent process.
- Create the `<chroot_base>/<exec_file_name>/<id>/root` folder, which will be
  henceforth referred to as `<chroot_dir>`. Nothing is done if the path already
  exists (it should not, since `<id>` is supposed to be unique).
- Copy the file specified with `--exec-file` to `<chroot_dir>/<exec_file_name>`.
  This ensures the new process will not share memory with any other Firecracker
  process.
- Set resource bounds for current process and its children through
  `--resource-limit` argument, by calling `setrlimit()` system call with the
  specific resource argument. If no limits are provided, the jailer bounds
  `no-file` to a maximum default value of 2048.
- Create the cgroup sub-folders. The jailer can use either `cgroup v1` or
  `cgroup v2`. On most systems, this is mounted by default in `/sys/fs/cgroup`
  (should be mounted by the user otherwise). The jailer will parse
  `/proc/mounts` to detect where each of the controllers required in `--cgroup`
  can be found (multiple controllers may share the same path). For each
  identified location (referred to as `<cgroup_base>`), the jailer creates the
  `<cgroup_base>/<parent_cgroup>/<id>` subfolder, and writes the current pid to
  `<cgroup_base>/<parent_cgroup>/<id>/tasks`. Also, the value passed for each
  `<cgroup_file>` is written to the file.
- Call `unshare()` into a new mount namespace, use `pivot_root()` to switch the
  old system root mount point with a new one base in `<chroot_dir>`, switch the
  current working directory to the new root, unmount the old root mount point,
  and call `chroot` into the current directory.
- Use `mknod` to create a `/dev/net/tun` equivalent inside the jail.
- Use `mknod` to create a `/dev/kvm` equivalent inside the jail.
- Use `chown` to change ownership of the `<chroot_dir>` (root path `/` as seen
  by the jailed firecracker), `/dev/net/tun`, `/dev/kvm`. The ownership is
  changed to the provided `<uid>:<gid>`.
- If `--netns <netns>` is present, attempt to join the specified network
  namespace.
- If `--daemonize` is specified, call `setsid()` and redirect `STDIN`, `STDOUT`,
  and `STDERR` to `/dev/null`.
- If `--new-pid-ns` is specified, call `clone()` with `CLONE_NEWPID` flag to
  spawn a new process within a new PID namespace. The new process will assume
  the role of init(1) in the new namespace. The parent will store child's PID
  inside `<exec_file_name>.pid`, while the child drops privileges and `exec()`s
  into the `<exec_file_name>`, as described below.
- Drop privileges via setting the provided `uid` and `gid`.
- Exec into
  `<exec_file_name> --id=<id> --start-time-us=<opaque> --start-time-cpu-us=<opaque>`
  (and also forward any extra arguments provided to the jailer after `--`, as
  mentioned in the **Jailer Usage** section), where:
  - `<id>`: (`string`) - The `<id>` argument provided to jailer.
  - `<opaque>`: (`number`) time calculated by the jailer that it spent doing its
    work.

This jailer does the same things in a different order (Firecracker closes descriptors and clears the environment first, joins the network namespace after the pivot and makes the pid namespace after the device nodes), with differences that are choices and one that is a loss. It does not copy the exec file; it binds it read-only. Firecracker copies so that the new process “will not share memory with any other Firecracker process”, and a bind mount of one binary shares its pages in the page cache between every jail that uses it: what is shared is read-only text, and a hundred jails cost no copies, but a deployment that wants Firecracker’s separation has to copy the file and bind the copy. It does not mknod the device nodes and chown them, because an unprivileged user cannot; it binds /dev/kvm, and /dev/net/tun when asked. It does not chroot after the pivot, as Firecracker’s does as a last step; after the pivot and the unmount there is no old root to resolve a path to. It does not set RLIMIT_NOFILE or RLIMIT_FSIZE, which Firecracker’s --resource-limit does (the default there is no-file 2048), it has no --daemonize, it does not write a pid file, and it knows only cgroup v2, where Firecracker also does v1. It always makes a new pid namespace, which Firecracker makes only for --new-pid-ns. And it clears the environment, as Firecracker’s first steps do.

What the unprivileged form cannot do is what the root form is for. It cannot join a network namespace that someone else made, so it cannot hand the VMM a TAP; it cannot drop to a uid that is not its own with setresuid, only map one; and the files in its jail are owned by the user who ran it, so a VMM that writes to its root writes to a directory of that user’s. The root form does all three, as root-form.sh shows, and it needs doas.

The root of the jail is a plain directory, writable by the jailed uid. Before the filter the VMM can create files in / and in /run, in the host’s jail directory; after it, the one call on the list that creates a file is chapter 27’s snapshot openat, whose rule passes only a write-only create-new (O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC): it can make a file in any directory the jailed uid may write (in the root form /run and the target of any --bind-rw of a directory, in the unprivileged form the jail’s root and its /dev as well, which are the invoking user’s directories), and it cannot open a file that exists, truncate one or replace one; and what remains is pwrite64 past the end of the read-write disk file, which no cgroup limit here bounds and RLIMIT_FSIZE (Firecracker’s --resource-limit fsize) would, and unlink, which is on the list for the sockets and can reach only the files in run/ that the process owns. Firecracker has the same exposure and says in its notes that cleanup is the operator’s. And without the filter the jailed program can read more than it should: its /proc/self/mountinfo shows the host paths of the root and of every bind source, and /proc/sys and /proc/cmdline are readable; an openat that can only create a new file cannot open them for reading, so wick cannot read them.

What hearth has instead

hearth has no jailer, and no filter. The reasons are the same reason. A jailer exists to confine a process: a program on a kernel that offers hundreds of system calls, a file system, a network stack and every other process of the machine, any of which a compromised VMM could use. hearth is not a process on a kernel. It is the hypervisor and its guest, on the CPU, with no system call table (the line that makes it hearth and not wick), no file system but what it carries, no other process. There is nothing for a jailer to remove and no kernel interface for a filter to narrow. The syllabus says the whole of it in four words, “the TCB is the image”, and the comparison the figure draws is the point of this chapter: wick’s trusted computing base is the VMM, plus Linux, plus KVM, plus the jailer and the filter that confine the first; hearth’s is the image and the CPU. Every wall in the figure is the price of the host kernel under the VMM, and a design that has no host kernel does not pay it, or buy what it pays for.

The axes

Chapter 14’s three axes, for the jail. Shared: the host kernel, through the system calls the filter allows (three threads, 35 names), and KVM inside it, which the jail does not confine: /dev/kvm is bound in, and what KVM_RUN does is the kernel’s. The cgroup limits are shared too, between the jailer’s parent and the VMM, which sit in the same cgroup. Trusted: the kernel’s namespace, mount, cgroup and seccomp code, which is where a bug is a jail escape; the jailer itself, which has the power to build the jail and is therefore the program whose arguments are validated as hostile; the operator, who names every path and limit and who is not trusted to name them safely (hence the validation); and seccompiler. The guest is trusted with nothing. Copy: the jail adds none to the data path (a bind mount is a name for a file, and /dev/kvm is the same device), and costs a fixed amount per VM at start, small: the Lab section’s whole run, two jails and a guest’s boot, takes under a second on both hosts.

Walkthrough

The cgroup

/// Make `<own cgroup>/<id>`, move this process into it, give the parent the controllers, and write each limit. The
/// parent must hold no process when it enables a controller for its children (cgroup v2's no-internal-processes rule),
/// so the move comes first. `root` is `/sys/fs/cgroup`; `mkdir` is `create_dir` (a test hands in one that also makes the
/// interface files the kernel makes for a new cgroup).
fn setup_cgroup(root: &Path, own: &str, id: &str, limits: &[(String, String)], pid: u32, mkdir: &dyn Fn(&Path) -> io::Result<()>) -> Res<()> {
    let parent = root.join(own.trim_start_matches('/'));
    let child = parent.join(id);
    mkdir(&child).map_err(os(&format!("mkdir {}", child.display())))?;
    write_file(&child.join("cgroup.procs"), &pid.to_string())?;
    write_file(&parent.join("cgroup.subtree_control"), "+cpu +memory +pids")?;
    for (file, value) in limits {
        write_file(&child.join(file), value)?;
        eprintln!("jailer: cgroup {file}={value}");
    }
    Ok(())
}

setup_cgroup is the four steps of the rule in order: mkdir, move this process (a write of its pid to the child’s cgroup.procs), enable the controllers on the parent, write the limits. write_file opens without O_CREAT, and mkdir is a parameter so that a test can hand in one that also makes the interface files, as the kernel does. Reading the own cgroup is parse_proc_cgroup, from the line 0::PATH of /proc/self/cgroup; a host on cgroup v1 alone has no such line and the jailer says so (a hybrid host has one, for the unified hierarchy, and the jailer then fails later, at the mkdir, if the controllers are not there). The function prints jailer: cgroup FILE=VALUE for each limit, which the lab pins.

The user namespace

/// Enter the new namespaces. Unprivileged: a user namespace in which this process is root (uid 0 maps to the caller), and
/// a mount, a pid and a network namespace that user namespace owns. Root form: no user namespace; the network namespace
/// is the one `--netns` names, or a new empty one. The pid namespace takes effect for the children, so the caller forks next.
fn enter_namespaces(root_form: bool, netns: Option<&Path>, euid: u32, egid: u32) -> Res<()> {
    if root_form {
        if let Some(path) = netns {
            let f = File::open(path).map_err(os(&format!("open {}", path.display())))?;
            // SAFETY: `f` is an open descriptor; CLONE_NEWNET makes setns refuse anything that is not a network namespace.
            if unsafe { libc::setns(f.as_raw_fd(), libc::CLONE_NEWNET) } != 0 {
                return Err(format!("setns({}): {}", path.display(), io::Error::last_os_error()));
            }
        }
        let net = if netns.is_some() { 0 } else { libc::CLONE_NEWNET };
        return unshare(libc::CLONE_NEWNS | libc::CLONE_NEWPID | net, "mount, pid, net");
    }
    unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWPID | libc::CLONE_NEWNET, "user, mount, pid, net")?;
    write_maps(0, 0, euid, egid)
}

enter_namespaces is the whole of step 3. Root form: join the network namespace first, if one was named (setns with CLONE_NEWNET, which makes the kernel refuse a file that is not a network namespace), then unshare the mount and pid namespaces, and the network namespace too when none was named. Unprivileged form: all four in one unshare, then the three writes of write_maps, in the order the manual requires. The jailer’s uid and gid are read before the unshare, because afterward they read as the overflow id (65534, what the kernel shows for an id that has no mapping) until the map is written.

The mounts

/// Make the mount point for `dst` under `root` and return a descriptor that names it: the parent directories are made one
/// component at a time with `dir_at`, and a file is made with `O_CREAT | O_EXCL | O_NOFOLLOW`, so a mount target is always
/// something this jailer just made and never something a link led to. Mounts are then made on `/proc/self/fd/N` of that
/// descriptor, so the path is not looked up a second time.
fn mount_point(root: RawFd, dst: &[String], is_dir: bool) -> io::Result<OwnedFd> {
    let (last, parents) = dst.split_last().ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
    let mut cur: Option<OwnedFd> = None;
    for name in parents {
        cur = Some(dir_at(cur.as_ref().map_or(root, AsRawFd::as_raw_fd), OsStr::new(name))?);
    }
    let at = cur.as_ref().map_or(root, AsRawFd::as_raw_fd);
    if is_dir {
        return dir_at(at, OsStr::new(last));
    }
    let c = CString::new(last.as_str()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
    // SAFETY: `at` is an open directory descriptor, `c` a NUL-terminated name; O_EXCL refuses a name that exists.
    let fd = unsafe { libc::openat(at, c.as_ptr(), libc::O_CREAT | libc::O_EXCL | libc::O_WRONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0o644) };
    if fd < 0 { Err(io::Error::last_os_error()) } else { Ok(owned(fd)) }
}

/// A bind mount of `src` on the mount point `dst` (made here), then a remount that adds what the bind is to be: `MS_RDONLY` for
/// a read-only one, and the `extra` flags (`nosuid`, `nodev`, `noexec`: a bound file is data, not something to run or to
/// make a device of), and keeps the flags the source's mount already has, because in a user namespace the kernel locks them
/// (`nosuid`, `nodev`, `noexec`, the access-time mode) and a remount that drops one is `EPERM`.
fn bind(root: RawFd, src: &Src, dst: &[String], rw: bool, extra: libc::c_ulong) -> Res<()> {
    let point = mount_point(root, dst, src.is_dir).map_err(os(&format!("make /{}", dst.join("/"))))?;
    let what = format!("bind /{}", dst.join("/"));
    mount(Some(&fd_path(&src.fd)), &fd_path(&point), None, libc::MS_BIND).map_err(os(&what))?;
    // `point` still names what is under the new mount; a second look, through the same links-refused walk, names the mount.
    let top = reopen(root, dst, src.is_dir).map_err(os(&format!("reopen /{}", dst.join("/"))))?;
    let target = fd_path(&top);
    let mut vfs = std::mem::MaybeUninit::<libc::statvfs>::uninit();
    // SAFETY: `target` is a NUL-terminated path and `vfs` is a buffer of the right type that statvfs fills on success.
    if unsafe { libc::statvfs(target.as_ptr(), vfs.as_mut_ptr()) } != 0 {
        return Err(format!("statvfs {what}: {}", io::Error::last_os_error()));
    }
    // SAFETY: statvfs returned 0, so the buffer is initialised.
    let kept = unsafe { vfs.assume_init() }.f_flag & (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_NOATIME | libc::MS_NODIRATIME);
    let ro = if rw { 0 } else { libc::MS_RDONLY };
    mount(None, &target, None, libc::MS_REMOUNT | libc::MS_BIND | ro | extra | kept).map_err(os(&format!("remount {what}")))
}

/// Everything the jail's root needs, before the pivot: the root a mount point of its own, the fixed directories, the
/// exec file and the binds, `/dev/kvm`, and a procfs for the new pid namespace (mounted now, while the old `/proc` is
/// still in this mount namespace: the kernel refuses a procfs mount in a namespace that has no fully visible one). Returns a
/// descriptor on the root, on the mount that now covers it, for `pivot`.
fn build_root(o: &Opts, jail: &Jail, srcs: &Srcs, root_form: bool) -> Res<OwnedFd> {
    let r = fd_path(&jail.root);
    mount(None, c"/", None, libc::MS_REC | libc::MS_PRIVATE).map_err(os("make / private"))?;
    // The bind comes first and the descriptor after it: a descriptor opened before would name the directory under the mount.
    mount(Some(&r), &r, None, libc::MS_BIND).map_err(os("bind the root on itself"))?;
    let top = reopen(jail.base.as_raw_fd(), &[OsStr::new("wick"), OsStr::new(&jail.id), OsStr::new("root")], true).map_err(os("reopen the root"))?;
    // The root was bound by its descriptor and is re-opened by name: it must be the same directory.
    let (a, b) = (fstat(&jail.root).map_err(os("stat the root"))?, fstat(&top).map_err(os("stat the re-opened root"))?);
    if (a.st_dev, a.st_ino) != (b.st_dev, b.st_ino) {
        return Err("the root that was bound is not the directory found by name: the jail's path was changed under the jailer".into());
    }
    let raw = top.as_raw_fd();
    for d in FIXED_DIRS {
        let made = dir_at(raw, OsStr::new(d)).map_err(os(&format!("make /{d}")))?;
        if root_form && d == "run" {
            // The root form's program is not root: the one directory it writes in (the API and vsock sockets) is its own.
            // SAFETY: an open descriptor, an empty name and AT_EMPTY_PATH: the call changes the owner of exactly that directory.
            if unsafe { libc::fchownat(made.as_raw_fd(), c"".as_ptr(), o.uid, o.gid, libc::AT_EMPTY_PATH) } != 0 {
                return Err(format!("chown /run: {}", io::Error::last_os_error()));
            }
        }
    }
    let data = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC;
    // A program: it may run, and nothing else about it is special.
    bind(raw, &srcs.exec, std::slice::from_ref(&o.exec_name), false, libc::MS_NOSUID | libc::MS_NODEV)?;
    let flags = |src: &Src| if src.char_dev { libc::MS_NOSUID | libc::MS_NOEXEC } else { data };
    for (b, src) in o.binds.iter().zip(&srcs.binds).filter(|(b, _)| !b.rw) {
        bind(raw, src, &b.dst, false, flags(src))?;
    }
    for (b, src) in o.binds.iter().zip(&srcs.binds).filter(|(b, _)| b.rw) {
        bind(raw, src, &b.dst, true, flags(src))?;
    }
    bind(raw, &srcs.kvm, &["dev".into(), "kvm".into()], true, libc::MS_NOSUID | libc::MS_NOEXEC)?;
    let proc_point = dir_at(raw, OsStr::new("proc")).map_err(os("open /proc"))?;
    mount(Some(c"proc"), &fd_path(&proc_point), Some(c"proc"), libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC).map_err(os("mount proc"))?;
    Ok(top)
}

make_jail is the first of the descriptor walks: the base, wick, the id and the new root, with the checks of the root form and its fchownat. open_src opens a bind’s source once. mount_point is the walk that creates what is mounted over, and bind is the bind and the remount that makes it read-only and adds the flags; reopen exists because the descriptor mount_point returns names the directory under the mount, and the remount has to name the mount. build_root is the sequence: private mounts, the root bound on itself and re-opened through the base afterwards, the four fixed directories, the exec file and the binds (read-only first, then read-write), /dev/kvm, and the procfs. In the root form it also gives /run to the jailed uid.

The pivot

/// Make the root the jail's. `pivot_root(".", "old")` puts the old root at `/old`, a lazy unmount takes it out of the
/// namespace, and `rmdir` removes the empty name. After this the only names that exist are the ones `build_root` made.
fn pivot(root: &OwnedFd) -> Res<()> {
    // SAFETY: an open descriptor; fchdir changes this process's working directory to the root.
    if unsafe { libc::fchdir(root.as_raw_fd()) } != 0 {
        return Err(format!("chdir to the root: {}", io::Error::last_os_error()));
    }
    // SAFETY: both arguments are NUL-terminated strings; pivot_root has no libc wrapper, so it is the raw system call.
    if unsafe { libc::syscall(libc::SYS_pivot_root, c".".as_ptr(), c"old".as_ptr()) } != 0 {
        return Err(format!("pivot_root: {}", io::Error::last_os_error()));
    }
    std::env::set_current_dir("/").map_err(os("chdir to /"))?;
    // SAFETY: a NUL-terminated path and a flag word.
    if unsafe { libc::umount2(c"/old".as_ptr(), libc::MNT_DETACH) } != 0 {
        return Err(format!("umount /old: {}", io::Error::last_os_error()));
    }
    std::fs::remove_dir("/old").map_err(os("rmdir /old"))
}

chdir into the root, the raw pivot_root(".", "old") (there is no libc wrapper, the manual’s note), chdir("/") because the call does not change the working directory, a lazy unmount of /old, and rmdir. The lazy unmount detaches the mount from the namespace at once and finishes when nothing uses it. After this function the jailer prints the names in /, sorted, jailer: root: bzImage dev disk.img initramfs.cpio proc run wick: a listing of the root is behaviour, and the capture pins it.

The last steps

/// The last steps, in the jail's root: a second user namespace that maps the target uid and gid onto the first namespace's
/// root, or, in the root form, a real drop of group and user; then the parent-death signal again (a change of uid clears it),
/// every descriptor above 2 closed, `NO_NEW_PRIVS`, and the exec, with no environment. A process that is not uid 0 in its
/// namespace loses its capabilities at the exec, whichever of the two did the drop.
fn drop_and_exec(o: &Opts, root_form: bool, alive: RawFd) -> Res<std::convert::Infallible> {
    if root_form {
        // SAFETY: plain credential calls with values we validated; each result is checked. The group list goes first,
        // the gid before the uid, because after the uid is dropped the process may no longer change either.
        unsafe {
            if libc::setgroups(0, std::ptr::null()) != 0 {
                return Err(format!("setgroups: {}", io::Error::last_os_error()));
            }
            if libc::setresgid(o.gid, o.gid, o.gid) != 0 {
                return Err(format!("setresgid: {}", io::Error::last_os_error()));
            }
            if libc::setresuid(o.uid, o.uid, o.uid) != 0 {
                return Err(format!("setresuid: {}", io::Error::last_os_error()));
            }
        }
    } else {
        unshare(libc::CLONE_NEWUSER, "user")?;
        write_maps(o.uid, o.gid, 0, 0)?;
    }
    // SAFETY: prctl with integer arguments only.
    unsafe {
        libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0);
    }
    // The request was cleared by the uid change and is made again: a parent that died in between is found in the pipe.
    parent_alive(alive)?;
    // SAFETY: close_range(3, ~0, 0) closes every descriptor above stderr; there is nothing after it that uses one.
    if unsafe { libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, 0u32) } != 0 {
        return Err(format!("close_range: {}", io::Error::last_os_error()));
    }
    // SAFETY: prctl with integer arguments only.
    if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
        return Err(format!("prctl(NO_NEW_PRIVS): {}", io::Error::last_os_error()));
    }
    let path = format!("/{}", o.exec_name);
    let mut argv: Vec<CString> = vec![CString::new(path.clone()).map_err(|_| "NUL in the exec name")?];
    for a in &o.args {
        argv.push(CString::new(a.as_bytes()).map_err(|_| format!("argument {a:?} holds a NUL"))?);
    }
    let mut ptrs: Vec<*const libc::c_char> = argv.iter().map(|a| a.as_ptr()).collect();
    ptrs.push(std::ptr::null());
    let cpath = CString::new(path).map_err(|_| "NUL in the exec name")?;
    // The program gets an empty environment: nothing the jailer's caller exported (a token, a proxy, a path) crosses into the jail.
    let envp: [*const libc::c_char; 1] = [std::ptr::null()];
    // SAFETY: `cpath` and every pointer in `ptrs` are NUL-terminated strings that live until the call; both vectors end with null.
    unsafe { libc::execve(cpath.as_ptr(), ptrs.as_ptr(), envp.as_ptr()) };
    let e = io::Error::last_os_error();
    // The file is there (it was bound in); ENOENT from execve of a present file is its dynamic loader, which the jail does not hold.
    let hint = if e.raw_os_error() == Some(libc::ENOENT) { " (the file is in the jail, so it is its loader that is missing: the jail holds no libraries, build the program static)" } else { "" };
    Err(format!("exec {}: {e}{hint}", cpath.to_string_lossy()))
}

The root form’s three credential calls are in the order a drop must have: the supplementary groups, then the gid, then the uid, because after the uid has changed the process may no longer change the others. The unprivileged form is the second user namespace and its maps. Then the parent-death signal again (a change of uid clears it), the descriptors (close_range(3, ~0, 0), one call), NO_NEW_PRIVS, and the exec with an empty environment. The hint on ENOENT is for a mistake that looks like something else: the file is in the jail, so the missing file is the dynamic loader of a program that was not built static. What comes before it, in child and run, is the pipe and the signal handler of the pid-namespace section, the /dev/null for standard input, and the zero core-file limit main sets.

The jailer’s tests are in the file and in wick/tests/jailer.rs. The pure parts have 17 unit tests (the id, the SRC:DST split at the last colon, a destination that is not plain or that overlaps another, a cgroup file that is a path or not a controller’s, arguments that are not UTF-8, the own cgroup out of sample text, the mount-point walk against a symlink planted in it, the order and the failure of the cgroup writes). The integration tests run the real jailer, with no guest: one jails wick --probe-seccomp --no-seccomp and finds jailer: root: dev proc run wick and exit 0, and jails it without --no-seccomp and finds exit 159 and jailer: child killed by signal 31; one jails examples/jail-probe, a program that reports what it holds, and checks each line (pid 1, the uid, CapEff zero, no descriptor above 2 though the jailer had one open, standard input at end of file though the jailer’s was an open pipe, no environment though the jailer had one, a zero core limit, the owner of the mount, pid and network namespaces refused, the flags of every mount, an empty network namespace, a root of the names it was given, mknod, mount and chroot refused); one plants a symlink at wick and at the id under the base and finds the jail refused and the directory it points to empty; one jails under a base whose name is not UTF-8; one sends SIGTERM to a jailer whose wick is serving and finds exit 137; and one refuses eighteen bad command lines before a directory is made.

The filter

/// Apply the compiled filter to every thread of the process. `apply_filter_all_threads` sets `NO_NEW_PRIVS` itself and
/// uses `SECCOMP_FILTER_FLAG_TSYNC`, so every thread that exists, the API thread, the VMM thread and the parked vCPU
/// thread, is covered. A system call off the list kills the process. The filter is installed once per process, and a second
/// call does nothing. No thread is created afterwards (`clone3` is off the list), and a thread that first uses a `HashMap`
/// after this call would call `getrandom` for its hash keys and die: every thread's maps exist before it.
pub fn install(program: &seccompiler::BpfProgram) -> Result<()> {
    // mine:begin
    static INSTALLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    if INSTALLED.load(std::sync::atomic::Ordering::SeqCst) {
        return Ok(());
    }
    seccompiler::apply_filter_all_threads(program).map_err(|e| Error::Seccomp(format!("install: {e}")))?;
    INSTALLED.store(true, std::sync::atomic::Ordering::SeqCst);
    Ok(())
    // mine:end
}

install applies a compiled program to all threads, once. The program is made at startup: Policy::embedded() compiles the JSON built into the binary, Policy::from_file an operator’s document (a regular file, read up to a bound, never opened if it is a FIFO; --seccomp-filter replaces the shipped policy entirely, and a document that does not compile stops wick before it binds a socket), and a Vmm built on a thread of a test process has the default, Off, because a filter on a test harness would end the harness with its first unlisted call. Chapter 24’s ch24-instance-start listing shows the order: the vCPU thread is made parked, apply runs, the thread is started. The thread is released with resume, which is the one step after the filter, and if it fails the machine stays built, Running if the resume was sent and is unanswered and Paused if the thread never got it, and the error is the reply (chapter 24).

wick --probe-seccomp is the filter’s smallest test: it installs it as InstanceStart does and calls getppid, which is not on the list. wick/tests/seccomp.rs runs it and asserts signal 31; with --no-seccomp it asserts the line probe: getppid returned and exit 0. --probe-call clone3, unshare and setns make those calls instead (harmless where allowed: null arguments, an invalid descriptor) and die of SIGSYS; --probe-call abort calls glibc’s own abort, which ends with SIGSYS under the filter and SIGABRT without it; --probe-panic panics after the install and exits 101 with its message, jailed or not, filtered or not.

The list

The list is the JSON, quoted whole: wick/seccomp/x86_64.json, lines 1 to 59 (a test, tests/seccomp.rs, compares this block with the file, so the two cannot drift apart). Each entry’s comment names the thread and the reason, and the labs whose traces show it:

{
  "wick": {
    "mismatch_action": "kill_process",
    "match_action": "allow",
    "filter": [
      { "syscall": "accept4", "comment": "vmm: the vsock bridge takes a host connection from its listener (labs 25)" },
      { "syscall": "brk", "comment": "any thread: the allocator grows the heap; seen on the VMM thread when a snapshot is made (labs 27)" },
      { "syscall": "close", "comment": "any thread: descriptors end: a connection, a thread's own files (labs 24, 25)" },
      { "syscall": "connect", "comment": "vmm: the vsock bridge connects to <uds_path>_<port>, a path the host listener made; the socket call below allows only AF_UNIX (labs 25)" },
      { "syscall": "epoll_ctl", "comment": "vmm: InstanceStart's reply registers the queue eventfds and the TAP on the event loop (labs 25)" },
      { "syscall": "epoll_wait", "comment": "vmm: the event loop waits; the vsock bridge polls its own epoll with a zero timeout (labs 24, 25)" },
      { "syscall": "exit", "comment": "vcpu: a thread ends by itself when the guest shuts down (labs 24, 25)" },
      { "syscall": "exit_group", "comment": "vmm: the process ends (labs 24, 25)" },
      { "syscall": "fcntl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 1030 }], "comment": "vmm: only F_DUPFD_CLOEXEC 0x406, the dup of a queue eventfd that InstanceStart's reply registers (labs 25)" },
      { "syscall": "fdatasync", "comment": "vmm: snapshot create flushes the memory file and the state file (labs 27); the block device's FLUSH request calls it too (wick/tests/hostile.rs)" },
      { "syscall": "futex", "comment": "any thread: mutexes under contention, the join of the vCPU thread, the channel to the API thread (labs 24, 25)" },
      { "syscall": "gettid", "comment": "any thread: the panic hook's message names the panicking thread by its id before the process leaves with status 101 (a panic probe shows it)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 21537 }], "comment": "vmm: FIONBIO 0x5421, set_nonblocking on a host connection the vsock bridge accepted (labs 25)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 44672 }], "comment": "vcpu: KVM_RUN 0xae80, every guest exit (labs 24, 25)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 44707 }], "comment": "vcpu: KVM_GET_TSC_KHZ 0xaea3, a snapshot's read of the guest's counter frequency (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 44717 }], "comment": "vcpu: KVM_KVMCLOCK_CTRL 0xaead, at every pause: tells the guest's kvm-clock the host stopped it (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2147790488 }], "comment": "vcpu: KVM_GET_MP_STATE 0x8004ae98, the first read of a vCPU's state at a snapshot (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2150674044 }], "comment": "vmm: KVM_GET_CLOCK 0x8030ae7c, a snapshot's read of the guest's kvm-clock (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2151722655 }], "comment": "vcpu: KVM_GET_VCPU_EVENTS 0x8040ae9f, the last read of a vCPU's state at a snapshot (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2154868383 }], "comment": "vmm: KVM_GET_PIT2 0x8070ae9f, a snapshot's read of the interval timer (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2155916961 }], "comment": "vcpu: KVM_GET_DEBUGREGS 0x8080aea1, a snapshot's read of the debug registers (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2156965505 }], "comment": "vcpu: KVM_GET_REGS 0x8090ae81, a snapshot's read of the general registers (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2167975555 }], "comment": "vcpu: KVM_GET_SREGS 0x8138ae83, a snapshot's read of the segment and control registers (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2173218470 }], "comment": "vcpu: KVM_GET_XCRS 0x8188aea6, a snapshot's read of the extended control registers (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2214637198 }], "comment": "vcpu: KVM_GET_LAPIC 0x8400ae8e, a snapshot's read of the local APIC's registers (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 2415963812 }], "comment": "vcpu: KVM_GET_XSAVE 0x9000aea4, a snapshot's read of the x87, SSE and AVX register state (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 3221794440 }], "comment": "vcpu: KVM_GET_MSRS 0xc008ae88, a snapshot's read of the model-specific registers, in chunks (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 3221794449 }], "comment": "vcpu: KVM_GET_CPUID2 0xc008ae91, a snapshot's read of the CPUID the guest was given (labs 27)" },
      { "syscall": "ioctl", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 3255348834 }], "comment": "vmm: KVM_GET_IRQCHIP 0xc208ae62, a snapshot's read of each interrupt controller, three times: the two PICs and the IOAPIC (labs 27)" },
      { "syscall": "madvise", "comment": "any thread: the allocator hands pages back (labs 24, 25)" },
      { "syscall": "mmap", "args": [{ "index": 2, "type": "dword", "op": { "masked_eq": 4 }, "val": 0 }], "comment": "any thread: allocator arenas; never PROT_EXEC 0x4; no lab call is made after the filter, a longer run can" },
      { "syscall": "mprotect", "args": [{ "index": 2, "type": "dword", "op": { "masked_eq": 4 }, "val": 0 }], "comment": "any thread: the allocator grows an arena; never PROT_EXEC 0x4, the call that would turn data into code; lab 27 shows one on the vCPU thread, when reading a snapshot's state grows its arena" },
      { "syscall": "mremap", "comment": "any thread: the allocator moves a large block when a Vec grows; no trace shows it after the filter, a longer run can" },
      { "syscall": "munmap", "comment": "any thread: the allocator and the thread's own stack at its end (labs 24, 25)" },
      { "syscall": "openat", "args": [{ "index": 0, "type": "dword", "op": "eq", "val": 4294967196 }, { "index": 2, "type": "dword", "op": "eq", "val": 524481 }, { "index": 3, "type": "dword", "op": "eq", "val": 384 }], "comment": "vmm: PUT /snapshot/create makes its two files, each a new one: the directory is AT_FDCWD (any path, relative or absolute, passes, since the kernel ignores the directory for an absolute one), the flags are exactly O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC (0x800c1) and the mode exactly 0600, so nothing is opened for reading, truncated or followed through a link, and no file is made executable or setuid (labs 27)" },
      { "syscall": "pread64", "comment": "vmm: the block device reads a request's sectors from the backing file (labs 25)" },
      { "syscall": "pwrite64", "comment": "vmm: the block device writes a request's sectors to the backing file (labs 25)" },
      { "syscall": "read", "comment": "vmm: the API wake-up eventfd, a doorbell eventfd, the TAP, the vsock timerfd and kick eventfd (labs 24, 25)" },
      { "syscall": "recvfrom", "comment": "vmm, api: a request off the API socket, bytes off a vsock bridge connection (labs 24, 25)" },
      { "syscall": "rt_sigprocmask", "comment": "vcpu: glibc blocks signals while a thread ends (labs 24, 25)" },
      { "syscall": "rt_sigreturn", "comment": "vcpu: the return from the SIGRTMIN kick handler, installed before the filter; a signal sent to the process by anyone with its uid must still return from it" },
      { "syscall": "sendto", "comment": "vmm, api: the API socket's reply, bytes onto a vsock bridge connection (labs 24, 25)" },
      { "syscall": "setsockopt", "args": [{ "index": 1, "type": "dword", "op": "eq", "val": 1 }], "comment": "api: only level SOL_SOCKET, the per-request receive and send timeouts (labs 24, 25)" },
      { "syscall": "shutdown", "comment": "vmm, api: the API reply's end, a vsock connection's half-close (labs 24, 25)" },
      { "syscall": "sigaltstack", "comment": "vmm, vcpu: a thread end disables the alternate stack std made at its start (labs 24, 25)" },
      { "syscall": "socket", "args": [{ "index": 0, "type": "dword", "op": "eq", "val": 1 }], "comment": "vmm: only AF_UNIX 1, the bridge's connect to a host listener; nothing else opens a socket (labs 25)" },
      { "syscall": "statx", "comment": "vmm: the vsock bridge checks that the socket file it removes is the one it made (labs 25)" },
      { "syscall": "tgkill", "args": [{ "index": 2, "type": "dword", "op": "eq", "val": 34 }], "comment": "vmm: the kick that pauses the vCPU thread, SIGRTMIN (34 on glibc) only; the process and thread are the caller's to name, and the call is made directly because glibc's pthread_kill makes a getpid call first (labs 27)" },
      { "syscall": "timerfd_settime", "comment": "vmm, vcpu: the vsock device arms its one-shot timer, from the doorbell path on the vCPU thread too (labs 25)" },
      { "syscall": "unlink", "comment": "vmm: the API socket and the vsock socket are removed at exit (labs 24, 25), and a snapshot create that fails removes the files it made" },
      { "syscall": "write", "comment": "any thread: the console, the log, the TAP, eventfds that raise an interrupt or wake a loop, and the snapshot's two files (labs 24, 25, 27)" }
    ]
  }
}

Read it by kind. The calls every thread makes to live: read, write, close, futex, the memory calls (mmap and mprotect without PROT_EXEC, munmap, madvise, brk, mremap), rt_sigprocmask, sigaltstack and exit, the thread’s own end. The calls of the three devices: pread64 and pwrite64 for the disk, read and write on the TAP, and for the vsock bridge socket (only AF_UNIX), connect, accept4, fcntl (only F_DUPFD_CLOEXEC), ioctl (only FIONBIO), epoll_ctl, epoll_wait, timerfd_settime, recvfrom, sendto, shutdown, statx and unlink. The API thread’s: accept4, recvfrom, sendto, setsockopt (only SOL_SOCKET), shutdown. The vCPU’s: ioctl of KVM_RUN, and, from chapter 27, of the fourteen reads of the machine’s state and KVM_KVMCLOCK_CTRL that a pause and a snapshot make (the VM’s three, KVM_GET_PIT2, KVM_GET_CLOCK and KVM_GET_IRQCHIP, are the VMM thread’s), and rt_sigreturn, the return from the SIGRTMIN handler. The VMM thread’s, for a snapshot: tgkill and openat, below. A panic’s: gettid. Three entries are in no trace of labs 24, 25 and 27 and are justified in their comments from the code: gettid, which only a panic reaches, and mmap and mremap, which the allocator makes whenever a heap or a large block grows, and a short lab may not. Chapter 27’s lab is the first whose trace shows brk, mprotect (on the vCPU thread, when reading a snapshot’s state grows its arena), fdatasync (the flush of the snapshot’s two files; before it a block device’s flush request was its only caller, and tests/hostile.rs’s flush test showed it under strace) and rt_sigreturn. The last was first tried by signalling a jailed wick from the host: one that was stopped with kill -STOP, continued with kill -CONT and sent kill -RTMIN while the guest waited (talos, 2026-10-02, a copy of labs/ch26/run.sh with those three lines added after the facts) went on to finish the guest’s run with Seccomp: 2. restart_syscall, which the kernel uses to resume a sleep with a timeout that a signal interrupted, is not on the list because nothing after the filter sleeps with one, and the same stop and continue needed none. mmap, mprotect, brk and mremap are listed for the allocator: a thread’s arena is made before the filter, and a longer run may grow it.

Two entries have an argument rule that matters beyond their name. tgkill(tgid, tid, sig) is allowed when sig is 34, SIGRTMIN under glibc (a unit test asserts the 34 against libc::SIGRTMIN()), and the kick calls it directly with the process and thread ids that were read before the filter, because glibc’s pthread_kill makes a getpid call first and getpid is not on the list. The rule pins the signal and not the target: the filter sees integers, and the thread’s id is not one it can know in advance. Read plainly, a compromised wick may send SIGRTMIN, whose default action is to terminate the process, to any thread its uid may signal. Outside a pid namespace that is any thread of any process of the same user whose id it can guess, so the clause is not a footnote there; inside the jail the pid namespace shrinks the set to the jail’s own threads, and a SIGRTMIN to one of those is what the kick does. The second is openat: AT_FDCWD as the directory, the flags equal to O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, 0x800c1, the mode equal to 0600, and a path the filter cannot see (for an absolute path the kernel ignores the directory, so AT_FDCWD does not confine the path). It can only create a file that does not exist, so no existing file is opened, truncated or replaced, no symbolic link is followed, nothing is read, and no file made is executable or setuid. What it costs: a compromised VMM can create files of any content it likes in any directory it can write: in the root form /run and the target of any --bind-rw of a directory, and in the unprivileged form the jail’s root and its /dev as well, because they are the invoking user’s directories; and it can fill a disk that no cgroup limit here bounds. Chapter 27 says why the snapshot’s files need it and why rename is not on the list.

What is not there is as much of the list as what is. The thread-start calls (clone3, prctl, rseq, set_robust_list, sched_getaffinity) and the install of the kick’s handler (rt_sigaction) are absent, because the vCPU thread is made and the handler installed before the filter goes on. KVM_GET_API_VERSION is absent because the start reads the version before the filter and prints it after. A thread that first used a HashMap after the filter would call getrandom for its hash keys and die, which is why the install comment names the trap: every thread’s maps exist before the filter does.

The method that made the list is a script, labs/ch26/derive.sh, and it is how the list is kept:

set -uo pipefail
unset CROSS CROSS_COMPILE ARCH
cd "$(dirname "$0")"
dir=${1:-out/derive}
mkdir -p "$dir"
dir=$(cd "$dir" && pwd)
rm -f "$dir"/*.trace
WICK_REAL=$(cd ../../wick && pwd)/target/x86_64-unknown-linux-gnu/release/wick
cat > "$dir/permissive.json" <<'JSON'
{"wick": {"mismatch_action": "log", "match_action": "allow", "filter": [{"syscall": "exit_group"}]}}
JSON
# The wrapper stands in for wick in the labs: `ctl` runs untraced, the VMM runs under strace. $DERIVE_LAB names the lab
# in the trace's file name, $$ makes each run's file its own.
cat > "$dir/wick-traced" <<WRAP
#!/usr/bin/env bash
real=$WICK_REAL
[ "\${1:-}" = ctl ] && exec "\$real" "\$@"
exec strace -f -qq -e raw=ioctl,mmap,mprotect,madvise,socket,fcntl,clone3,clone,openat,prlimit64,mremap,futex \\
  -o "$dir/\$DERIVE_LAB.\$\$.trace" "\$real" --seccomp-filter "$dir/permissive.json" "\$@"
WRAP
chmod +x "$dir/wick-traced"
status=0
for lab in ch24 ch25 ch27; do
  export DERIVE_LAB=$lab
  make -C "../$lab" run WICK="$dir/wick-traced" > "$dir/$lab.make.log" 2>&1 || { echo "derive: $lab run failed, see $dir/$lab.make.log" >&2; status=1; continue; }
  if diff -q "../$lab/capture.txt" "../$lab/out/run.txt" > /dev/null; then echo "derive: $lab capture matches under strace"; else echo "derive: $lab capture DIFFERS under strace" >&2; status=1; fi
done
python3 derive.py --check ../../wick/seccomp/x86_64.json "$dir" ch24 ch25 ch27 || status=1
exit $status

It runs chapter 24’s lab, chapter 25’s and chapter 27’s, with wick under strace -f and a filter that lets everything through. The filter is there for its install call: the seccomp(SET_MODE_FILTER) line in the trace is the exact point after which a call is the filter’s business, and the parser splits at it:

def parse(path):
    """-> list of (pid, name, args-text) in trace order, from the install on; and pid -> thread name."""
    calls, thread_names, order, seen_split = [], {}, [], False
    for raw in open(path, errors="replace"):
        m = LINE.match(raw.rstrip("\n"))
        if not m:
            continue
        pid, rest = int(m.group(1)), m.group(2)
        if pid not in order:
            order.append(pid)
        if rest.startswith("<...") or rest.startswith("+++") or rest.startswith("---"):
            continue
        c = CALL.match(rest)
        if not c:
            continue
        name, args = c.group(1), re.sub(r"\)\s*= .*$", "", c.group(2).replace(" <unfinished ...>", ""))
        if name == "prctl":
            n = re.match(r'PR_SET_NAME, "([^"]*)"', args)
            if n:
                thread_names[pid] = n.group(1)
        if name == SPLIT and not seen_split:
            seen_split = True
            continue
        if seen_split:
            calls.append((pid, name, args))
    if not seen_split:
        raise SystemExit(f"derive.py: {path}: no seccomp(...) call: was wick started with --seccomp-filter?")
    thread_names.setdefault(order[0], "wick (vmm)")
    for pid in order:
        thread_names.setdefault(pid, f"thread {pid}")
    return calls, thread_names

The install call is the exact marker: every thread already exists when it is made, so what follows is only what the three threads do at run time (a split at the first KVM_RUN would miss the VMM thread’s calls between the install and the vCPU’s first run: the release of the parked thread and the start’s log writes). The script prints a table by lab and by thread, the union, and a comparison with the JSON: names seen and not listed (any is a failure), and names listed and not seen (each must be justified in its comment). Run on 2026-10-03 as labs/ch26/derive.sh, the output on talos (Intel; the same names on straylight):

== ch24: 1 trace(s); calls made after the filter is installed, by thread
  wick (vmm): close 7, epoll_wait 1, exit_group 1, futex 4, munmap 3, read 1, sigaltstack 1, unlink 1, write 13
  wick_api: accept4 1, close 1, recvfrom 1, sendto 1, setsockopt 1, shutdown 1
  wick_vcpu0: close 1, exit 1, futex 1, ioctl 13943, madvise 1, munmap 1, rt_sigprocmask 1, sigaltstack 1, write 6810
  wick_vcpu0 ioctl requests: KVM_RUN 0xae80 x13943
  mmap/mprotect protections: none; with PROT_EXEC: 0
  socket domains: none
== ch25: 4 trace(s); calls made after the filter is installed, by thread
  wick (vmm): accept4 8, close 98, connect 4, epoll_ctl 24, epoll_wait 101, exit_group 4, fcntl 12, futex 16, ioctl 4, munmap 12, pread64 10, pwrite64 2, read 74, recvfrom 35, sendto 12, shutdown 6, sigaltstack 4, socket 4, statx 2, timerfd_settime 14, unlink 6, write 145
  wick_api: accept4 4, close 4, recvfrom 4, sendto 4, setsockopt 4, shutdown 4
  wick_vcpu0: close 4, exit 4, futex 4, ioctl 60274, madvise 4, munmap 4, rt_sigprocmask 4, sigaltstack 4, timerfd_settime 4, write 29501
  wick (vmm) ioctl requests: FIONBIO 0x5421 x4
  wick_vcpu0 ioctl requests: KVM_RUN 0xae80 x60274
  mmap/mprotect protections: none; with PROT_EXEC: 0
  socket domains: 0x1 x4
== ch27: 2 trace(s); calls made after the filter is installed, by thread
  wick (vmm): brk 1, close 17, epoll_ctl 2, epoll_wait 7, exit_group 1, fcntl 2, fdatasync 2, futex 12, ioctl 5, munmap 3, openat 2, pread64 3, read 6, sigaltstack 1, tgkill 1, unlink 1, write 32
  wick_api: accept4 4, close 4, futex 2, recvfrom 290, sendto 4, setsockopt 292, shutdown 4, write 2
  wick_vcpu0: close 1, exit 1, futex 6, ioctl 14883, madvise 1, mprotect 1, munmap 1, rt_sigprocmask 1, rt_sigreturn 1, sigaltstack 1, write 7270
  wick (vmm) ioctl requests: KVM_GET_CLOCK 0x8030ae7c x1, KVM_GET_PIT2 0x8070ae9f x1, KVM_GET_IRQCHIP 0xc208ae62 x3
  wick_vcpu0 ioctl requests: KVM_RUN 0xae80 x14859, KVM_GET_TSC_KHZ 0xaea3 x1, KVM_KVMCLOCK_CTRL 0xaead x1, KVM_GET_MP_STATE 0x8004ae98 x1, KVM_GET_VCPU_EVENTS 0x8040ae9f x1, KVM_GET_DEBUGREGS 0x8080aea1 x1, KVM_GET_REGS 0x8090ae81 x1, KVM_GET_SREGS 0x8138ae83 x1, KVM_GET_XCRS 0x8188aea6 x1, KVM_GET_LAPIC 0x8400ae8e x1, KVM_GET_XSAVE 0x9000aea4 x1, KVM_GET_MSRS 0xc008ae88 x13, KVM_GET_CPUID2 0xc008ae91 x1
  mmap/mprotect protections: mprotect(0x3) x1; with PROT_EXEC: 0
  socket domains: none

and the comparison against the JSON, which is the same on both hosts:

== check against ../../wick/seccomp/x86_64.json
  seen in a trace, not in the list: none
  in the list, seen in no trace (each needs a comment saying why): gettid, mmap, mremap
  ioctl requests seen, not in the list: none
  ioctl requests listed, seen in no trace: none
  bare ioctl rules: none

KVM_GET_MSRS is one number in the list and many calls: the vCPU thread makes it 13 times in chapter 27’s lab on talos and once on straylight, because a read that stops short at an MSR the guest cannot read is followed by another that starts after it (chapter 27), and on the Intel host the guest has no VMX, so its twelve capability registers are such MSRs.

On straylight (AMD, NixOS, glibc and the kernel differ from talos’s) the sets of names are the same and the counts differ: KVM_RUN was made 15,320 times in chapter 24’s lab, 65,792 in chapter 25’s and 16,238 in chapter 27’s, against 13,943, 60,274 and 14,859 on talos; the counts are the machine’s, and the names are what the list needs. That agreement is the point of tracing both: a call a different glibc makes only on one host would have appeared as a name seen on one and not the other.

A trace shows the paths a lab takes. A call reached only on an error path is not in it, and kills the VMM in production if it is not on the list. That is why the list was checked the other way as well, from the code: a search of wick/src for the calls that open, create, bind, connect, sleep, sync, resize or start something found mmap, mremap, gettid, fdatasync, brk and the signal return; the traces of labs 24, 25 and 27 show all but the first three. The search is a reading and can miss; the test of it is every lab and every test that starts a guest, run under the filter on both hosts.

Exercises

Each answer is a run on talos (Intel, 2026-10-02) in a scratch copy of wick/ and of labs/ch26/ with the edit the exercise names, on the lab’s own kernel and initramfs, bounded by timeout; the output of each run is kept outside the repository, one directory for each. Where an answer is a sentence from a manual or the kernel and not a run, it says so.

(a) Move the /proc mount in wick-jailer from before the pivot to after it, and run the lab. What happens, and what does the kernel’s rule say about when it is allowed?

Answer

The mount is refused, EPERM, and no VMM is started. The jailer’s own log, with the mount moved to after the pivot, the unmount of /old and the rmdir:

jailer: cgroup memory.max=268435456
jailer: cgroup pids.max=64
jailer: cgroup cpu.max=50000 100000
jailer: FAIL mount proc after the pivot: Operation not permitted (os error 1)
jailer: child exited 1

The rule is mount_too_revealing, above: a procfs may be mounted in a mount namespace that a user namespace owns only if that namespace already has a fully visible procfs. With the old root detached there is none. It is the pivot’s order that matters and not the pivot itself. The same edit with the mount made right after chdir("/"), before /old is detached, succeeds, because the host’s procfs under /old/proc is still a visible mount of the namespace, and the lab passes:

jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: virtio-mmio slot 1 type 19
wick: vcpu 0 exit Shutdown
wick: exit 0
jailer: child exited 0

(b) Map uid 1000 directly in the first user namespace, 1000 <uid> 1, instead of root. Which call fails first? Then also remove the second user namespace, and say what the capture shows and what, if anything, is different.

Answer

With the second namespace kept, nothing in the first half fails: the mounts, the pivot and the root listing all happen, because the jailer keeps every capability it has in the namespace until it execs. The first failure is the second namespace’s own map, 1000 0 1, which names an outside id, 0, that the first namespace never mapped (the manual’s rule above: “the mapped user IDs … must in turn have a mapping in the parent user namespace”):

jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
jailer: FAIL write /proc/self/uid_map: Operation not permitted (os error 1)
jailer: child exited 1

With the second namespace removed too, the whole lab passes, and the capture’s facts are the reference’s:

jail: NSpid depth 2
jail: CapEff 0000000000000000
jail: NoNewPrivs 1
jail: Seccomp 2
jail: cgroup pids.max 64
jail: cgroup memory.max 268435456
jail: cgroup cpu.max 50000 100000

The jailer, in that variant, is a process with every capability in the namespace that owns the jail, and then a process of uid 1000 with none, as user_namespaces(7) says an exec makes it. The same fact, with the tools of the shell instead of the jailer: a user namespace that maps root, then exec of mount --make-rprivate /, and one that maps uid 1000:

# map root (unshare --user --map-root-user --mount), then exec mount --make-rprivate /
Uid:    0    0    0    0
CapEff:    000001ffffffffff
rc=0
# map uid 1000 (unshare --user --map-user=1000 --mount), then exec the same
Uid:    1000    1000    1000    1000
CapEff:    0000000000000000
mount: /: must be superuser to use mount.
       dmesg(1) may have more information after failed mount system call.
rc=32

So “a process that maps straight to a non-zero id has no capabilities” is true of a process that has execed (the shell’s mount is a new program) and not of the jailer between two of its own calls. What differs is who owns the jail’s namespaces, which jail-probe reports with NS_GET_USERNS (the jailer with its second user namespace, then the variant with one):

# the jailer (two user namespaces)
uid: 1000 gid: 1000
CapEff: 0000000000000000
userns owner of mnt: Operation not permitted (os error 1)
userns owner of pid: Operation not permitted (os error 1)
userns owner of net: Operation not permitted (os error 1)
uid_map: 1000 0 1
# first map straight to uid 1000, no second user namespace
uid: 1000 gid: 1000
CapEff: 0000000000000000
userns owner of mnt: own
userns owner of pid: own
userns owner of net: own
uid_map: 1000 1000 1

In the variant the VMM is a process of the user namespace that owns its mount, pid and network namespaces (each ioctl returns it: “own”), without capabilities. With the second namespace the owner is an ancestor and the kernel refuses to name it, EPERM: whatever capabilities the VMM were ever to hold would be in a namespace that owns none of them. Both runs have CapEff zero.

(c) Remove the KVM_RUN rule from the ioctl entries and run the lab. Where does the VMM die?

Answer

At the vCPU thread’s first KVM_RUN, the first call the guest needs once the thread is released. In the jail, the lab’s log ends where the VMM was killed (the last wick: line is cut off, and the reply to PUT /actions never comes: the client’s line is ctl: io: bad response …):

jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2jailer: child killed by signal 31

Which call, from strace -f of chapter 24’s lab run with the edited list. The thread that makes the call is the one that named itself wick_vcpu0 earlier in the trace; the other two are the API thread (the middle id) and the VMM thread:

3083314 ioctl(11, KVM_RUN <unfinished ...>
3083308 write(2, "12", 2)               = 2
3083314 <... ioctl resumed>, 0)         = 16
3083308 write(2, "\n", 1)               = ?
3083309 <... futex resumed>)            = ?
3083314 +++ killed by SIGSYS (core dumped) +++
3083309 +++ killed by SIGSYS (core dumped) +++
3083308 +++ killed by SIGSYS (core dumped) +++

The call is entered and does not run: the = 16 on its resumed line is not a result but the call’s own number, __NR_ioctl in arch/x86/entry/syscalls/syscall_64.tbl, which the kernel’s syscall_rollback puts back into the registers so that a dump shows the original call (kernel/seccomp.c, lines 1363 and 1364). The process ends as though killed by SIGSYS (the trace’s “core dumped” is the signal’s default; wick sets its core-file limit to zero, so none is written); chapter 24’s lab prints wick rc=159. All three threads die: the list is one for the process, and kill_process takes the whole thread group.

(d) Replace the seventeen ioctl rules by one bare ioctl entry. A patched --probe-seccomp holds an open /dev/kvm (what the VMM holds) and then makes KVM_CREATE_VM. Name what an attacker gains, and say why a rule on the request number is still not a capability system.

Answer

A virtual machine of its own: the call succeeds and returns a new descriptor, which an attacker with code in the VMM can fill with memory regions and run, outside everything the VMM’s API controls. With the shipped list it is SIGSYS. The five runs, with the patched probe (--probe-call names the call, and the probe holds an open /dev/kvm as the VMM does; rc=159 is a shell’s view of signal 31):

# shipped filter, KVM_CREATE_VM (0xae01) on the held /dev/kvm descriptor
rc=159
# bare ioctl filter (bare-ioctl.json), KVM_CREATE_VM
probe: create_vm on fd 3 returned, errno Success (os error 0)
rc=0
# shipped filter, KVM_RUN (0xae80, on the list) on the descriptor of /dev/kvm, which is not a vCPU
probe: run on fd 3 returned, errno Invalid argument (os error 22)
rc=0
# shipped filter, getppid (off the list), for comparison
rc=159
# no filter, KVM_CREATE_VM
probe: create_vm on fd 3 returned, errno Success (os error 0)
rc=0

The third run is the other half of the answer. KVM_RUN is on the list, and the probe made it on the descriptor of /dev/kvm, which is not a vCPU: it passed the filter and the kernel refused it, EINVAL. The filter saw the number 0xae80 and had no way to see what the descriptor was; the kernel’s description of the limit, “policy for logical behavior and information flow should be managed with a combination of other system hardening techniques”, is that. A request number names an operation, not an object. Nor can a rule see a request’s argument structure (the filter “may not dereference pointers”), and a rule that named the descriptor by number would break the first time a descriptor numbered differently. What the real list relies on instead is what it leaves out: with one openat that can only create a new file, write-only, no descriptor for a file that exists or for a device, and AF_UNIX alone in socket, the descriptors the process can use for a new kind of thing are the ones it already has.

(e) Set pids.max to 2 and run the lab. What fails, and with which error?

Answer

The VMM’s first thread. The jailer’s parent and the VMM are two tasks, which is the limit, so the API thread cannot be made: wick prints one line and ends, and the jailer reports its status:

jailer: cgroup memory.max=268435456
jailer: cgroup pids.max=2
jailer: cgroup cpu.max=50000 100000
jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
wick: FAIL api socket: io: Resource temporarily unavailable (os error 11)
jailer: child exited 1

The error is EAGAIN (os error 11), and the kernel’s text says so: “it is not possible to violate a cgroup PID policy through fork() or clone(). These will return -EAGAIN if the creation of a new process would cause a cgroup policy to be violated” (Documentation/admin-guide/cgroup-v2.rst, lines 2458 to 2462 at the tag). The control client sees Connection refused on every request, because the socket was bound and never served, and the lab’s host-side check, host: FAIL sector 1 not written, is the verdict. At 64 the four tasks are far from the limit; the limit is for a VMM that has been made to fork or to start threads without end.

(f) While the lab’s guest waits, from the host, list /proc/PID/root/ for the wick process and compare it with the jail’s directory on the host. What does each show, and what permission makes the first possible?

Answer

Two views of one root. Through the process, the jail as the VMM sees it, with the bound files at their real sizes; through the directory the jailer made, the same names as empty mount points, because the binds live only in the jail’s mount namespace:

id -u: 1000; owner of /proc/2877190: 1000
readlink /proc/2877190/root: /
ls -l /proc/2877190/root/:
total 7332
-rw-r--r--   1 kyle kyle 1704960 Oct  2 06:01 bzImage
drwxr-xr-x   1 kyle kyle       6 Oct  2 06:01 dev
-rw-r--r--   1 kyle kyle    8192 Oct  2 06:01 disk.img
-rw-r--r--   1 kyle kyle 3334144 Oct  2 06:01 initramfs.cpio
dr-xr-xr-x 392 root root       0 Oct  2 06:01 proc
drwxr-xr-x   1 kyle kyle      28 Oct  2 06:01 run
-rwxr-xr-x   1 kyle kyle 2457280 Oct  2 06:01 wick
ls -l out/jail/wick/ch26/root/ (the host's path to the same directory):
total 0
-rw-r--r-- 1 kyle kyle  0 Oct  2 06:01 bzImage
drwxr-xr-x 1 kyle kyle  6 Oct  2 06:01 dev
-rw-r--r-- 1 kyle kyle  0 Oct  2 06:01 disk.img
-rw-r--r-- 1 kyle kyle  0 Oct  2 06:01 initramfs.cpio
drwxr-xr-x 1 kyle kyle  0 Oct  2 06:01 proc
drwxr-xr-x 1 kyle kyle 28 Oct  2 06:01 run
-rw-r--r-- 1 kyle kyle  0 Oct  2 06:01 wick
ls -l /proc/2877190/root/dev/:
total 0
crw-rw-rw- 1 root kvm 10, 232 Oct  2 06:01 kvm
wc -c of the bound files, through /proc/2877190/root and through the host path:
1704960 /proc/2877190/root/bzImage
      0 out/jail/wick/ch26/root/bzImage
1704960 total
mountinfo lines of the jail's mount namespace: 7
yama ptrace_scope: 1

The manual for the first path says what it is: “not merely a symbolic link. It provides the same view of the filesystem (including namespaces and the set of per-process mounts) as the process itself”, which is why readlink prints only / (the root is not a path in the host’s mount namespace) and listing the directory works. The permission is the one the same page names: “Permission to dereference or read (readlink(2)) this symbolic link is governed by a ptrace access mode PTRACE_MODE_READ_FSCREDS check”. That check, from ptrace(2):

(3)  Deny access if neither of the following is true:

     •  The real, effective, and saved-set user IDs of the target
        match the caller's user ID, and the real, effective, and
        saved-set group IDs of the target match the caller's group
        ID.

     •  The caller has the CAP_SYS_PTRACE capability in the user
        namespace of the target.

(4)  Deny access if the target process "dumpable" attribute has a
     value other than 1 (SUID_DUMP_USER; see the discussion of
     PR_SET_DUMPABLE in prctl(2)), and the caller does not have
     the CAP_SYS_PTRACE capability in the user namespace of the
     target process.

(https://man7.org/linux/man-pages/man2/ptrace.2.html, fetched 2026-10-02.) The caller is the user who ran the lab and the target is that user’s own process, in the kernel’s ids (the jail maps both ids to the invoking user’s), so the first bullet holds; the process is dumpable, so (4) holds, and no capability is needed. The first line of the run shows the two ids equal. A different user would be refused. The jail is a wall against what is inside it and not against the user who started it, who owns every namespace around it.

Lab

make lab CH=26
make lab CH=26 IMPL=mine
tools/remote-lab.sh lab CH=26
make -C wick test clippy

labs/ch26/Makefile includes the shared labs/lab.wick.mk and adds the two helpers this lab needs, the guest’s /bin/vsock and the host’s vsock-connect, built native and static from chapter 25’s sources into this lab’s own out/bin and overlay/bin (a lab runs from a clean tree without another lab’s out/), and a build target that makes wick, the guest and the helpers without running anything, which is what root-form.sh is run after. The guest’s init is chapter 25’s block section, then the vsock helper’s listener, which prints vsock: listening and waits until the host connects and sends a line:

mount -t proc proc /proc
mount -t devtmpfs devtmpfs /dev
mount -t sysfs sysfs /sys
dmesg -n 1
echo "=== lab begin"
if [ ! -b /dev/vda ]; then
  echo "blk: FAIL no /dev/vda"
else
  set -- $(hexdump -n 16 -e '16/1 "%02x "' /dev/vda)
  echo "blk: sector 0: $*"
  echo "blk: capacity $(cat /sys/block/vda/size) sectors"
  head -c 512 /dev/zero | tr '\0' 'Z' > /tmp/z512
  dd if=/tmp/z512 of=/dev/vda bs=512 seek=1 count=1 2>/dev/null
  sync
  blockdev --flushbufs /dev/vda
  dd if=/dev/vda bs=512 skip=1 count=1 of=/tmp/back 2>/dev/null
  if cmp -s /tmp/z512 /tmp/back; then echo "blk: write verified"; else echo "blk: FAIL write not verified"; fi
fi
# The root form's boot adds net=1: its jail joined a network namespace that holds tap0 (the unprivileged jail has none).
case " $(cat /proc/cmdline) " in
  *" net=1 "*)
    ip addr add 172.16.0.2/24 dev eth0
    ip link set eth0 up
    echo "net: $(ping -c 1 -W 2 172.16.0.1 | grep 'packets transmitted')"
    ;;
esac
# The helper prints "vsock: listening" once the port is bound, then holds still until the host connects and says "release".
/bin/vsock listen 6000
echo "=== lab end"
exec >/dev/null 2>&1 </dev/null
reboot -f

(The net=1 branch is for the root form’s boot only; the unprivileged lab has no network device.)

run.sh makes a delegated scope and runs the jailer in it in the background, with the jail’s base in out/jail, the three files bound in (bzImage and initramfs.cpio read-only, disk.img read-write), the three limits, and wick’s own arguments after --:

systemd-run --user --scope -p Delegate=yes --quiet -- "$JAILER" \
  --id ch26 --exec-file "$WICK" --uid 1000 --gid 1000 --chroot-base out/jail \
  --bind-ro out/bzImage:/bzImage --bind-ro out/initramfs.cpio:/initramfs.cpio --bind-rw out/disk.img:/disk.img \
  --cgroup memory.max=268435456 --cgroup pids.max=64 --cgroup 'cpu.max=50000 100000' \
  -- --api-sock /run/api.sock --id ch26

Then it drives the API with wick ctl against out/jail/wick/ch26/root/run/api.sock, with the paths as the jail sees them (/bzImage, /disk.img, the vsock’s uds_path /run/v.sock), and starts the machine. While the guest waits for the host (the script blocks on labs/waitline.sh out/console.txt 'vsock: listening' 30, which has a real deadline), it finds the wick process, the one process in the jail’s cgroup whose name is wick, and prints what the host reads from /proc/PID/status and the cgroup’s files. Then vsock-connect sends the guest a line and the guest finishes. The probe closes the run: the same jail around wick --probe-seccomp, whose two lines end the capture.

The capture:

=== boot jail
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /drives/vda 204
ctl: PUT /vsock 204
ctl: PUT /actions 204
=== lab begin
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
blk: capacity 16 sectors
blk: write verified
vsock: listening
vsock: guest got "release"
=== lab end
host: OK
host: got "ack release"
host: sector 1 written by guest
jail: NSpid depth 2
jail: CapEff 0000000000000000
jail: NoNewPrivs 1
jail: Seccomp 2
jail: cgroup pids.max 64
jail: cgroup memory.max 268435456
jail: cgroup cpu.max 50000 100000
jailer: cgroup memory.max=268435456
jailer: cgroup pids.max=64
jailer: cgroup cpu.max=50000 100000
jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: virtio-mmio slot 1 type 19
wick: vcpu 0 exit Shutdown
wick: exit 0
jailer: child exited 0
jailer rc=0
=== probe
jailer: child killed by signal 31
probe rc=159

The jail: lines are the point of the lab, read from the host side while the VMM runs, and none of them is a pid or a uid of the host. NSpid depth 2: the process has two pids, the host’s and the one it has in its pid namespace (1); one namespace below the host’s. CapEff 0000000000000000: its effective capability set is empty, after the exec of a non-root uid (chapter 15). NoNewPrivs 1: the bit the jailer set. Seccomp 2: filter mode, which wick set when InstanceStart arrived (chapter 15: 0 is off, 1 strict, 2 a filter). The three cgroup lines are the limits as the kernel holds them, read back from the files the jailer wrote, from the host’s view of the jail’s cgroup. The jailer: lines are the jailer’s own account: the limits it wrote, the root’s names after the pivot, how its child ended. The wick: lines are chapter 25’s, with the block device in slot 0 and the vsock in slot 1. The probe’s two lines are the filter’s: the child was killed by signal 31, and the jailer’s exit, 159.

Timings, 2026-10-02, with wick, the kernel and the helpers already built: make lab CH=26 on talos took 567 to 598 ms on three warm runs, and on straylight, inside the Nix shell, 777 to 904 ms (the shell’s own clock around the command; it includes the two jails, the guest’s boot, the facts and the probe). tools/remote-lab.sh lab CH=26 there adds the rsync and the round trip. The capture is byte-identical in four runs on each host, and between the hosts.

IMPL=mine replaces the body of seccomp::install, between its mine:begin and mine:end lines, by eprintln!("MINE: seccomp stub"); Ok(()): the VMM then installs nothing. The diff of capture.txt against that run:

--- capture.txt
+++ out/run.txt
@@ -17,7 +17,7 @@
 jail: NSpid depth 2
 jail: CapEff 0000000000000000
 jail: NoNewPrivs 1
-jail: Seccomp 2
+jail: Seccomp 0
 jail: cgroup pids.max 64
 jail: cgroup memory.max 268435456
 jail: cgroup cpu.max 50000 100000
@@ -25,6 +25,7 @@
 jailer: cgroup pids.max=64
 jailer: cgroup cpu.max=50000 100000
 jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
+MINE: seccomp stub
 wick: KVM API version 12
 wick: memory 128 MiB
 wick: boot protocol 64-bit entry
@@ -36,5 +37,7 @@
 jailer: child exited 0
 jailer rc=0
 === probe
-jailer: child killed by signal 31
-probe rc=159
+probe: getppid returned
+MINE: seccomp stub
+jailer: child exited 0
+probe rc=0

The three differences are the filter’s. jail: Seccomp 0: no filter. The MINE: line, in the boot and in the probe. And the probe: the call that is off the list returns, probe: getppid returned, the jailer’s child exits 0 and probe rc=0. jail: NoNewPrivs 1 does not change, which is the jailer’s doing, as the Mechanism section said; a reader who expects the stub to make it 0 has the order of the two programs wrong.

The unit tests of the pure parts and the integration tests are make -C wick test, which also runs everything earlier chapters wrote; and make -C wick clippy. The tests that start a guest through InstanceStart (tests/api.rs, tests/restart.rs) run the wick binary, with the filter on, and one of them (tests/seccomp.rs) reads Seccomp: of each of its threads and finds 2 on wick, wick_api and wick_vcpu0, and 0 with --no-seccomp. Two kinds of test do not run with it. tests/boot.rs drives spawn_vcpu from the test process and never calls InstanceStart, so it has no install point; and the_exit_waits_for_a_reply_that_is_being_written needs two statics of the library (WRITE_DELAY_MS and RESPONSES_WRITTEN), which a separate process does not share. Both are in-process by nature, and no test needs --no-seccomp to pass: the flag is the control in the tests that show what the filter changes, the probe’s and the jailer’s.

The root form, straylight, 2026-10-02

labs/ch26/root-form.sh is the jailer as Firecracker’s is run, as root, and is never part of make. It makes a network namespace hp26 with tap0 in it (chapter 25’s address, 172.16.0.1/24, the TAP owned by uid 30026), runs wick-jailer --netns /run/netns/hp26 --uid 30026 --gid 30026 in a scope of its own, boots the same guest with a network interface and chapter 25’s net: check, prints the same facts and three more lines (the uid, the network namespace and the base check), and removes the namespace, the scope’s cgroups and the jail on every way out of the script. It refuses to run unless it is root, and touches only labs/ch26/out/, root-form.txt, /run/netns/hp26 and the one scope. The run, on straylight, 2026-10-02, with doas labs/ch26/root-form.sh (once, after the tree was built with tools/remote-lab.sh -C labs/ch26 build; the file is labs/ch26/root-form.txt):

# the jailer's root form: host straylight, 2026-10-02, doas labs/ch26/root-form.sh
ctl: PUT /machine-config 204
ctl: PUT /boot-source 204
ctl: PUT /drives/vda 204
ctl: PUT /network-interfaces/eth0 204
ctl: PUT /vsock 204
ctl: PUT /actions 204
=== lab begin
blk: sector 0: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
blk: capacity 16 sectors
blk: write verified
net: 1 packets transmitted, 1 packets received, 0% packet loss
vsock: listening
vsock: guest got "release"
=== lab end
host: OK
host: got "ack release"
host: sector 1 written by guest
jail: base check refused
jail: NSpid depth 2
jail: CapEff 0000000000000000
jail: NoNewPrivs 1
jail: Seccomp 2
jail: Uid 30026
jail: network namespace is hp26
jail: cgroup pids.max 64
jail: cgroup memory.max 268435456
jail: cgroup cpu.max 50000 100000
jailer: cgroup memory.max=268435456
jailer: cgroup pids.max=64
jailer: cgroup cpu.max=50000 100000
jailer: root: bzImage dev disk.img initramfs.cpio proc run wick
wick: KVM API version 12
wick: memory 128 MiB
wick: boot protocol 64-bit entry
wick: InstanceStart
wick: virtio-mmio slot 0 type 2
wick: virtio-mmio slot 1 type 1
wick: virtio-mmio slot 2 type 19
wick: vcpu 0 exit Shutdown
wick: exit 0
jailer: child exited 0
jailer rc=0

The differences from the unprivileged capture are the point. jail: Uid 30026 is the host’s own view of the VMM’s uid, a real one: the uid is 30026 in the host’s ids and not a mapping of the invoking user’s. jail: base check refused is a run before the main one: the same jailer, given a base that group may write, refuses it (“must be owned by root and not writable by group or others”) and makes nothing in it. jail: network namespace is hp26 compares the namespace of the running wick with the file hp26 is held by, and says they are the same: the VMM found tap0 there and the guest’s ping reached it (net: 1 packets transmitted, 1 packets received), which the unprivileged jail cannot do. CapEff is zero because setresuid from root to a non-root uid takes the capabilities with it; NoNewPrivs and Seccomp are as before. wick: virtio-mmio slot 1 type 1 is the net device, in the slot after the disk. Everything else is the same, down to the root’s listing, and the capture’s jailer: child exited 0.

Further reading

results matching ""

    No results matching ""