15. What Linux actually is from here
Why this layer exists
wick and ward run on Linux. Chapter 24 boots a Linux kernel as the guest of wick. The KVM hosts are x86_64, so that chapter reuses this chapter’s pins and the shape of its build script (a cached tree, a BusyBox initramfs) for an x86_64 guest, with a tinyconfig kernel where this chapter uses defconfig; the riscv64 Image built here boots under QEMU. Chapter 26’s jailer is made of the objects this chapter reads. A reader who has written a kernel with nine syscalls and has to put a second, much larger kernel in the trusted computing base of the second floor should know what that kernel’s isolation is made of, and know it from its source, not from a container tutorial.
Linux’s riscv64 syscall table is 472 entries long (__NR_syscalls), the number chapter 13 took from this host’s headers; here it comes with its source. It has the same three axes chapter 14 defined and a great deal more machinery on each. Five of its objects are the ones wick’s host stands on: the syscall table, namespaces, cgroups, capabilities and seccomp. The chapter reads each in the kernel source at tag v7.2.8 while the kernel runs in QEMU next to the tree, and reads a line the running kernel prints for each. You do not implement any of them. The lab is a probe: a shell script, a BusyBox initramfs and a short C program that asks the kernel five questions, and the capture pins its answers.
Mechanism
Every quoted block below is headed with its file and line range at v7.2.8, copied from the pinned checkout the build fetched, not retyped. The kernel is configured by riscv64 defconfig and built with the cross toolchain make doctor checks; labs/ch15/build.sh records the pins.
The syscall table, grown up
Chapter 13’s table is a switch on a7 in ember/syscall.c. Linux’s has the same shape with more around it. The first is how a user ecall reaches C. The trap vector saves the frame and indexes a table of handlers by scause; cause 8, an ecall from U mode, is the ninth entry:
// linux v7.2.8, arch/riscv/kernel/entry.S:485-494
SYM_DATA_START_LOCAL(excp_vect_table)
RISCV_PTR do_trap_insn_misaligned
ALT_INSN_FAULT(RISCV_PTR do_trap_insn_fault)
RISCV_PTR do_trap_insn_illegal
RISCV_PTR do_trap_break
RISCV_PTR do_trap_load_misaligned
RISCV_PTR do_trap_load_fault
RISCV_PTR do_trap_store_misaligned
RISCV_PTR do_trap_store_fault
RISCV_PTR do_trap_ecall_u /* system call */
The handler is the function that chapter 13’s syscall() grew into:
// linux v7.2.8, arch/riscv/kernel/traps.c:324-345
asmlinkage __visible __trap_section __no_stack_protector
void do_trap_ecall_u(struct pt_regs *regs)
{
if (user_mode(regs)) {
long syscall = regs->a7;
regs->epc += 4;
regs->orig_a0 = regs->a0;
regs->a0 = -ENOSYS;
riscv_v_vstate_discard(regs);
syscall = syscall_enter_from_user_mode(regs, syscall);
add_random_kstack_offset();
if (syscall >= 0 && syscall < NR_syscalls) {
syscall = array_index_nospec(syscall, NR_syscalls);
syscall_handler(regs, syscall);
}
syscall_exit_to_user_mode(regs);
The moves are ember’s: step epc over the ecall (ember does it at the end of syscall(), tf->sepc += 4), take the number from a7, store -ENOSYS in a0 as the answer to a number that is not in the table, and dispatch. Two things are new. The bound is NR_syscalls, and the index is passed through array_index_nospec so that a mispredicted branch cannot speculatively index past the table. And syscall_enter_from_user_mode runs before the dispatch. It is the one place where everything that wants to veto or observe a syscall gets its turn: ptrace stops there and seccomp runs there (the seccomp section follows the call down). The table’s size is a constant in the generic header:
// linux v7.2.8, include/uapi/asm-generic/unistd.h:866-867
#undef __NR_syscalls
#define __NR_syscalls 472
472 is the table’s length, the last number plus one. On chapter 14’s axes this is the copy, the boundary every byte crosses at the same door, now with a hook on the way in.
PID 1 and /proc
The probe runs as a child of PID 1. The kernel runs whatever rdinit= names as the first user process, and /init in the initramfs is a shell script, so /proc/1/comm is init, the basename of the file the kernel execed. /proc is a file system the kernel synthesizes: reading /proc/self/status calls a function that prints the fields of the running task’s kernel structures into a buffer. The lines the probe keeps come from two helpers in fs/proc/array.c. The capability masks are printed by render_cap_t through task_cap; the seccomp state by task_seccomp:
// linux v7.2.8, fs/proc/array.c:302-308
static void render_cap_t(struct seq_file *m, const char *header,
kernel_cap_t *a)
{
seq_puts(m, header);
seq_put_hex_ll(m, NULL, a->val, 16);
seq_putc(m, '\n');
}
// linux v7.2.8, fs/proc/array.c:325-329
render_cap_t(m, "CapInh:\t", &cap_inheritable);
render_cap_t(m, "CapPrm:\t", &cap_permitted);
render_cap_t(m, "CapEff:\t", &cap_effective);
render_cap_t(m, "CapBnd:\t", &cap_bset);
render_cap_t(m, "CapAmb:\t", &cap_ambient);
// linux v7.2.8, fs/proc/array.c:332-336
static inline void task_seccomp(struct seq_file *m, struct task_struct *p)
{
seq_put_decimal_ull(m, "NoNewPrivs:\t", task_no_new_privs(p));
#ifdef CONFIG_SECCOMP
seq_put_decimal_ull(m, "\nSeccomp:\t", p->seccomp.mode);
The \t in each header is why the capture has real tab characters after the colons. Seccomp_filters: follows on the next lines; the probe’s regex, anchored with the colon directly after Seccomp, does not match it. /proc is not an isolation mechanism. It is the observation window onto the four that are, and on chapter 14’s axes it adds no boundary: it is a read-only window through which a program sees the kernel’s state.
Namespaces
A namespace wraps one global resource of the kernel, such as the set of process ids, the mount table or the network stack, so that the processes inside see their own instance of it (the wording is namespaces(7)’s). A task’s view of most of these hangs off one pointer, task->nsproxy:
// linux v7.2.8, include/linux/nsproxy.h:32-41
struct nsproxy {
refcount_t count;
struct uts_namespace *uts_ns;
struct ipc_namespace *ipc_ns;
struct mnt_namespace *mnt_ns;
struct pid_namespace *pid_ns_for_children;
struct net *net_ns;
struct time_namespace *time_ns;
struct time_namespace *time_ns_for_children;
struct cgroup_namespace *cgroup_ns;
Two entries are the namespaces that the task’s future children will be born into, pid_ns_for_children and time_ns_for_children, and they differ from the task’s own once someone has asked for a new one. For pid, the task’s own namespace is reached through task_active_pid_ns (which fs/proc/root.c calls below), not through this struct. The user namespace, which owns the others, is not here either; it is in the task’s credentials, which is where the capability section looks.
The probe lists /proc/self/ns, which fs/proc/namespaces.c generates from a table gated by the CONFIG_*_NS symbols that defconfig turns on (all =y, below):
// linux v7.2.8, fs/proc/namespaces.c:15-40
static const struct proc_ns_operations *const ns_entries[] = {
#ifdef CONFIG_NET_NS
&netns_operations,
#endif
#ifdef CONFIG_UTS_NS
&utsns_operations,
#endif
#ifdef CONFIG_IPC_NS
&ipcns_operations,
#endif
#ifdef CONFIG_PID_NS
&pidns_operations,
&pidns_for_children_operations,
#endif
#ifdef CONFIG_USER_NS
&userns_operations,
#endif
&mntns_operations,
#ifdef CONFIG_CGROUPS
&cgroupns_operations,
#endif
#ifdef CONFIG_TIME_NS
&timens_operations,
&timens_for_children_operations,
#endif
};
The probe’s output, cgroup ipc mnt net pid pid_for_children time time_for_children user uts, is that table in alphabetical order, because ls sorts. The table has ten rows, pid and time each contributing two (the task’s own and the one its children will get), so the list has ten names from eight mechanisms: net, uts, ipc, pid, user, mnt, cgroup and time.
A namespace is born in one of two places: clone(2), through copy_namespaces when a task is created, or unshare(2), through unshare_nsproxy_namespaces when a task changes its own set. Both call create_new_namespaces, which builds a new nsproxy. The probe’s pid namespace comes from the second. The unshare path checks CAP_SYS_ADMIN in the relevant user namespace (the new one if the same call also asks for CLONE_NEWUSER) and calls create_new_namespaces:
// linux v7.2.8, kernel/nsproxy.c:211-235
int unshare_nsproxy_namespaces(unsigned long unshare_flags,
struct nsproxy **new_nsp, struct cred *new_cred, struct fs_struct *new_fs)
{
struct user_namespace *user_ns;
u64 flags = unshare_flags;
int err = 0;
if (!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))
return 0;
user_ns = new_cred ? new_cred->user_ns : current_user_ns();
if (!ns_capable(user_ns, CAP_SYS_ADMIN))
return -EPERM;
/*
* Convert the 32-bit UNSHARE_EMPTY_MNTNS (which aliases
* CLONE_PARENT_SETTID) to the unique 64-bit CLONE_EMPTY_MNTNS.
*/
if (flags & UNSHARE_EMPTY_MNTNS) {
flags &= ~(u64)UNSHARE_EMPTY_MNTNS;
flags |= CLONE_EMPTY_MNTNS;
}
*new_nsp = create_new_namespaces(flags, current, user_ns,
new_fs ? new_fs : current->fs);
and create_new_namespaces is where the pid namespace for the task’s future children is made:
// linux v7.2.8, kernel/nsproxy.c:118-119
new_nsp->pid_ns_for_children =
copy_pid_ns(flags, user_ns, tsk->nsproxy->pid_ns_for_children);
The clone path is the one every ordinary fork takes. copy_namespaces reads the user namespace from the new task’s credentials; if the clone flags ask for none of the namespace-creating flags it takes another reference on the parent’s nsproxy and returns, which creates nothing, and otherwise it checks CAP_SYS_ADMIN in that user namespace (the new task’s, which is the new one under CLONE_NEWUSER) before building a new set:
// linux v7.2.8, kernel/nsproxy.c:169-181
int copy_namespaces(u64 flags, struct task_struct *tsk)
{
struct nsproxy *old_ns = tsk->nsproxy;
struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
struct nsproxy *new_ns;
if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
if ((flags & CLONE_VM) ||
likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
get_nsproxy(old_ns);
return 0;
}
} else if (!ns_capable(user_ns, CAP_SYS_ADMIN))
The probe’s child sh takes the fast path: it is forked with no namespace flags, and inherits the nsproxy that unshare already replaced in its parent.
The probe’s unshare -f -p --mount-proc sh -c … needs three facts from the source. unshare(2) with CLONE_NEWPID does not move the caller: in the manual’s words the calling process “is not moved into the new namespace”, and “the first child created by the calling process will have the process ID 1”. That is why the probe passes -f: BusyBox’s unshare calls unshare(2) (util-linux/unshare.c:305 at BusyBox 1_38_0) and then, because of -f, creates a child with xvfork (line 336; BusyBox’s checked vfork, include/libbb.h:1377) before it runs sh, so the sh is the first child. The place that the child’s number is decided is fork, which allocates a pid from the parent’s pid_ns_for_children, not from its own namespace:
// linux v7.2.8, kernel/fork.c:2306-2307
if (pid != &init_struct_pid) {
pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
and the allocation loop walks the namespace chain and insists that the first pid handed out in a new namespace is 1:
// linux v7.2.8, kernel/pid.c:300-305
* PID 1 (init) must be created first.
*/
if (!READ_ONCE(tmp->child_reaper) && nr != 1) {
retval = -EINVAL;
goto out_free;
}
So pid inside: 1 is the answer to the question “what number did alloc_pid give the first process in a namespace”, and it is fixed by that check, not by an accident of timing. The third fact explains processes visible inside: 1. /proc lists the pids of one pid namespace, the one its mounter was in, fixed at mount time:
// linux v7.2.8, fs/proc/root.c:341-353
static int proc_init_fs_context(struct fs_context *fc)
{
struct proc_fs_context *ctx;
ctx = kzalloc_obj(struct proc_fs_context);
if (!ctx)
return -ENOMEM;
ctx->pid_ns = get_pid_ns(task_active_pid_ns(current));
put_user_ns(fc->user_ns);
fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
fc->fs_private = ctx;
fc->ops = &proc_fs_context_ops;
--mount-proc is the flag that mounts a fresh /proc inside the child, after the child is in the new namespace, so task_active_pid_ns(current) is the new one and /proc/[0-9]* has one entry, the shell. Without the flag the glob would count the host namespace’s pids, a number that depends on how many kernel threads the boot started (Exercise (b) runs it), and the capture would move. The probe counts with the shell’s glob so that nothing forks inside the namespace (an ls would be a second process, and the count would be two).
A namespace is a change to what is shared and nothing else: the kernel, the syscall table and the address-space machinery are unchanged, and what differs is which instance of a named resource a name reaches. Every bug in the kernel still crosses the boundary; isolation by namespace is a statement about naming, not about who is trusted.
Control groups
A cgroup is a node in a tree of process groups to which the kernel attaches controllers: per-resource accounting and limits, such as memory, cpu time, or the number of processes. Version 2 has a single tree, mounted by the mount -t cgroup2 in /init. The file cgroup.controllers at its root lists the controllers that the tree offers; the probe prints it, and the answer is cpuset cpu io memory hugetlb pids.
The read is cgroup_controllers_show, which prints a mask of controllers from cgroup_control:
// linux v7.2.8, kernel/cgroup/cgroup.c:465-482
static u32 cgroup_control(struct cgroup *cgrp)
{
struct cgroup *parent = cgroup_parent(cgrp);
u32 root_ss_mask = cgrp->root->subsys_mask;
if (parent) {
u32 ss_mask = parent->subtree_control;
/* threaded cgroups can only have threaded controllers */
if (cgroup_is_threaded(cgrp))
ss_mask &= cgrp_dfl_threaded_ss_mask;
return ss_mask;
}
if (cgroup_on_dfl(cgrp))
root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
cgrp_dfl_implicit_ss_mask);
return root_ss_mask;
At the root of the default (v2) hierarchy the mask is everything the kernel was built with, minus two sets: cgrp_dfl_inhibit_ss_mask and cgrp_dfl_implicit_ss_mask. The controllers a kernel is built with are a list gated by config symbols, in a header included under a macro that turns each entry into an array slot:
// linux v7.2.8, include/linux/cgroup_subsys.h:12-30
#if IS_ENABLED(CONFIG_CPUSETS)
SUBSYS(cpuset)
#endif
#if IS_ENABLED(CONFIG_CGROUP_SCHED)
SUBSYS(cpu)
#endif
#if IS_ENABLED(CONFIG_CGROUP_CPUACCT)
SUBSYS(cpuacct)
#endif
#if IS_ENABLED(CONFIG_BLK_CGROUP)
SUBSYS(io)
#endif
#if IS_ENABLED(CONFIG_MEMCG)
SUBSYS(memory)
#endif
The output order is this list’s order. Six of the twelve controllers in this .config appear; the other six are removed by the two masks, and the loop that fills them is where the reason lives:
// linux v7.2.8, kernel/cgroup/cgroup.c:6509-6512
if (ss->implicit_on_dfl)
cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
else if (!ss->dfl_cftypes)
cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
A controller that has no files for the default hierarchy (dfl_cftypes is null) is inhibited there. The probe’s missing names are each that case: cpuacct (kernel/sched/cpuacct.c, which sets only .legacy_cftypes), devices (security/device_cgroup.c, the same), freezer (kernel/cgroup/legacy_freezer.c), net_cls (net/core/netclassid_cgroup.c) and net_prio (net/core/netprio_cgroup.c). A controller marked implicit_on_dfl is also not listed, because it is always on and not something to enable: perf_event (kernel/events/core.c, which sets .implicit_on_dfl = true). That accounts for all six: twelve of the sixteen symbols in the header are =y in this .config (CGROUP_MISC, RDMA, DMEM and DEBUG are not), and six of the twelve reach the file. memory, cpu and pids are controllers that bound how much of the machine a group of processes can use. On chapter 14’s axes a cgroup is none of the three; it is a fourth thing, a budget on use: it bounds how much of the machine a program can consume and says nothing about what it can touch.
Capabilities
A capability, in the POSIX sense Linux implements, is one named piece of the superuser’s power (CAP_SYS_ADMIN, CAP_NET_RAW, …) that a task holds or does not. It is unrelated to seL4’s kind, which is a reference to an object; the word has two meanings and the book uses each in its own chapter. Each task’s credentials (struct cred) carry several sets of them as 64-bit masks. CapEff is the effective set, the one that permission checks consult.
CapEff: 000001ffffffffff is 41 one-bits. The bit count comes from the number of the last capability, and the mask from CAP_VALID_MASK:
// linux v7.2.8, include/uapi/linux/capability.h:421-423
#define CAP_CHECKPOINT_RESTORE 40
#define CAP_LAST_CAP CAP_CHECKPOINT_RESTORE
// linux v7.2.8, include/linux/capability.h:64-67
#define CAP_VALID_MASK (BIT_ULL(CAP_LAST_CAP+1)-1)
# define CAP_EMPTY_SET ((kernel_cap_t) { 0 })
# define CAP_FULL_SET ((kernel_cap_t) { CAP_VALID_MASK })
CAP_LAST_CAP is 40, BIT_ULL(41) - 1 is , which is 0x1ffffffffff, and render_cap_t (above) prints it in sixteen hex digits, which gives the two leading zeros the probe shows. Init has all of them because the kernel’s first task is born with the full set:
// linux v7.2.8, init/init_task.c:90-94
.securebits = SECUREBITS_DEFAULT,
.cap_inheritable = CAP_EMPTY_SET,
.cap_permitted = CAP_FULL_SET,
.cap_effective = CAP_FULL_SET,
.cap_bset = CAP_FULL_SET,
and every process the initramfs runs is a descendant that is root (uid 0) and inherits them: handle_privileged_root in security/commoncap.c is the step at execve that gives a root process its capability sets (Exercise (a) shows a case where it gives none). The check that uses the masks is cap_capable, and its helper cap_capable_helper walks up the user namespaces from the resource’s to the credential’s:
// linux v7.2.8, security/commoncap.c:68-106
static inline int cap_capable_helper(const struct cred *cred,
struct user_namespace *target_ns,
const struct user_namespace *cred_ns,
int cap)
{
struct user_namespace *ns = target_ns;
/* See if cred has the capability in the target user namespace
* by examining the target user namespace and all of the target
* user namespace's parents.
*/
for (;;) {
/* Do we have the necessary capabilities? */
if (likely(ns == cred_ns))
return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
/*
* If we're already at a lower level than we're looking for,
* we're done searching.
*/
if (ns->level <= cred_ns->level)
return -EPERM;
/*
* The owner of the user namespace in the parent of the
* user namespace has all caps.
*/
if ((ns->parent == cred_ns) && uid_eq(ns->owner, cred->euid))
return 0;
/*
* If you have a capability in a parent user ns, then you have
* it over all children user namespaces as well.
*/
ns = ns->parent;
}
/* We never get here */
}
The test is per namespace: a task holds a capability over a user namespace and, by the last branch, over its descendants. That is why capabilities granted in a new user namespace are worth nothing against the host; Exercise (a) runs unshare -U and shows the sets a process ends with. A capability is a change to who is trusted: it divides root into parts so that a program can be handed fewer of them, which is the direction a jailer moves in.
Seccomp
Seccomp (“secure computing”) is a per-task mode that restricts which syscalls the task may make. The mode is stored in the task (p->seccomp.mode, the Seccomp: line); the probe prints 0, meaning disabled, for the shell, and then the C program turns on the simplest mode, strict, which is one prctl away. prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT) reaches prctl_set_seccomp, which translates the mode into an operation for do_seccomp, which calls seccomp_set_mode_strict, which assigns the mode:
// linux v7.2.8, kernel/seccomp.c:1428-1441
static long seccomp_set_mode_strict(void)
{
const unsigned long seccomp_mode = SECCOMP_MODE_STRICT;
long ret = -EINVAL;
spin_lock_irq(¤t->sighand->siglock);
if (!seccomp_may_assign_mode(seccomp_mode))
goto out;
#ifdef TIF_NOTSC
disable_TSC();
#endif
seccomp_assign_mode(current, seccomp_mode, 0);
seccomp_assign_mode also sets the task’s SYSCALL_WORK_SECCOMP flag, and the check is on the syscall path the trap handler called: syscall_enter_from_user_mode calls syscall_enter_from_user_mode_work, which calls syscall_trace_enter when any entry-work flag is set, and that function calls __secure_computing when this one is:
// linux v7.2.8, include/linux/entry-common.h:104-109
/* Do seccomp after ptrace, to catch any tracer changes. */
if (work & SYSCALL_WORK_SECCOMP) {
ret = __secure_computing();
if (ret == -1L)
return ret;
}
On riscv64 HAVE_ARCH_SECCOMP_FILTER is selected (arch/riscv/Kconfig), so the function that runs is the second of the two __secure_computing definitions in kernel/seccomp.c, the one that switches on the mode:
// linux v7.2.8, kernel/seccomp.c:1388-1413
int __secure_computing(void)
{
int mode = current->seccomp.mode;
int this_syscall;
if (IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) &&
unlikely(current->ptrace & PT_SUSPEND_SECCOMP))
return 0;
this_syscall = syscall_get_nr(current, current_pt_regs());
switch (mode) {
case SECCOMP_MODE_STRICT:
__secure_computing_strict(this_syscall); /* may call do_exit */
return 0;
case SECCOMP_MODE_FILTER:
return __seccomp_filter(this_syscall, false);
/* Surviving SECCOMP_RET_KILL_* must be proactively impossible. */
case SECCOMP_MODE_DEAD:
WARN_ON_ONCE(1);
do_exit(SIGKILL);
return -1;
default:
BUG();
}
}
Strict mode’s whole policy is one table and one function:
// linux v7.2.8, kernel/seccomp.c:1051-1065
/*
* Secure computing mode 1 allows only read/write/exit/sigreturn.
* To be fully secure this must be combined with rlimit
* to limit the stack allocations too.
*/
static const int mode1_syscalls[] = {
__NR_seccomp_read, __NR_seccomp_write, __NR_seccomp_exit, __NR_seccomp_sigreturn,
#ifdef __NR_uretprobe
__NR_uretprobe,
#endif
#ifdef __NR_uprobe
__NR_uprobe,
#endif
-1, /* negative terminated */
};
// linux v7.2.8, kernel/seccomp.c:1067-1085
static void __secure_computing_strict(int this_syscall)
{
const int *allowed_syscalls = mode1_syscalls;
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
allowed_syscalls = get_compat_mode1_syscalls();
#endif
do {
if (*allowed_syscalls == this_syscall)
return;
} while (*++allowed_syscalls != -1);
#ifdef SECCOMP_DEBUG
dump_stack();
#endif
current->seccomp.mode = SECCOMP_MODE_DEAD;
seccomp_log(this_syscall, SIGKILL, SECCOMP_RET_KILL_THREAD, true);
do_exit(SIGKILL);
}
The table has read, write, exit and rt_sigreturn (__NR_seccomp_* in include/asm-generic/seccomp.h map to __NR_read, __NR_write, __NR_exit and __NR_rt_sigreturn, which are 63, 64, 93 and 139 in include/uapi/asm-generic/unistd.h), and, where the architecture defines them, uretprobe and uprobe. getpid is 172, is not in the table, and the loop falls out of the do … while into the tail: the task’s mode is set to dead, the attempt is logged, and do_exit(SIGKILL) runs, in the task’s own context, before the syscall’s handler is ever called. The process is killed by signal 9; BusyBox’s shell prints Killed and reports 128 + 9 = 137, the two lines the capture pins after strict mode on. The program’s last write never runs.
Seccomp is a change to who is trusted, by shrinking the interface: the kernel’s TCB is unchanged, but the set of doors into it that this task can reach is four. Filter mode, which the jailer uses, replaces the table with a program; Exercise (d) reads where.
The configuration and the build’s identity
defconfig is the kernel’s own statement of what it is. The config symbols the probe depends on are these, read from the .config that make defconfig wrote for this tag, and every one is =y:
CONFIG_CGROUPS=y
CONFIG_NAMESPACES=y
CONFIG_UTS_NS=y
CONFIG_IPC_NS=y
CONFIG_USER_NS=y
CONFIG_PID_NS=y
CONFIG_NET_NS=y
CONFIG_BLK_DEV_INITRD=y
CONFIG_SECCOMP=y
CONFIG_SECCOMP_FILTER=y
CONFIG_DEVTMPFS=y
CONFIG_DEVTMPFS_MOUNT=y
CONFIG_VIRTIO_BLK=y
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_POWER_RESET_SYSCON=y
CONFIG_POWER_RESET_SYSCON_POWEROFF=y
CONFIG_VIRTIO_MMIO=y
Nothing had to be enabled on top of defconfig; the only edit build.sh makes to the kernel’s configuration is to disable CONFIG_LOCALVERSION_AUTO, which scripts/setlocalversion could otherwise extend on a shallow clone with a + or -g suffix, so that uname -r is exactly 7.2.8. The first sixteen hex digits of the SHA-256 of the final .config are 4f23a572ce2f5876 on straylight; build.sh writes them to out/config.sha. The hash covers every line of the file, including the compiler’s own version string: CONFIG_CC_VERSION_TEXT and CONFIG_GCC_VERSION are in .config, so a different toolchain gives a different hash, and talos, whose cross compiler is GCC 16.2.1 against straylight’s 16.2.0, wrote 7fcf186d9ad26d19 for the same tag and the same CONFIG_ answers. The hash is the identity of this build, not of the tag: the tag says which source, the CONFIG_ lines above say which question the source was asked, and the hash says which compiler built the answer. The capture is identical on both hosts.
Walkthrough
Nothing here quotes the kernel again; the kernel blocks are in Mechanism. These three listings are ours.
/init
# PID 1. Mount the three kernel views a probe needs, run the probe
# between two sentinels the lab's capture is cut at, then power off:
# the kernel's own log lines carry timestamps and never enter the
# capture.
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null
mkdir -p /sys/fs/cgroup
mount -t cgroup2 none /sys/fs/cgroup
# Only emergencies reach the console from here: a kernel line landing
# between the sentinels would make the capture depend on timing.
dmesg -n 1
echo '=== probe begin'
/probe
echo "=== probe end rc=$?"
poweroff -f
PID 1 mounts three views of the kernel before anything else can be asked: /proc for the per-task files, /sys for the device and cgroup trees, and devtmpfs on /dev, which the kernel populates by itself. CONFIG_DEVTMPFS_MOUNT does not apply to an initramfs (its help text in drivers/base/Kconfig says the file system always has to be mounted by hand after the rootfs is), so /init mounts it; the probe never reads /dev, and the 2>/dev/null only keeps a failed mount’s message off the console. cgroup2 goes on /sys/fs/cgroup, which is what makes cgroup.controllers exist. dmesg -n 1 sets the console log level so that only emergencies print, because a kernel message that lands between the sentinels would make the capture depend on timing. Then the two sentinels bracket the probe, and the closing one carries the probe’s exit status. poweroff -f powers the machine off at once, without signalling init, which is this script. The virt machine has a power-off device (OpenSBI’s boot banner names syscon-poweroff as the platform shutdown device), the console shows reboot: Power down, and QEMU exits on its own without the timeout firing.
/probe
# Every line here is a fact about the running kernel that the chapter
# reads in the source. Nothing prints a timestamp, an address or a pid
# from outside the new namespace (those depend on how many kernel
# threads started first). Inside unshare, the count uses the shell's
# glob and forks nothing, so the answer is the shell alone.
echo "kernel $(uname -r)"
echo "pid1 $(cat /proc/1/comm)"
grep -E '^(CapEff|Seccomp|NoNewPrivs):' /proc/self/status
echo namespaces $(ls /proc/self/ns)
echo "cgroup controllers: $(cat /sys/fs/cgroup/cgroup.controllers)"
if [ "${$}" -ne 1 ]; then echo 'pid outside: not 1'; fi
unshare -f -p --mount-proc sh -c 'echo "pid inside: ${$}"; set -- /proc/[0-9]*; echo "processes visible inside: $#"'
echo "seccomp strict, then a forbidden syscall:"
/seccomp-probe
echo "seccomp-probe rc=$?"
Each line asks one question of one kernel object. uname -r is the version the build pinned. /proc/1/comm names PID 1. The grep picks three fields of proc_pid_status for the probe’s own process. /proc/self/ns lists the namespace files of the process; cgroup.controllers lists the controllers of the root cgroup. The if line is the outside view of pid numbering: the probe is init’s child, so ${$} (the shell’s own pid, spelled so the book’s math markup leaves it alone) is not 1 and the line prints pid outside: not 1, the counterpart of pid inside: 1, and unlike the pid itself the sentence does not depend on how many kernel threads started before the probe. The unshare line is the namespace experiment, and the set -- and $# count the entries /proc/[0-9]* expands to without forking. The last two lines run the C program and print its exit status.
seccomp.c
/* Enter seccomp strict mode — read, write, _exit and sigreturn are the
* whole syscall table from here — then call one that is not on it. The
* kernel answers with SIGKILL; the shell reports 137. Chapter 15 reads
* the check in kernel/seccomp.c. */
#include <stdio.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <linux/seccomp.h>
int main(void)
{
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0) != 0) {
perror("prctl");
return 2;
}
write(1, "strict mode on\n", 15);
getpid(); /* not read, write, _exit or sigreturn */
write(1, "still alive (no seccomp?)\n", 26);
return 0;
}
The program checks the prctl call, writes one line, makes the forbidden call, and would write a second line if it survived. The first write is allowed, so the capture has strict mode on; the getpid call is not, so the second write never runs and the string still alive never appears. getpid() on riscv64 is a real ecall, which the run shows by the program dying. The write’s return value is ignored, the compiler says so when the program is built, and the warning is correct and harmless: a program whose next instruction might be its own death has nowhere to put an error.
Exercises
(a) Predict CapEff for a process that runs unshare -U (a new user namespace), then run it in the guest and answer with the value observed and the kernel’s reason.
Answer
Observed on talos, from a scratch copy of probe.sh with unshare -U sh -c 'grep -E "^Cap(Prm|Eff|Bnd):" /proc/self/status; id -u' appended, rebuilt and booted: CapPrm: 0000000000000000, CapEff: 0000000000000000, CapBnd: 000001ffffffffff, and id -u prints 65534. The prediction that a new user namespace gives a process every capability is half right, and the half that is wrong is the interesting one. set_cred_user_ns in kernel/user_namespace.c does give the task the full set when the namespace is created:
// linux v7.2.8, kernel/user_namespace.c:44-53
static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
{
/* Start with the same capabilities as init but useless for doing
* anything as the capabilities are bound to the new user namespace.
*/
cred->securebits = SECUREBITS_DEFAULT;
cred->cap_inheritable = CAP_EMPTY_SET;
cred->cap_permitted = CAP_FULL_SET;
cred->cap_effective = CAP_FULL_SET;
cred->cap_ambient = CAP_EMPTY_SET;
but the shell is then execed, and at execve the capability sets are recomputed. cap_bprm_creds_from_file in security/commoncap.c (line 935) computes root_uid = make_kuid(new->user_ns, 0) and passes it to handle_privileged_root, which grants the root sets only if the process’s uid is that uid. In a new user namespace with no uid map, make_kuid calls map_id_down, which returns (u32) -1 for an id that is not mapped (kernel/user_namespace.c, map_id_range_down), so there is no root in the namespace for the process to be, CapPrm and CapEff come out as zero, and id -u shows the overflow uid 65534. The bounding set is untouched. With a mapping of root (unshare -U -r; the map is 0 0 1) the same probe prints CapPrm, CapEff and CapBnd all 000001ffffffffff and uid 0. What the new namespace’s capabilities are worth is the last branch of cap_capable_helper: they are held over the new namespace and its descendants, not over the namespaces above it.
(b) Drop --mount-proc from the probe’s unshare line. What do the two lines print, and why does only one of them change? Cite fs/proc/root.c.
Answer
Observed on talos, from a scratch copy of probe.sh with a copy of the unshare line appended, --mount-proc removed and its two echoes relabelled no mount-proc: pid inside and no mount-proc: visible, rebuilt and booted: no mount-proc: pid inside 1 and no mount-proc: visible 47. The pid does not change, because the flag has nothing to do with allocation: Mechanism’s alloc_pid still hands the first child of the new namespace pid 1. The count changes because /proc is still the mount /init made, and proc_init_fs_context in fs/proc/root.c fixed that mount’s namespace to task_active_pid_ns(current) of its mounter, the host’s. The glob lists the host’s processes and kernel threads, a count of this boot that the probe therefore never prints.
(c) Which cgroup.controllers entry would disappear if CONFIG_MEMCG were off? Cite the table.
Answer
memory. In include/linux/cgroup_subsys.h the line SUBSYS(memory) is inside #if IS_ENABLED(CONFIG_MEMCG) (lines 28 to 30 at the tag), and the cgroup_subsys[] array in kernel/cgroup/cgroup.c is built by including that header, so with the symbol off the slot does not exist, the controller is not in the mask that cgroup_control returns, and the word does not print. The other five are gated by other symbols: cpuset by CONFIG_CPUSETS, cpu by CONFIG_CGROUP_SCHED, io by CONFIG_BLK_CGROUP, hugetlb by CONFIG_CGROUP_HUGETLB and pids by CONFIG_CGROUP_PIDS.
(d) Replace SECCOMP_MODE_STRICT with a filter. What does SECCOMP_MODE_FILTER need that strict does not, and where does the kernel run it?
Answer
A BPF program, passed in by the caller, and one of two things about the caller’s privilege. The program is what strict mode’s fixed table is replaced with. The privilege rule is in kernel/seccomp.c:
// linux v7.2.8, kernel/seccomp.c:684-693
/*
* Installing a seccomp filter requires that the task has
* CAP_SYS_ADMIN in its namespace or be running with no_new_privs.
* This avoids scenarios where unprivileged tasks can affect the
* behavior of privileged children.
*/
if (!task_no_new_privs(current) &&
!ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))
return ERR_PTR(-EACCES);
A task installs a filter only if it has set no_new_privs (so that a program it later runs cannot gain privilege through the filter) or holds CAP_SYS_ADMIN in its user namespace. The kernel runs the program at the same point strict mode’s check runs: __secure_computing’s SECCOMP_MODE_FILTER case calls __seccomp_filter, which calls seccomp_run_filters, and that evaluates every attached filter with bpf_prog_run_pin_on_cpu and keeps the lowest action:
// linux v7.2.8, kernel/seccomp.c:404-430
static u32 seccomp_run_filters(const struct seccomp_data *sd,
struct seccomp_filter **match)
{
u32 ret = SECCOMP_RET_ALLOW;
/* Make sure cross-thread synced filter points somewhere sane. */
struct seccomp_filter *f =
READ_ONCE(current->seccomp.filter);
/* Ensure unexpected behavior doesn't result in failing open. */
if (WARN_ON(f == NULL))
return SECCOMP_RET_KILL_PROCESS;
if (seccomp_cache_check_allow(f, sd))
return SECCOMP_RET_ALLOW;
/*
* All filters in the list are evaluated and the lowest BPF return
* value always takes priority (ignoring the DATA).
*/
for (; f; f = f->prev) {
u32 cur_ret = bpf_prog_run_pin_on_cpu(f->prog, sd);
if (ACTION_ONLY(cur_ret) < ACTION_ONLY(ret)) {
ret = cur_ret;
*match = f;
}
}
so the decision is an integer the program returns (allow, errno, trap, kill), not always a signal. The verdict is reached before the syscall’s handler runs, as in strict mode.
(e) Which of the five objects has ember an analogue of, and which has it none of? Use chapter 14’s axes.
Answer
The syscall table, namespaces and capabilities have analogues; cgroups and seccomp have none. The table is chapter 13’s switch on a7 in ember/syscall.c, the same door with nine entries and no hook before it. A namespace is a per-task table of names that reach objects; ember’s is the descriptor table, ofile[NOFILE] in ember/proc.h, which maps a small integer to an entry in the kernel-wide open-file table (ember/fd.h): two processes that both hold descriptor 1 are not naming the same thing unless the kernel put them there, which is the shared axis (what a name reaches) made per-process. The capability analogue is the same table read differently: a descriptor is the only way a program names a pipe end, and the readable and writable bits in struct file are rights bound when it is created, which chapter 14’s exercise (c) already used for exokernel secure binding; it is the closest ember has to seL4’s capabilities and a long way from POSIX’s, which divide root. It has no analogue of a cgroup, because nothing in it accounts for or bounds a process’s use of anything except the fixed NOFILE and NFILE tables, and no analogue of seccomp, because all nine syscalls are open to every process: syscall() in ember/syscall.c has no per-task filter before its switch. Procfs, the window rather than one of the five, has no analogue either: none of the nine syscalls reports the kernel’s own state to a program.
(f) Which of the five does the jailer of chapter 26 use on wick? Answer from the syllabus alone.
Answer
SYLLABUS.md’s entry for chapter 26 reads “Namespaces, cgroups, pivot_root, drop uid, seccomp on the VMM.” Three of the five are named outright: namespaces, cgroups and seccomp. “Drop uid” is the fourth, the credential and capability object: a process that gives up root loses the capability sets that CapEff shows. The syscall table is not chosen by the jailer; it is the boundary the other objects guard, and seccomp narrows it. Procfs is not one of the five and is not used as a mechanism: the jailer only needs the mount in its namespace to be correct. The entry also says where the five apply: to the VMM process, not to the guest. The jailer does not reach into the guest kernel, which runs as a virtual machine; everything the five do is about wick, the process on the host.
Lab
make lab CH=15
make lab CH=15 IMPL=mine
labs/ch15/build.sh fetches Linux v7.2.8 from https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git and BusyBox 1_38_0 from https://git.busybox.net/busybox, each a shallow clone of one tag, into ${XDG_CACHE_HOME:-$HOME/.cache}/hp/ch15/, outside the tree. A clean clone of the book does not rebuild them and rm -rf _build does not remove them. It runs defconfig, builds Image for riscv64, builds BusyBox static with CONFIG_TC off (its tc.c needs CBQ definitions that the toolchain’s kernel headers do not have), installs it into an initramfs tree, adds /init, /probe and the static seccomp-probe, and packs the tree with cpio and gzip. The cross prefix is whichever of riscv64-linux-gnu- and riscv64-unknown-linux-gnu- is installed, the two spellings of the same toolchain that make doctor accepts. Only out/Image and out/initramfs.cpio.gz leave the cache. out/Image is a riscv64 kernel that boots under QEMU here; it is not chapter 24’s guest (the opening of this chapter says why).
Timings, measured: on straylight (32 cores) on 2026-09-30, the first run took 4 min 3 s wall, including the copy of the tree, the clone of both trees and the kernel’s configuration and build, and ended where BusyBox’s build stopped at tc.c (the reason for CONFIG_TC off); a complete cold rebuild with CONFIG_TC off, on 2026-10-01, took 302 s wall including the rsync and the boot; the run that then built BusyBox, the initramfs and booted took 22 s; a run with a warm cache (build.sh skips the builds and repacks) takes about 10 s. On talos (8 cores), the first run took 18 min 4 s wall for the clone, both builds and the boot (BusyBox and the kernel both built there).
The boot is qemu-system-riscv64 -machine virt -m 512M -smp 1 -nographic -monitor none -kernel out/Image -initrd out/initramfs.cpio.gz -append 'console=ttyS0 rdinit=/init'. There is no -bios none: that is ember’s rule. Here OpenSBI, QEMU’s default firmware, runs in M mode and hands the kernel to S mode. That is this boot only. A RISC-V guest under KVM runs no M-mode firmware: the host kernel answers its SBI calls itself, in arch/riscv/kvm/vcpu_sbi.c and its neighbours. Chapter 24’s x86_64 guest has no M mode to begin with.
The capture is the probe’s lines between === probe begin and === probe end, cut out of the console with sed and stripped of carriage returns. The kernel’s own boot log, with timestamps and addresses, is in out/console.txt and is not pinned: a timestamp moves on every boot, and a capture of it would fail on a cold cache. Two runs on straylight were byte-identical. The capture holds three lines with a tab character after the colon, because that is what the kernel prints; a diff that complains about those lines has had its tabs replaced.
IMPL=mine rebuilds the initramfs from mine/ against the same kernel. The reader’s copy has the seccomp program stubbed to print MINE: seccomp probe stub and exit 1: the boot and every line before it match, and the diff is the three lines after seccomp strict, then a forbidden syscall:.
Further reading
- Control Group v2 (Linux kernel documentation) — the authoritative description of the hierarchy, the controllers and the default-hierarchy rules that
cgroup_controlimplements. - Seccomp BPF (SECure COMPuting with filters) (Linux kernel documentation) — filter mode, the return actions and
no_new_privs, for Exercise (d). - namespaces(7) (Linux man-pages) — the namespace types and what each wraps.
- capabilities(7) (Linux man-pages) — the sets, the
execvetransformation, and the user-namespace rules Exercise (a) runs into. - unshare(2) (Linux man-pages) — why
CLONE_NEWPIDmoves the children and not the caller. - The kernel source at
v7.2.8— every file quoted above, at the tag the build fetches.