Linux Containers by Hand. Part 8: Writing a container runtime in C
All parts of the series “Linux Containers by Hand”We have been working down the stack. In Part 1, containerd and runc started the container. In Part 2, we wrote config.json for runc by hand. Then we took the tools away and worked through namespaces and the root in Part 3, image layers in Part 4, cgroups in Part 5, networking in Part 6, and privileges in Part 7. Each command turned out to wrap a few system calls. Today we will put those calls into one C program, minirun, a small runtime that performs the core work of runc using only libc.
The complete code is about 400 lines. We will walk through it piece by piece. minirun.c
Lab setup
| Item | Value |
|---|---|
| Machine | lincont-lab.example.com, Hyper-V VM |
| OS | Ubuntu Server 26.04.1, kernel 7.0.0, cgroup v2 |
| Compiler | gcc 15.2.0 |
| Image | docker.io/library/alpine:3.24, root extracted with nerdctl export |
Run all commands as root (sudo -i). Install the compiler and headers, build the program, and prepare the root.
apt-get install -y gcc libc6-dev
mkdir -p /srv/c8
cd /srv/c8
curl -sSLO https://raw.githubusercontent.com/vitaliy-leschenko/linux-containers-by-hand/main/08-minirun/minirun.c
curl -sSLO https://raw.githubusercontent.com/vitaliy-leschenko/linux-containers-by-hand/main/06-network/connect.sh
chmod +x connect.sh
gcc -O2 -Wall -o minirun minirun.c
img=docker.io/library/alpine:3.24
mkdir rootfs
id=$(nerdctl create $img)
nerdctl export $id | tar -C rootfs -xf -
nerdctl rm $id > /dev/null
How the program works
minirun takes a root directory, a command, a hostname (-n), limits for memory, CPU, and process count (-m, -c, -p), a networking hook (-H), and an option to create a user namespace (-U). Two processes share the work.
parent: minirun child
─────────────── ─────
cgroup and limits
clone(CLONE_NEW*) ──────────────────► waits on the pipe
uid_map and gid_map (-U) │
PID into cgroup.procs │
network hook (-H) │
closes the pipe ────────────────────► unshare(CLONE_NEWCGROUP)
waitpid() sethostname(), lo
│ mount(): root, /proc, /sys, /dev
│ pivot_root(".", ".")
│ PR_CAPBSET_DROP, no_new_privs
│ seccomp()
│ execve(command)
▼
exit status, rmdir cgroup
Some setup requires the child’s PID, which the parent learns only after clone(). The child waits while the parent writes the ID mappings, moves it into the cgroup, and configures the network. Then it prepares the root and runs the command. runc also uses a rendezvous. In Part 2 we saw runc init wait on exec.fifo.
clone() and the pipe
int flags = CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWNET | SIGCHLD;
if (c.userns)
flags |= CLONE_NEWUSER;
pid_t pid = clone(child, stack + STACK_SIZE, flags, &c);
clone() creates a process directly in the new namespaces. In Part 3, creating a pid namespace with unshare() required --fork. The child starts in the child function on a stack allocated with mmap(). The stack grows downward, so we pass its upper end. SIGCHLD tells the kernel to notify the parent when the child exits, as it would after fork().
The pipe created with pipe2() is the signal to proceed. The child reads from it, and the parent simply closes its end without writing. read() returns 0 in the child, which then continues.
close(c->sync[1]);
if (read(c->sync[0], &buf, 1) < 0)
die("sync");
The child creates its own cgroup namespace with unshare() after the parent moves it into the group. That makes the group appear to the child as /, as in Part 5.
The root filesystem
setup_root() repeats Part 3 using system calls.
// nothing we mount may leak to the host
do_mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
// pivot_root() needs the new root to be a mount point
do_mount(r, r, NULL, MS_BIND | MS_REC, NULL);
First, it makes mount propagation private everywhere so our mounts stay off the host. The unshare command did this for us by default. Then it bind-mounts the root directory over itself.
The code mounts /proc, read-only /sys, and the cgroup2 filesystem at /sys/fs/cgroup so the container can see its limits. /dev is a tmpfs. Here we bind-mount the host’s device nodes. With a user namespace, creating new devices with mknod() is forbidden but mounting existing ones works, so this code serves both modes.
The root and /proc/sys are then remounted read-only. The remount needs one detail.
struct statvfs sv;
if (statvfs(p, &sv) < 0)
die(p);
unsigned long keep = sv.f_flag & (ST_NOSUID | ST_NODEV | ST_NOEXEC | ST_NOATIME |
ST_NODIRATIME | ST_RELATIME);
do_mount(NULL, p, NULL, MS_REMOUNT | MS_BIND | MS_RDONLY | keep, NULL);
A remount replaces the flags as a set. In a user namespace, the kernel rejects attempts to remove locked flags inherited from the host mount. Read the existing flags with statvfs() and pass them back in. The relevant values are the same in statvfs() and mount().
Switch roots using the runc technique from Part 3.
if (chdir(r) < 0)
die(r);
if (syscall(SYS_pivot_root, ".", ".") < 0)
die("pivot_root");
if (umount2(".", MNT_DETACH) < 0)
die("umount old root");
libc has no wrapper for pivot_root(), so call it by number through syscall().
Privileges
Capabilities
for (int cap = 0; cap <= last; cap++) {
int kept = 0;
for (size_t i = 0; i < sizeof keep / sizeof keep[0]; i++)
kept |= keep[i] == cap;
if (!kept && prctl(PR_CAPBSET_DROP, cap, 0, 0, 0) < 0)
die("PR_CAPBSET_DROP");
}
Keep the three capabilities from runc spec: CAP_KILL, CAP_NET_BIND_SERVICE, and CAP_AUDIT_WRITE. Drop the others from the bounding set. In this setup, when a UID 0 process runs a program with execve(), the kernel gives the program permitted and effective sets equal to that bounding set. Read the highest capability number from /proc/sys/kernel/cap_last_cap, since the running kernel can know about capabilities newer than the headers.
The seccomp filter
In Part 7, runc used libseccomp to build the filter from JSON. Without it, write the filter directly in classic BPF, the instruction set of a small virtual machine in the kernel. The program reads the architecture and system call number from seccomp_data and returns a decision.
#define DENY(nr) \
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, (nr), 0, 1), \
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA))
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 0x40000000, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
DENY(__NR_mount),
DENY(__NR_umount2),
DENY(__NR_pivot_root),
DENY(__NR_unshare),
DENY(__NR_setns),
...
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
- The first three instructions load the architecture and kill the process if it is outside x86-64. System call numbers vary by architecture, so check the architecture first.
- The next two kill a process that sets bit
0x40000000in its system call number. These are x32 calls for the ABI that uses 32-bit pointers on a 64-bit processor. Their numbering could otherwise bypass the deny list. - Each
DENYexpands to two instructions. A matching number returnsEPERM. Other numbers proceed to the next check. The filter denies calls that change mounts or namespaces, pluskeyctl,ptrace,kexec_load, andbpf. - The remaining calls are allowed.
Set PR_SET_NO_NEW_PRIVS before installing the filter. The kernel requires it for a process without CAP_SYS_ADMIN, because otherwise the process could run a setuid program under conditions it does not expect. We set it in both modes, as runc does. Install the filter last, just before execve(), since our setup code needs mount().
The parent process
The parent creates /sys/fs/cgroup/lab/minirun-<PID> and writes memory.max, memory.swap.max, cpu.max, and pids.max as in Part 5. After clone() it writes the child’s PID to cgroup.procs. With -U it also writes uid_map and gid_map under /proc/<PID>/, mapping IDs 0–65535 inside to a range starting at 100000 outside. The child can then become root in its namespace with setgroups(), setgid(0), and setuid(0).
The parent runs the hook with sh -c and supplies the container PID as $1. This follows the idea behind CNI in Part 1. The runtime calls an external program to set up networking. We will use connect.sh from Part 6, downloaded next to minirun.
When the command finishes, the parent prints its exit status or signal. If it was killed, the parent also prints the group’s oom_kill counter. Then it removes the group.
Run the container
Inside the container
./minirun rootfs sh -c 'hostname; echo $$; ps; cat /proc/mounts; grep -E "^(CapEff|NoNewPrivs|Seccomp)" /proc/self/status; cat /proc/self/cgroup; ip a; touch /x'
box
1
PID USER TIME COMMAND
1 root 0:00 sh -c hostname; echo $$; ps; cat /proc/mounts; grep -E "^(CapEff|NoNewPrivs|Seccomp)" /proc/self/status; cat /proc/self/cgroup; ip a; touch /x
3 root 0:00 ps
/dev/sda2 / ext4 ro,relatime 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
sysfs /sys sysfs ro,nosuid,nodev,noexec,relatime 0 0
cgroup2 /sys/fs/cgroup cgroup2 ro,nosuid,nodev,noexec,relatime,nsdelegate,memory_recursiveprot,memory_hugetlb_accounting 0 0
tmpfs /dev tmpfs rw,nosuid,relatime,size=64k,mode=755,inode64 0 0
devtmpfs /dev/null devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devtmpfs /dev/zero devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devtmpfs /dev/full devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devtmpfs /dev/random devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devtmpfs /dev/urandom devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devtmpfs /dev/tty devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,mode=620,ptmxmode=666 0 0
shm /dev/shm tmpfs rw,nosuid,nodev,relatime,inode64 0 0
devtmpfs /proc/kcore devtmpfs rw,nosuid,size=2639912k,nr_inodes=659978,mode=755,inode64 0 0
proc /proc/sys proc ro,nosuid,nodev,noexec,relatime 0 0
CapEff: 0000000020000420
NoNewPrivs: 1
Seccomp: 2
Seccomp_filters: 1
0::/
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
touch: /x: Read-only file system
minirun: exit code 1
The pieces we built throughout the series are in place: a separate hostname, PID 1, a read-only root, /proc/kcore masked by the host’s /dev/null (the devtmpfs source is the host’s /dev), three capabilities, no_new_privs, a seccomp filter, a cgroup, and an active lo.
Trace the system calls
strace with -f shows calls from both processes. Keep the relevant calls and omit the failed execve() attempts from libc’s search along PATH.
strace -f -qq -s 64 -e trace=clone,clone3,unshare,sethostname,mount,pivot_root,umount2,prctl,seccomp,execve -e signal=none -o /tmp/c8.trace ./minirun rootfs true
grep -v ENOENT /tmp/c8.trace
rm /tmp/c8.trace
6789 execve("./minirun", ["./minirun", "rootfs", "true"], 0x7fff0c3ac190 /* 16 vars */) = 0
6789 clone(child_stack=0x766ddcfffff0, flags=CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWPID|CLONE_NEWNET|SIGCHLD) = 6790
6790 unshare(CLONE_NEWCGROUP) = 0
6790 sethostname("box", 3) = 0
6790 mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) = 0
6790 mount("/srv/c8/rootfs", "/srv/c8/rootfs", NULL, MS_BIND|MS_REC, NULL) = 0
6790 mount("proc", "/srv/c8/rootfs/proc", "proc", MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL) = 0
6790 mount("sysfs", "/srv/c8/rootfs/sys", "sysfs", MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL) = 0
6790 mount("cgroup2", "/srv/c8/rootfs/sys/fs/cgroup", "cgroup2", MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC, NULL) = 0
6790 mount("tmpfs", "/srv/c8/rootfs/dev", "tmpfs", MS_NOSUID, "mode=755,size=64k") = 0
6790 mount("/dev/null", "/srv/c8/rootfs/dev/null", NULL, MS_BIND, NULL) = 0
6790 mount("/dev/zero", "/srv/c8/rootfs/dev/zero", NULL, MS_BIND, NULL) = 0
6790 mount("/dev/full", "/srv/c8/rootfs/dev/full", NULL, MS_BIND, NULL) = 0
6790 mount("/dev/random", "/srv/c8/rootfs/dev/random", NULL, MS_BIND, NULL) = 0
6790 mount("/dev/urandom", "/srv/c8/rootfs/dev/urandom", NULL, MS_BIND, NULL) = 0
6790 mount("/dev/tty", "/srv/c8/rootfs/dev/tty", NULL, MS_BIND, NULL) = 0
6790 mount("devpts", "/srv/c8/rootfs/dev/pts", "devpts", MS_NOSUID|MS_NOEXEC, "newinstance,ptmxmode=0666,mode=0620") = 0
6790 mount("shm", "/srv/c8/rootfs/dev/shm", "tmpfs", MS_NOSUID|MS_NODEV, "mode=1777") = 0
6790 mount("/srv/c8/rootfs/dev/null", "/srv/c8/rootfs/proc/kcore", NULL, MS_BIND, NULL) = 0
6790 mount("/srv/c8/rootfs/proc/sys", "/srv/c8/rootfs/proc/sys", NULL, MS_BIND, NULL) = 0
6790 mount(NULL, "/srv/c8/rootfs/proc/sys", NULL, MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_REMOUNT|MS_BIND, NULL) = 0
6790 mount(NULL, "/srv/c8/rootfs", NULL, MS_RDONLY|MS_REMOUNT|MS_BIND, NULL) = 0
6790 pivot_root(".", ".") = 0
6790 umount2(".", MNT_DETACH) = 0
6790 prctl(PR_CAPBSET_DROP, CAP_CHOWN) = 0
6790 prctl(PR_CAPBSET_DROP, CAP_DAC_OVERRIDE) = 0
6790 prctl(PR_CAPBSET_DROP, CAP_DAC_READ_SEARCH) = 0
...
6790 prctl(PR_CAPBSET_DROP, CAP_BPF) = 0
6790 prctl(PR_CAPBSET_DROP, CAP_CHECKPOINT_RESTORE) = 0
6790 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) = 0
6790 seccomp(SECCOMP_SET_MODE_FILTER, 0, {len=29, filter=0x766ddcfffee0}) = 0
6790 execve("/bin/true", ["true"], 0x7fff4fc2ee58 /* 16 vars */) = 0
That is the container setup: two namespace calls, 18 mounts, a root switch, 38 prctl() calls to drop capabilities, then the flag and the filter. The trace omits the middle of the capability list. The /proc/sys remount retained nosuid, nodev, and noexec from statvfs(). The filter took 29 BPF instructions.
Exercise the limits
./minirun -m 64M rootfs sh -c 'cat /sys/fs/cgroup/memory.max; x=aaaaaaaaaaaaaaaa; while :; do x=$x$x; done'
./minirun -p 10 rootfs sh -c 'cat /sys/fs/cgroup/pids.max; for i in $(seq 20); do sleep 5 & done; wait'
./minirun -c 0.5 rootfs sh -c 'cat /sys/fs/cgroup/cpu.max; timeout 3 sh -c "while :; do :; done"; grep -E "usage_usec|nr_throttled" /sys/fs/cgroup/cpu.stat'
67108864
minirun: killed by signal 9, oom_kill 1
10
sh: can't fork: Resource temporarily unavailable
minirun: exit code 2
50000 100000
Terminated
usage_usec 1547291
nr_throttled 30
minirun: exit code 0
The container reads its limits at /sys/fs/cgroup, where the mount reflects its own cgroup namespace. The kernel killed a process that ran out of memory. fork() failed at the process limit. Over three seconds, the CPU loop got about 1.5 seconds of CPU time and waited for the next quota period 30 times.
Check what is blocked
./minirun rootfs sh -c 'mount -t tmpfs t /tmp; unshare -U true; hostname other; chown 1 /dev/shm; cat /proc/kcore | wc -c; echo 1 > /proc/sys/kernel/ostype; echo done'
mount: permission denied (are you root?)
unshare: unshare(0x10000000): Operation not permitted
hostname: sethostname: Operation not permitted
chown: /dev/shm: Operation not permitted
0
sh: can't create /proc/sys/kernel/ostype: Read-only file system
done
minirun: exit code 0
Both capabilities and seccomp block mount and unshare. Capabilities also block hostname and chown. /proc/kcore is empty and /proc/sys is read-only.
Set up networking with the hook
Attach the container to the bridge with connect.sh from Part 6 and try ping.
./minirun -H './connect.sh $1 8' rootfs sh -c 'ip -4 a show eth0; ip route; cat /proc/sys/net/ipv4/ping_group_range; ping -c 1 1.1.1.1'
6827: eth0 10.6.0.8/24, gateway 10.6.0.1
2: eth0@if19: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP qlen 1000
inet 10.6.0.8/24 scope global eth0
valid_lft forever preferred_lft forever
default via 10.6.0.1 dev eth0
10.6.0.0/24 dev eth0 scope link src 10.6.0.8
1 0
PING 1.1.1.1 (1.1.1.1): 56 data bytes
ping: permission denied (are you root?)
minirun: exit code 1
The network is up, but ping fails. A traditional ping uses a raw ICMP socket, which requires CAP_NET_RAW. We dropped it. Linux also supports ICMP datagram sockets for groups listed in net.ipv4.ping_group_range. Ubuntu allows them for all groups on the host, but this setting belongs to the network namespace and defaults to the empty range 1 0 in a new namespace. Have the same hook use nsenter to allow group 0 in the container’s network namespace. Docker sets a similar value for its containers.
./minirun -H './connect.sh $1 9 && nsenter -t $1 -n sysctl -qw net.ipv4.ping_group_range="0 0"' rootfs sh -c 'ping -c 1 1.1.1.1 | head -2'
./connect.sh --down
6874: eth0 10.6.0.9/24, gateway 10.6.0.1
PING 1.1.1.1 (1.1.1.1): 56 data bytes
64 bytes from 1.1.1.1: seq=0 ttl=42 time=8.986 ms
minirun: exit code 0
Use a user namespace
./minirun -U rootfs sh -c 'id; cat /proc/self/uid_map; ls -ln /etc/shadow; sleep 2' &
sleep 1
ps -o user,pid,cmd -C sleep
wait
uid=0(root) gid=0(root)
0 100000 65536
-rw-r----- 1 65534 65534 260 Nov 5 09:19 /etc/shadow
USER PID CMD
100000 6921 sleep 2
minirun: exit code 0
The process is root inside and UID 100000 on the host. Files owned by host root appear as 65534 because that host UID has no mapping. The process can still read the files it needs, and the root is mounted read-only.
From the host
./minirun -m 128M rootfs sleep 30 &
sleep 1
ps -o pid,ppid,cmd --forest -C minirun,sleep
ls -d /sys/fs/cgroup/lab/*/
cat /sys/fs/cgroup/lab/minirun-*/cgroup.procs /sys/fs/cgroup/lab/minirun-*/memory.max
p=$(pgrep -x sleep)
for n in cgroup ipc mnt net pid uts user; do
printf '%-6s host %-14s container %s\n' $n "$(readlink /proc/1/ns/$n | sed 's/.*://')" "$(readlink /proc/$p/ns/$n | sed 's/.*://')"
done
kill -KILL $p
wait
PID PPID CMD
6926 6740 ./minirun -m 128M rootfs sleep 30
6928 6926 \_ sleep 30
/sys/fs/cgroup/lab/minirun-6926/
6928
134217728
cgroup host [4026531835] container [4026532144]
ipc host [4026531839] container [4026532256]
mnt host [4026531832] container [4026532142]
net host [4026531833] container [4026532258]
pid host [4026531836] container [4026532257]
uts host [4026531838] container [4026532143]
user host [4026531837] container [4026531837]
minirun: killed by signal 9, oom_kill 0
As in Part 1, the container has six separate namespaces and a cgroup with a limit. minirun itself stays on as the parent, performing the job that the shim handles after runc exits.
minirun and runc
In config.json |
In minirun |
Part |
|---|---|---|
linux.namespaces |
clone() with CLONE_NEW* flags, unshare(CLONE_NEWCGROUP) |
3 |
root, mounts |
mount(), pivot_root(), umount2() |
3 |
hostname |
sethostname() |
3 |
maskedPaths, readonlyPaths |
Mount /dev/null and remount read-only |
3 |
linux.resources, cgroupsPath |
Files in /sys/fs/cgroup/lab/minirun-<PID> |
5 |
hooks |
-H |
6 |
process.capabilities |
prctl(PR_CAPBSET_DROP) |
7 |
process.noNewPrivileges |
prctl(PR_SET_NO_NEW_PRIVS) |
7 |
linux.seccomp |
seccomp() with a BPF program |
7 |
linux.uidMappings, gidMappings |
/proc/<PID>/uid_map and gid_map |
7 |
runc includes features that minirun leaves out: parsing config.json, a stateful create and start lifecycle, terminal handling, exec into running containers, protections against symlink attacks in the root, and seccomp filters for other architectures. That accounts for much of runc’s code. The container setup we saw in strace takes a few dozen system calls.
Clean up
cd /
rm -rf /srv/c8
nerdctl rmi $img > /dev/null
minirun removes its own cgroups. Keep gcc and the headers installed.
What we built
A Linux container is an ordinary process. Before running it, the runtime creates namespaces so it gets its own view of processes, networking, the hostname, and mounts. It switches to an image filesystem assembled from layers with OverlayFS, puts the process in a cgroup to account for and limit resources, and removes privileges it does not need. containerd, shims, CNI, and nerdctl add image storage, declarative networking, process supervision, and commands people can use.
References
- Creating namespaces. clone(2), unshare(2), and namespaces(7)
- Mounts and switching roots. mount(2), mount_namespaces(7), pivot_root(2), and statvfs(3)
PR_CAPBSET_DROPandPR_SET_NO_NEW_PRIVS. capabilities(7) and prctl(2)- Filters and the BPF program format. seccomp(2) and Seccomp BPF
uid_map,gid_map, and mount restrictions. user_namespaces(7)- ICMP sockets and
ping_group_range. icmp(7) - How runc implements these operations. libcontainer
This is the final part of the series.
Only registered users can leave a comment.
Sign in or register to leave a comment.