knaxuslearn · build · ship

Projects / Container runtime / Phase 2

Phase 2 of 4 · about 2.5 hours

A root file system of its own

You end with commands that run inside a small, separate file system, with working /proc, /dev and /tmp, and nothing of the host visible.

Step 2.1: What goes into a root file system (about 40 minutes)

A root file system is just a directory tree that looks like / to the programs inside. A program needs very little from it: its own file, the shared libraries it was linked against, and whatever it opens at run time. So we can build a tiny one by copying a handful of programs from the host together with their libraries.

The tool for finding the libraries is ldd, which lists what a program needs. We copy each file to the same path under a new directory, with cp --parents. The script below does that for a list of programs, then for every test program in a tools folder (we add some in Phase 3), and finally writes a minimal /etc/passwd and /etc/group so that id can print names:

# Build a small root file system from programs of the host. Usage: sh mkrootfs.sh DIR
set -e
ROOT=${1:-rootfs}
rm -rf "$ROOT"
mkdir -p "$ROOT/proc" "$ROOT/dev" "$ROOT/tmp" "$ROOT/etc" "$ROOT/root" "$ROOT/usr/bin"

# Copy every shared library that a program needs to the same path inside ROOT.
copy_libs() {
    ldd "$1" 2>/dev/null | grep -o '/[^ ]*' | while read -r lib; do
        cp -L --parents "$lib" "$ROOT"
    done
}

# Copy a program of the host, and its libraries.
copy_program() {
    path=$(which "$1")
    cp -L --parents "$path" "$ROOT"
    copy_libs "$path"
}

for prog in sh ls cat ps id hostname mount mkdir rm touch head tail wc sleep env true false grep cut; do
    copy_program "$prog"
done

# Small test programs from the tools folder, if there are any.
for src in tools/*.c; do
    [ -e "$src" ] || continue
    name=$(basename "$src" .c)
    gcc -O2 -o "$ROOT/usr/bin/$name" "$src"
    copy_libs "$ROOT/usr/bin/$name"
done

echo "root:x:0:0:root:/root:/bin/sh" > "$ROOT/etc/passwd"
echo "root:x:0:" > "$ROOT/etc/group"
echo "built $ROOT: $(du -sh "$ROOT" | cut -f1)"
  • copy_libs reads the output of ldd, picks out every absolute path, and copies it. The dynamic loader, ld-linux, shows up in that list too. Without it nothing would start.
  • copy_program finds a program with which and copies it, so the script works on systems that keep programs in /bin, /usr/bin or elsewhere.
  • The tools loop does nothing yet, because the folder does not exist. It saves us from changing this script in later phases.

Run it and look at the result:

sh mkrootfs.sh rootfs
ls rootfs
built rootfs: 8.5M
dev
etc
lib
lib64
proc
root
tmp
usr

About 8 MB, and it holds a shell, ls, ps, mount and a few others. A real image has a package manager's worth of files, but the idea is the same: a directory tree you can point to.

If you would rather not depend on the host's libraries, a statically linked program such as BusyBox needs no libraries at all, and a root file system for it is a single file.

Step 2.2: Enter it with pivot_root (about 45 minutes)

Now let's make the child see that directory as /. Phase 2 changes the runtime in a few places. First, the list of headers grows, and rt now gets a struct that carries the root directory and the command:

#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <unistd.h>
struct run {
    const char *rootfs;
    char **cmd;
};

The function that switches roots:

/* Make `root` the root of our view of the file system, and forget the old one. */
static void enter_rootfs(const char *root) {
    /* pivot_root wants the new root to be a mount point, so bind it onto itself. */
    if (mount(root, root, NULL, MS_BIND | MS_REC, NULL) < 0) die("bind rootfs");
    if (chdir(root) < 0) die("chdir rootfs");
    /* Putting the old root "under" the new one at the same place, then detaching it. */
    if (syscall(SYS_pivot_root, ".", ".") < 0) die("pivot_root");
    if (umount2(".", MNT_DETACH) < 0) die("detach old root");
    if (chdir("/") < 0) die("chdir /");
}

You may know chroot, which also changes what / means. It is not enough for us. A process that keeps enough rights can walk out of a chroot, and the old file system stays mounted behind it. pivot_root works on mounts instead: it makes a new directory the root of the whole mount namespace. Here is what each line does:

Think it through: why does the old file system stay reachable after chroot but not after pivot_root and umount2? Look at what each call changes: a path lookup, or the mounts themselves.

  1. pivot_root requires the new root to be a mount point, and a plain directory is not one. So we bind mount the directory onto itself. That turns it into a mount point without copying anything. (pivot_root also refuses a mount that has the shared propagation type, which is one more reason for the private mounts we set up first.)
  2. We chdir into it. pivot_root is a raw system call that the C library does not wrap, so we call it through syscall.
  3. pivot_root(".", ".") is a trick the manual page documents: it puts the old root on top of the new one at the same place, so no extra directory is needed to park it.
  4. umount2(".", MNT_DETACH) then unmounts that old root. After this the host's file system has no name in our namespace at all.
  5. A last chdir("/") moves us into the new root.

Pitfall: if pivot_root fails, check two things: the bind mount must run before it, and the mounts must be private, because pivot_root refuses a shared one.

Step 2.3: /proc, /dev and /tmp (about 35 minutes)

An empty root has no /dev, and programs expect a few devices there. We mount a small RAM-backed file system called tmpfs on /dev and create three device files with mknod. The numbers are the pairs that Linux has always used: 1,3 for null, 1,5 for zero and 1,9 for urandom.

static void make_device(const char *path, int major_no, int minor_no) {
    if (mknod(path, S_IFCHR | 0666, makedev(major_no, minor_no)) < 0) die(path);
}

/* A private /dev with the few devices every program expects. */
static void mount_dev(void) {
    if (mount("tmpfs", "/dev", "tmpfs", MS_NOSUID | MS_STRICTATIME, "mode=755,size=64k") < 0)
        die("mount /dev");
    make_device("/dev/null", 1, 3);
    make_device("/dev/zero", 1, 5);
    make_device("/dev/urandom", 1, 9);
}

Then child_main puts the pieces in order. The order matters: private mounts first, then the new root, then /proc, /dev and /tmp inside it.

/* This function runs inside the new namespaces. It is process number 1 there. */
static int child_main(void *arg) {
    struct run *r = arg;

    if (sethostname("box", 3) < 0) die("sethostname");

    /* Stop our mounts from leaking out to the host. */
    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) die("make mounts private");

    enter_rootfs(r->rootfs);
    if (mount("proc", "/proc", "proc", 0, NULL) < 0) die("mount /proc");
    mount_dev();
    if (mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV, "size=16m") < 0) die("mount /tmp");

    setenv("PATH", "/usr/bin:/bin:/usr/sbin:/sbin", 1);
    execvp(r->cmd[0], r->cmd);
    die(r->cmd[0]);
    return 1;
}

We also set PATH, because a program that starts with no environment would not find ls or ps. The /tmp is a tmpfs as well: whatever the command writes there disappears with the container, and size=16m keeps it from eating the memory of the host. main changes only a little. It now takes the root directory as its first argument:

int main(int argc, char **argv) {
    if (argc < 4 || strcmp(argv[1], "run") != 0) {
        fprintf(stderr, "usage: %s run ROOTFS COMMAND [ARGS...]\n", argv[0]);
        return 2;
    }
    struct run r = {.rootfs = argv[2], .cmd = &argv[3]};

    char *stack = malloc(STACK_SIZE);
    if (!stack) die("malloc");

    int flags = CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD;
    pid_t pid = clone(child_main, stack + STACK_SIZE, flags, &r);
    if (pid < 0) die("clone (are you root?)");

    int status;
    if (waitpid(pid, &status, 0) < 0) die("waitpid");
    return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}

Step 2.4: Run it, and see what is still wrong (about 30 minutes)

Build and try it:

sh build.sh
sudo ./rt run rootfs ls /
sudo ./rt run rootfs ls /home
dev
etc
lib
lib64
proc
root
tmp
usr
ls: cannot access '/home': No such file or directory
exit status 2

The container sees its own directories only, and the host's /home does not exist for it. Let's check the other promises:

sudo ./rt run rootfs sh -c 'echo hi > /tmp/a; cat /tmp/a; ls /dev'
hi
null
urandom
zero

If a command in the container fails with "not found", the program is probably missing from the root file system. Add its name to the list in mkrootfs.sh and build the directory again.

Now the part that still needs fixing. We are still root inside, and we still have every one of root's powers:

sudo ./rt run rootfs grep Cap /proc/self/status
sudo ./rt run rootfs sh -c 'mkdir /tmp/x && mount -t tmpfs none /tmp/x && echo "mounted a new file system"'
CapInh:	0000000000000000
CapPrm:	000001fffeffffff
CapEff:	000001fffeffffff
CapBnd:	000001fffeffffff
CapAmb:	0000000000000000
mounted a new file system

Those Cap lines are hexadecimal masks of the process's capabilities. Nearly every bit is set. (On our test machine one bit is missing, so you may see all f digits where we have an e.) A program in this container can mount file systems, change the network, load kernel code on some systems and more. Isolation of the view is not enough, so Phase 3 takes the powers away.