Skip to content
systemcoding.dev
Systems Programming

Isolate the Filesystem with Mount Namespaces and pivot_root

Give a process its own root filesystem using CLONE_NEWNS, a private mount propagation and the pivot_root system call on Linux 6.12, with a complete C program.

6 min read
Summarize in AI
Flat illustration of guest machines running on a hypervisor over hardware, with the QEMU, C and Linux logos.

A process that should only see its own small filesystem needs two things: a private view of the mount table, and a new root directory. The mount namespace provides the first and pivot_root provides the second. People often reach for chroot instead, and for a process that can run as root it is a weaker tool: chroot changes where / points for one process but leaves every old mount reachable. This post builds the full sequence in C for Linux 6.12 and glibc 2.40, with every step and the error you meet if you skip one. The semantics come from mount_namespaces(7), pivot_root(2) and mount(2).

What a mount namespace is

Every process belongs to a mount namespace, which is its own copy of the list of mounts. A mount or unmount made inside the namespace changes only that list. A new namespace starts as a copy of the creator's list, requested with CLONE_NEWNS in clone or unshare. It needs CAP_SYS_ADMIN, so run the examples as root.

The flag is named NEWNS because mount namespaces were the first namespace type added to Linux, in 2.4.19, before anyone expected there would be more.

The trap: shared propagation

Copying the list is not enough, because mounts also carry a propagation type. On most distributions systemd marks the root mount as shared, which means a mount event in one namespace can propagate to the peer group it came from. If your new namespace keeps shared mounts, then a bind mount you make inside it can show up on the host, and pivot_root will refuse to work at all, returning EINVAL.

The cure is to turn the whole tree private right after creating the namespace:

c
mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);

MS_REC applies the change to every mount below /. Passing NULL for the source and filesystem type is correct here, because this call changes an existing mount instead of creating one. Skip it and you will see the failure further down.

The pivot_root contract

pivot_root(new_root, put_old) moves the current root to the directory put_old and makes new_root the root. The man page lists the rules, and each one costs someone an afternoon:

  1. new_root must be a mount point. A plain directory does not qualify; bind-mount it onto itself to make it one.

  2. put_old must be at or underneath new_root.

  3. Neither the mount holding new_root nor the parent of put_old may have shared propagation.

  4. The current root must not be the same mount as new_root.

glibc has no wrapper for it, so you call syscall(SYS_pivot_root, new_root, put_old) using the number from <sys/syscall.h>.

The root filesystem

The example needs a directory tree to pivot into. Build a tiny one with a statically linked BusyBox, which has no library dependencies:

Shell
mkdir -p /srv/rootfs/bin /srv/rootfs/proc /srv/rootfs/.pivot_old
cp /usr/bin/busybox /srv/rootfs/bin/busybox

The path to a static BusyBox varies by distribution, and the binary must be static, or the child will fail with "No such file or directory" because the dynamic loader is not inside the new root. Applets are selected by the argument, so busybox ls / runs the ls applet.

The complete program

mountns.cc
#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)
#define NEW_ROOT "/srv/rootfs"
#define PUT_OLD  "/srv/rootfs/.pivot_old"

static void die(const char *what)
{
    fprintf(stderr, "%s: %s\n", what, strerror(errno));
    _exit(1);
}

static int child_main(void *arg)
{
    (void)arg;

    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
        die("make mounts private");

    if (mount(NEW_ROOT, NEW_ROOT, NULL, MS_BIND | MS_REC, NULL) != 0)
        die("bind new root onto itself");

    if (syscall(SYS_pivot_root, NEW_ROOT, PUT_OLD) != 0)
        die("pivot_root");

    if (chdir("/") != 0)
        die("chdir");

    if (umount2("/.pivot_old", MNT_DETACH) != 0)
        die("umount old root");
    if (rmdir("/.pivot_old") != 0)
        die("rmdir old root mount point");

    if (mount("proc", "/proc", "proc", 0, NULL) != 0)
        die("mount proc");

    char *argv[] = { "/bin/busybox", "ls", "/", NULL };
    execv(argv[0], argv);
    die("execv");
    return 1;
}

int main(void)
{
    char *stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
    if (stack == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    pid_t pid = clone(child_main, stack + STACK_SIZE,
                      CLONE_NEWNS | CLONE_NEWPID | SIGCHLD, NULL);
    if (pid < 0) {
        perror("clone");
        return 1;
    }

    int wstatus;
    waitpid(pid, &wstatus, 0);
    return WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : 1;
}

Build with gcc -std=gnu17 -o mountns mountns.c and run sudo ./mountns. The child lists its new root:

Text
bin
proc

Only the two directories the tree contains are visible, and .pivot_old is gone. The host's /home, /etc and everything else is unreachable from the process, and not merely hidden.

Why each step is where it is

The private remount comes first so nothing that follows leaks. The self bind mount satisfies rule one: after it, /srv/rootfs is a mount point in its own right. pivot_root then swaps the roots, and the old root appears at /.pivot_old inside the new tree. At that moment the process can still read the host through that directory, which is exactly the hole chroot leaves permanently open.

chdir("/") is required because the process's working directory still refers to the old filesystem after the pivot. Without it, relative path lookups would go to the old tree.

umount2 with MNT_DETACH performs a lazy unmount: the mount disappears from the namespace immediately, and the kernel finishes cleaning up once nothing holds it. A plain umount would fail with EBUSY because the process's own earlier references keep the old root busy. After the unmount the old tree is gone from this namespace entirely, and rmdir removes the empty mount point.

The last mount puts a procfs at /proc. Because the child is also in a new PID namespace (CLONE_NEWPID), this procfs shows only the namespace's own processes, which fixes the ps problem from the PID namespace post.

The failures you will meet

Without the MS_PRIVATE remount on a systemd host, the pivot_root step fails:

Text
pivot_root: Invalid argument

That is rule three, shared propagation. If PUT_OLD is not under NEW_ROOT, it fails with the same EINVAL. If /srv/rootfs/bin/busybox is dynamically linked, execv fails with No such file or directory, which looks like a missing file but is a missing loader. And if you run as an ordinary user without a user namespace, the first mount call returns Operation not permitted.

chroot versus pivot_root

Propertychrootpivot_root
ChangesOne process's idea of /The root of the mount namespace
Old mountsStill reachable, can be escaped by rootDetached with umount2
Needs a mount namespaceNoEffectively yes
Needs a mount pointNoYes
Use in containersRareStandard

For a trusted process that only wants a tidy directory view, chroot is shorter. For anything that should resist a root process trying to escape, use the namespace plus pivot_root.

When this is not enough

A new root filesystem hides files but does not restrict anything else: the process still shares the network, and it can still use all of the host's CPU and memory. It also needs device nodes under /dev if the program opens /dev/null or a terminal, which this minimal tree omits. A real runtime populates /dev with bind mounts or a tmpfs, mounts /sys read-only, and drops capabilities. Those steps build on the same sequence.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.