knaxuslearn · build · ship

Projects / Container runtime / Phase 3

Phase 3 of 4 · about 2.5 hours

Fewer rights, and limits

You end with a container whose root has only a handful of powers, that can never gain more, and that is stopped when it uses too much memory or CPU time.

Step 3.1: What "root" really means (about 30 minutes)

On Linux, root is not one big power. The kernel splits it into about 40 separate capabilities, and each system call checks for the one it needs. Changing the hostname or mounting a file system needs CAP_SYS_ADMIN. Configuring the network needs CAP_NET_ADMIN. Sending raw packets needs CAP_NET_RAW. Creating device files needs CAP_MKNOD. A process that has all of them is "root" in the old sense, and a process with a few is a much smaller thing.

For a container we want the smallest set that ordinary programs still work with. We keep six:

CapabilityWhat it allows
CAP_CHOWNchange the owner of a file
CAP_DAC_OVERRIDEignore file permission checks, which root inside the container needs to install and edit files
CAP_FOWNERact as the owner of any file, for example to change its mode
CAP_KILLsend signals to other processes
CAP_SETUID, CAP_SETGIDswitch to another user or group, as a server does when it drops to a normal user

Everything else is removed. A capability is removed from the bounding set, which is the upper limit of what a process can ever hold. Once something is dropped from the bounding set, no exec can bring it back, and every child inherits the smaller set. That is exactly the kind of one-way door we want.

Step 3.2: Drop the capabilities (about 40 minutes)

Here is the code. A short list of what we keep, and a loop over all the numbers the kernel knows:

/* The capabilities a container keeps. Everything else is removed for good. */
static const int KEEP_CAPS[] = {CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_FOWNER, CAP_KILL, CAP_SETGID, CAP_SETUID};

static int is_kept(int cap) {
    for (size_t i = 0; i < sizeof KEEP_CAPS / sizeof KEEP_CAPS[0]; i++) {
        if (KEEP_CAPS[i] == cap) return 1;
    }
    return 0;
}

static int last_cap(void) {
    FILE *f = fopen("/proc/sys/kernel/cap_last_cap", "r");
    if (!f) die("read cap_last_cap");
    int last = 0;
    if (fscanf(f, "%d", &last) != 1) die("parse cap_last_cap");
    fclose(f);
    return last;
}

/* Remove every capability that is not in KEEP_CAPS from the bounding set. */
static void drop_capabilities(void) {
    for (int cap = 0; cap <= last_cap(); cap++) {
        if (!is_kept(cap) && prctl(PR_CAPBSET_DROP, cap, 0, 0, 0) < 0) die("drop capability");
    }
}
  • KEEP_CAPS holds the six capabilities as named constants from the kernel header.
  • last_cap reads /proc/sys/kernel/cap_last_cap, the highest capability number this kernel has. We ask instead of writing a number into the program, because new kernels add capabilities and we want to drop those too.
  • drop_capabilities calls prctl(PR_CAPBSET_DROP, cap, ...) for every capability that is not on our list.

The six bits we keep are numbers 0, 1, 3, 5, 6 and 7. As a mask: 1 + 2 + 8 + 32 + 64 + 128 = 235, which is 0xeb. Remember this number. We will look for it in the output in a moment.

Step 3.3: No new privileges, and limits (about 45 minutes)

Dropping capabilities is only half of it. A program inside could still run a set-uid file, one whose permission bits say "run as its owner". If the owner is root, the program starts with root's user id again. Linux has a switch for this, no_new_privs. Once set, it stays set for the process and all its children, it cannot be turned off, and from then on exec never hands out more rights than the caller already had: set-uid bits are ignored and file capabilities add nothing.

The limits come from setrlimit. Every limit has a soft value, which the kernel enforces, and a hard value, which is the ceiling for the soft one. We set both to the same number, so the process cannot raise its own limit. We use three:

LimitWhat it capsWhat happens at the limit
RLIMIT_ASthe size of the address space, set by --memmalloc and mmap fail with "out of memory"
RLIMIT_CPUCPU seconds, set by --cputhe process is killed
RLIMIT_NOFILEopen files, always 256 hereopen fails with "too many open files"

The code that sets them and applies everything together:

static void set_limit(int resource, rlim_t value, const char *name) {
    struct rlimit lim = {.rlim_cur = value, .rlim_max = value};
    if (setrlimit(resource, &lim) < 0) die(name);
}

/* Apply the limits last: they are inherited by everything the container starts. */
static void restrict_process(const struct run *r) {
    drop_capabilities();
    /* After this, exec can never give a program more rights than it had before. */
    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die("no_new_privs");
    if (r->mem_mb > 0) set_limit(RLIMIT_AS, (rlim_t)r->mem_mb * 1024 * 1024, "limit memory");
    if (r->cpu_secs > 0) set_limit(RLIMIT_CPU, (rlim_t)r->cpu_secs, "limit cpu time");
    set_limit(RLIMIT_NOFILE, 256, "limit open files");
}

restrict_process is called from child_main right before the command starts, because limits and dropped capabilities are inherited by everything the command runs. Doing it last also means that all the mounts and the root switch above could still use the powers we are about to remove.

The call sits in child_main, as the step just before the command starts:

/* 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);
    restrict_process(r);
    execvp(r->cmd[0], r->cmd);
    die(r->cmd[0]);
    return 1;
}

The runtime now has options. --mem and --cpu go in front of the root directory, so the struct and the argument parsing grow:

struct run {
    const char *rootfs;
    char **cmd;
    long mem_mb;   /* 0 means no limit */
    long cpu_secs; /* 0 means no limit */
};
static void usage(const char *prog) {
    fprintf(stderr, "usage: %s run [--mem MB] [--cpu SECONDS] ROOTFS COMMAND [ARGS...]\n", prog);
    exit(2);
}

static void parse_args(int argc, char **argv, struct run *r) {
    if (argc < 2 || strcmp(argv[1], "run") != 0) usage(argv[0]);
    int i = 2;
    while (i < argc && strncmp(argv[i], "--", 2) == 0) {
        if (i + 1 >= argc) usage(argv[0]);
        if (strcmp(argv[i], "--mem") == 0) r->mem_mb = atol(argv[i + 1]);
        else if (strcmp(argv[i], "--cpu") == 0) r->cpu_secs = atol(argv[i + 1]);
        else usage(argv[0]);
        i += 2;
    }
    if (argc - i < 2) usage(argv[0]);
    r->rootfs = argv[i];
    r->cmd = &argv[i + 1];
}
int main(int argc, char **argv) {
    struct run r = {0};
    parse_args(argc, argv, &r);

    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 3.4: Two programs that misbehave (about 35 minutes)

To test limits we need programs that break them on purpose. Put these two in a folder named tools. The first allocates N megabytes and touches every page, so the memory is really used. The second burns CPU forever:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Ask for N megabytes and touch every page, so the memory is really used. */
int main(int argc, char **argv) {
    long mb = argc > 1 ? atol(argv[1]) : 10;
    char *p = malloc((size_t)mb * 1024 * 1024);
    if (!p) {
        printf("hog: could not get %ld MB\n", mb);
        return 1;
    }
    memset(p, 1, (size_t)mb * 1024 * 1024);
    printf("hog: got %ld MB\n", mb);
    return 0;
}
/* Burn CPU until something stops us. */
int main(void) {
    for (volatile unsigned long i = 0;; i++) {
    }
}

mkrootfs.sh already looks in tools and compiles whatever it finds there into the root file system. Build everything and look at the capabilities first:

sh build.sh
sh mkrootfs.sh rootfs
sudo ./rt run rootfs grep -E "Cap|NoNewPrivs" /proc/self/status
CapInh:	0000000000000000
CapPrm:	00000000000000eb
CapEff:	00000000000000eb
CapBnd:	00000000000000eb
CapAmb:	0000000000000000
NoNewPrivs:	1

All three sets show eb, the mask we computed, and NoNewPrivs is 1. Now the things root could do a moment ago:

sudo ./rt run rootfs hostname other
sudo ./rt run rootfs sh -c 'mkdir /tmp/x; mount -t tmpfs none /tmp/x'
hostname: you must be root to change the host name
exit status 1
mount: /tmp/x: permission denied.
       dmesg(1) may have more information after failed mount system call.
exit status 32

Both are refused. Root inside the container can still write files and change owners, because we kept those capabilities. Now the limits. First memory, with a cap of 64 MB:

sudo ./rt run --mem 64 rootfs hog 20
sudo ./rt run --mem 64 rootfs hog 200
hog: got 20 MB
hog: could not get 200 MB
exit status 1

Twenty megabytes fit and two hundred do not. Then CPU time. We ask for two seconds, start a program that never ends, and measure the wall clock:

time sudo ./rt run --cpu 2 rootfs spin; echo "exit status $?"

real	0m2.011s
user	0m2.001s
sys	0m0.000s
exit status 137

The kernel killed it after two seconds of CPU time. The exit status 137 is 128 plus 9, the number of the kill signal. Read real as the wall clock and user as the CPU time. The digits after the decimal point will differ on your machine.

What do these limits really cap? RLIMIT_AS caps the address space of one process, not the memory the container really uses, and it counts memory a program has reserved but never touched. Ten processes can each use the full amount. A limit for the whole group of processes is the job of cgroups, which we leave for "Keep going".