Skip to content
systemcoding.dev
Security

The Complete Guide to Sandboxing Linux Processes

Build a Linux process sandbox layer by layer: drop root and capabilities, add namespaces, seccomp, Landlock, cgroups and systemd limits, then test what escapes.

31 min read
Summarize in AI
Flat illustration of a terminal session, with the Linux, Ubuntu and GNU Bash logos.

A sandbox is a promise about what a process cannot do, enforced by something other than the process. The process may be a network daemon parsing hostile input, a build step compiling someone else's code, a plugin loaded into your application or an image converter fed a file from a stranger. In each case the code is large, written by people you do not control or in a language that permits memory errors, and you have to assume that some input will take it over. The sandbox decides what the attacker gets after that happens. Linux has no single feature called "sandbox". It has about eight independent mechanisms, each restricting a different thing, and a sandbox is what you get by stacking the right ones. This guide builds that stack from the bottom, with working code at every layer, using Linux 6.12, glibc 2.40, libseccomp 2.5.5, libcap 2.66 and systemd 257. Each section says what a layer stops, what it does not, and how to confirm it is on.

Think in layers, because each one leaks

A single mechanism fails in a predictable way. File permissions fail when the process runs as root. Dropping root fails if the process can still call mount. Blocking mount with seccomp fails if the process can talk to a privileged daemon over a socket it can still reach. Every layer covers a gap in another, and the point of stacking is that an attacker must break all of them, in sequence, from inside a compromised process.

Start from what a compromised process can do, and take each capability away in turn.

What the attacker wantsMechanism that takes it away
Act as a privileged userRun unprivileged; drop UIDs and groups
Use root-only operationsDrop capabilities; set no_new_privs
See other processes, the network, the host's mountsNamespaces
Read or write files outside the jobMount namespace with a minimal root, Landlock, an LSM
Call dangerous kernel interfacesseccomp filter
Exhaust memory, CPU or process slotscgroups
Do all of the above with one configurationsystemd unit directives, bubblewrap

The order in this guide follows the order in which you would apply them in a launcher: identity first, then the kernel's view of the world, then system calls, then limits. The final sections assemble a working sandbox in C and discuss testing, and the boundary where none of this is enough.

Layer 0: write down the threat model

Before you pick mechanisms, answer three questions in a paragraph.

What is being protected? The host's other files, the network the host is on, other tenants' data, the kernel itself? A sandbox for a thumbnailer that must not read /etc is a different design from one for a service that must not reach the cloud metadata address.

What does the sandboxed code legitimately need? List files it reads, files it writes, the sockets it opens, the system calls it makes. This list becomes the allowlist, and a sandbox written without it either breaks the program or lets everything through.

What is the attacker's starting point? For most sandboxes it is arbitrary code execution in the process, with the process's own permissions. That is the assumption throughout, and it is the right one: you cannot rely on finding every bug, so you plan for the one you missed.

One more calibration. These mechanisms share one kernel with the host. A sandbox built from them stops an attacker who has only the process's rights, and it does not stop one who has a working kernel exploit, because a kernel bug lets them step outside every rule that the kernel enforces. If the threat is hostile code with kernel exploits at its disposal, the boundary has to be a hypervisor, as the last section covers.

Layer 1: never run as root, and drop it correctly

The first step is the cheapest and the one most often skipped: run the service as a dedicated unprivileged user. A user and group with no login shell, owning only the files the service needs, make every file permission check work for you. Create it once:

Shell
sudo useradd --system --no-create-home --shell /usr/sbin/nologin --user-group imgconv
id imgconv
Text
uid=998(imgconv) gid=998(imgconv) groups=998(imgconv)

The numeric IDs depend on your system. A program that must start as root, for example to bind port 443, then gives up root in code, and the order matters: clear supplementary groups, set the group, set the user with all three IDs at once, and verify. The full explanation and a tested function are in users, groups and setuid explained. The short form:

dropprivs_short.cc
#define _GNU_SOURCE
#include <grp.h>
#include <sys/types.h>
#include <unistd.h>

int drop_to(uid_t uid, gid_t gid) {
    if (setgroups(0, NULL) < 0) return -1;
    if (setresgid(gid, gid, gid) < 0) return -1;
    if (setresuid(uid, uid, uid) < 0) return -1;
    return setuid(0) == 0 ? -1 : 0;     /* must fail after a correct drop */
}

This layer alone stops an attacker from reading files they have no permission for. It does nothing about the network, other processes the same user owns, or what the kernel lets any user do, which is why it is layer 1 and not the whole story.

Layer 2: remove capabilities

Root's power is a set of about forty capabilities, as covered in Linux capabilities explained. An unprivileged process has none in its effective set, but programs started with setuid files, file capabilities or ambient capabilities can gain some, and a process that starts as root has all of them until it drops them. For a sandbox, make the empty set explicit and permanent.

Three controls work together. The bounding set caps what any descendant can ever acquire through execve(), and dropping a capability from it is irreversible for the process and its children. The permitted, effective and inheritable sets govern what the process holds now. And **no_new_privs**, covered in ambient capabilities and no_new_privs, makes execve() unable to grant anything through setuid files or file capabilities.

dropcaps.cc
#include <linux/capability.h>
#include <stdio.h>
#include <sys/capability.h>
#include <sys/prctl.h>

int drop_all_caps(void) {
    /* Bounding set: remove every capability the kernel knows. */
    for (int cap = 0; cap <= CAP_LAST_CAP; cap++) {
        if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0) < 0) {
            /* EINVAL means the kernel lacks this capability number: stop. */
            break;
        }
    }
    /* Clear the permitted, effective and inheritable sets. */
    cap_t empty = cap_init();
    if (cap_set_proc(empty) < 0) {
        perror("cap_set_proc");
        cap_free(empty);
        return -1;
    }
    cap_free(empty);

    /* Make it permanent for this process and every child. */
    return prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
}

After this function, the process cannot regain capabilities by executing a setuid binary and cannot raise a capability from the bounding set, because the set is empty. Confirm it from outside with the status lines:

Shell
grep -E '^(CapBnd|CapEff|NoNewPrivs)' /proc/$(pgrep -n imgconvd)/status
Text
CapBnd:	0000000000000000
CapEff:	0000000000000000
NoNewPrivs:	1

The binary name imgconvd is a placeholder for your service. An empty bounding set with NoNewPrivs: 1 is the target state for most sandboxed workers. What this layer does not stop is any action that needs no capability: reading world-readable files, opening outbound sockets, creating files in directories the user can write, and calling any system call at all. Those belong to the next layers.

Layer 3: namespaces change what the process can see

A namespace gives a process its own view of one kind of global resource. Linux has eight: mount, PID, network, UTS (host name), IPC, user, cgroup and time. A sandbox uses them not to restrict operations but to remove the objects the operations would act on. A process in a new PID namespace cannot signal host processes because it cannot name them. In a new network namespace there are no host interfaces to send on. In a new mount namespace the host's filesystem is not visible.

The quickest way to see them is unshare(1) from util-linux. This gives an unprivileged user a shell that believes it is root in a world of its own:

Shell
unshare --user --map-root-user --pid --fork --mount-proc --net --uts --ipc /bin/bash
id
hostname sandbox
ps -e
ip -brief link
Text
uid=0(root) gid=0(root) groups=0(root),65534(nogroup)
    PID TTY          TIME CMD
      1 pts/0    00:00:00 bash
      5 pts/0    00:00:00 ps
lo               DOWN           127.0.0.1/8

The process list shows only itself because of the new PID namespace and the fresh /proc that --mount-proc mounted. The network namespace has only a downed loopback interface, so there is no way out. hostname sandbox changed the host name inside the UTS namespace and left the real one untouched. The root identity is the part that surprises people.

The user namespace is the key, and the risk

The user namespace is what lets an unprivileged process create the others, and it is also the one that has produced the most kernel vulnerabilities, because it exposes kernel code to unprivileged users that was written assuming only root could reach it. Inside a user namespace, the process holds a full set of capabilities, but only over resources owned by that namespace. uid 0 inside maps to your real UID outside, as the mapping shows:

Shell
cat /proc/self/uid_map
Text
         0       1000          1

The three columns are the first ID inside, the first ID outside and the length of the range. So the shell is root for namespaced things like its own mounts and its own network stack, and an ordinary user for anything real.

Two operational notes. Some distributions restrict unprivileged user namespaces through a sysctl (kernel.unprivileged_userns_clone on Debian-derived kernels, user.max_user_namespaces generally, and an AppArmor restriction on Ubuntu 23.10 and later), because of the exposure. A service that creates a user namespace for its sandbox must handle the case where it is not allowed. And an attacker inside a user namespace has access to kernel features, such as creating netfilter rules in its own network namespace, that they would not otherwise reach, so pair user namespaces with a seccomp filter that blocks the calls the sandboxed code does not need.

Namespaces from C

The unshare(1) command is a wrapper over clone() and unshare(). A program creates a child in new namespaces with clone flags:

nsdemo.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)

static int child(void *arg) {
    (void)arg;
    printf("child: pid %d, uid %d\n", (int)getpid(), (int)getuid());
    return 0;
}

int main(void) {
    char *stack = malloc(STACK_SIZE);
    if (!stack) return 1;

    int flags = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS |
                CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWIPC | SIGCHLD;
    pid_t pid = clone(child, stack + STACK_SIZE, flags, NULL);
    if (pid < 0) {
        fprintf(stderr, "clone: %s\n", strerror(errno));
        return 1;
    }
    waitpid(pid, NULL, 0);
    return 0;
}
Text
child: pid 1, uid 65534

The child is PID 1 in its own PID namespace. Its getuid() is 65534, the overflow user ID, because the parent has not yet written a UID map and an unmapped ID reads as nobody. The real sandbox launcher below writes the maps before the child proceeds.

Layer 4: a minimal filesystem

A process that can see your whole filesystem can read /etc/shadow if permissions allow, read other users' files in world-readable directories, and find configuration that tells it where to go next. The sandbox should present only what the program needs: its own binary, its libraries, a scratch directory, and its inputs.

Linux gives you two ways to build such a view. chroot changes the process's root directory and is old, simple and weak: a process with CAP_SYS_CHROOT can escape it, and it does not hide the mount table. The right tool is a mount namespace plus pivot_root, which swaps the root of the whole namespace and lets you unmount the old one, so nothing of the host remains reachable.

The recipe, as the pivot_root(2) man page describes it, avoids needing a directory for the old root by pivoting onto the same place:

pivot.cc
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <unistd.h>

int enter_rootfs(const char *newroot) {
    /* Keep mount changes from propagating to the host. */
    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) return -1;
    /* pivot_root needs the new root to be a mount point. */
    if (mount(newroot, newroot, NULL, MS_BIND | MS_REC, NULL) < 0) return -1;
    if (chdir(newroot) < 0) return -1;
    /* Stack the old root under the new one, then detach it. */
    if (syscall(SYS_pivot_root, ".", ".") < 0) return -1;
    if (umount2(".", MNT_DETACH) < 0) return -1;
    return chdir("/");
}

After enter_rootfs("./rootfs"), the process sees only what is under rootfs. Populate it with the program, the libraries it links (ldd on a trusted build tells you which), and nothing else. The smallest rootfs is a statically linked program, which needs no libraries and fits in a directory with a handful of files. Mount /proc inside with MS_NOSUID | MS_NODEV | MS_NOEXEC if the program needs it, and nothing else unless it must.

Make data mounts read-only where you can. A bind mount made read-only needs two steps because the first bind does not honor the read-only flag:

robind.cc
#include <sys/mount.h>

int bind_readonly(const char *src, const char *dst) {
    if (mount(src, dst, NULL, MS_BIND | MS_REC, NULL) < 0) return -1;
    return mount(NULL, dst, NULL,
                 MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV,
                 NULL);
}

A sandbox that can only read its input and write to one scratch directory removes the most common post-exploitation steps: planting a persistent file, tampering with its own binary, and reading configuration.

Layer 5: Landlock, filesystem rules without a namespace

Building a root filesystem is heavyweight. Landlock, added in Linux 5.13, is a lighter way to say "this process may touch only these directories", and it needs no privilege and no mount namespace. A process builds a ruleset of the access types it wants to control, adds rules granting those accesses beneath chosen directories, and enforces the ruleset on itself. Once enforced it cannot be removed, and children inherit it.

landlock_demo.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/landlock.h>
#include <stdio.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>

static int allow(int ruleset_fd, const char *dir, __u64 access) {
    struct landlock_path_beneath_attr pb = { .allowed_access = access };
    pb.parent_fd = open(dir, O_PATH | O_CLOEXEC);
    if (pb.parent_fd < 0) return -1;
    int r = syscall(SYS_landlock_add_rule, ruleset_fd,
                    LANDLOCK_RULE_PATH_BENEATH, &pb, 0);
    close(pb.parent_fd);
    return r;
}

int main(void) {
    const __u64 READ = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
    const __u64 EXEC = LANDLOCK_ACCESS_FS_EXECUTE;
    const __u64 ALL = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE |
        LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR |
        LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE |
        LANDLOCK_ACCESS_FS_MAKE_CHAR | LANDLOCK_ACCESS_FS_MAKE_DIR |
        LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_SOCK |
        LANDLOCK_ACCESS_FS_MAKE_FIFO | LANDLOCK_ACCESS_FS_MAKE_BLOCK |
        LANDLOCK_ACCESS_FS_MAKE_SYM;

    struct landlock_ruleset_attr attr = { .handled_access_fs = ALL };
    int rs = syscall(SYS_landlock_create_ruleset, &attr, sizeof attr, 0);
    if (rs < 0) {
        fprintf(stderr, "landlock unavailable: %s\n", strerror(errno));
        return 1;
    }
    if (allow(rs, "/usr", READ | EXEC) < 0) return 1;
    if (allow(rs, "/tmp/work", READ | LANDLOCK_ACCESS_FS_WRITE_FILE |
                              LANDLOCK_ACCESS_FS_MAKE_REG) < 0) return 1;

    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) return 1;
    if (syscall(SYS_landlock_restrict_self, rs, 0) < 0) return 1;
    close(rs);

    int fd = open("/usr/share", O_RDONLY | O_DIRECTORY);
    printf("/usr/share: %s\n", fd >= 0 ? "allowed" : strerror(errno));
    fd = open("/etc/passwd", O_RDONLY);
    printf("/etc/passwd: %s\n", fd >= 0 ? "allowed" : strerror(errno));
    return 0;
}
Text
/usr/share: allowed
/etc/passwd: Permission denied

This uses the access rights from the first Landlock ABI, so it runs on any kernel from 5.13. Later ABIs add rights you can opt into: file renames across directories (ABI 2, Linux 5.19), truncation (ABI 3, 6.2), TCP bind and connect rules (ABI 4, 6.7), device ioctls (ABI 5, 6.10) and scoping of signals and abstract Unix sockets (ABI 6, 6.12). A well-written program asks the kernel for its ABI version with landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION) and uses the best it finds. The kernel's documentation under Documentation/userspace-api/landlock.rst is the reference. Landlock is best-effort by design, so check for failure and decide whether running without it is acceptable.

Landlock's limit is that it controls file system access and, in later ABIs, a few network and IPC operations. It does not hide processes, restrict system calls or stop a process from using file descriptors it already holds, so open what you need before you restrict, then close what you do not.

Layer 6: seccomp narrows the kernel interface

Everything so far restricts what the process can name. Seccomp restricts which system calls it can make at all, and that is the layer that cuts the kernel's attack surface. Linux has over 400 system calls, and a thumbnailer needs perhaps 40. The ones it never calls are interfaces an attacker could use to reach vulnerable kernel code, so a filter that denies them takes those bugs off the table.

The mechanism, the data the filter sees and the return actions are covered in seccomp-bpf explained. In practice you write the filter with libseccomp, as in writing a seccomp filter with libseccomp, and generate the allowlist from a recording, as in building an allowlist with strace. A compact version for a sandbox launcher uses a denylist as a baseline when you cannot yet enumerate the allowlist:

baseline_filter.cc
#include <errno.h>
#include <seccomp.h>

static const int denied[] = {
    SCMP_SYS(ptrace), SCMP_SYS(mount), SCMP_SYS(umount2),
    SCMP_SYS(pivot_root), SCMP_SYS(unshare), SCMP_SYS(setns),
    SCMP_SYS(keyctl), SCMP_SYS(add_key), SCMP_SYS(request_key),
    SCMP_SYS(bpf), SCMP_SYS(perf_event_open), SCMP_SYS(kexec_load),
    SCMP_SYS(init_module), SCMP_SYS(finit_module), SCMP_SYS(delete_module),
    SCMP_SYS(reboot), SCMP_SYS(swapon), SCMP_SYS(swapoff),
    SCMP_SYS(acct), SCMP_SYS(settimeofday), SCMP_SYS(clock_settime),
};

int install_baseline_filter(void) {
    scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
    if (!ctx) return -1;
    for (unsigned i = 0; i < sizeof denied / sizeof denied[0]; i++) {
        if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), denied[i], 0) < 0) {
            seccomp_release(ctx);
            return -1;
        }
    }
    int rc = seccomp_load(ctx);
    seccomp_release(ctx);
    return rc;
}

This is a floor, not a design. A denylist fails open when the kernel adds a call, and an allowlist is the correct end state. Move to one as soon as your recording is solid. Whichever you use, confirm it is on from the outside: the Seccomp line in /proc/PID/status is 0 for none, 1 for strict mode and 2 for a filter, and Seccomp_filters counts how many are stacked.

Shell
grep -E '^(Seccomp|Seccomp_filters)' /proc/$(pgrep -n imgconvd)/status
Text
Seccomp:	2
Seccomp_filters:	1

Seccomp cannot see strings or follow pointers, so it cannot say "open only these paths". That is why it pairs with a mount namespace or Landlock for files. When a decision truly needs the arguments' contents, SECCOMP_RET_USER_NOTIF lets a supervisor process decide, at the price of a more complex sandbox.

Layer 7: a Linux Security Module as a second opinion

AppArmor and SELinux add policy that the application cannot change, written by the administrator, covering files, capabilities, network families and more. They are valuable for the same reason defense in depth is: they stand outside the program's own sandbox code, so a bug in your launcher does not disable them, and they apply to programs that do not sandbox themselves. A profile for a daemon, as in writing an AppArmor profile for a system daemon, confines it whether or not it calls seccomp or landlock. The comparison between the two systems, and which your distribution has made the default, is in SELinux vs AppArmor. Use the one your platform ships and treat its policy as one more layer.

Layer 8: cgroups limit resources

A compromised or merely buggy process can take down the host without escaping anything: a fork bomb exhausts the process table, a memory leak triggers the out-of-memory killer on innocent neighbors, a spin loop pins a CPU. Control groups put hard ceilings on those. On a system with cgroup v2 (the default on current distributions), the files live under /sys/fs/cgroup, and a group is a directory.

Shell
sudo mkdir /sys/fs/cgroup/imgconv
echo "+memory +pids +cpu" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
echo 268435456 | sudo tee /sys/fs/cgroup/imgconv/memory.max
echo 64        | sudo tee /sys/fs/cgroup/imgconv/pids.max
echo "50000 100000" | sudo tee /sys/fs/cgroup/imgconv/cpu.max
echo $$        | sudo tee /sys/fs/cgroup/imgconv/cgroup.procs
cat /sys/fs/cgroup/imgconv/memory.max /sys/fs/cgroup/imgconv/pids.max /sys/fs/cgroup/imgconv/cpu.max
Text
268435456
64
50000 100000

The limits are 256 MiB of memory, 64 processes and threads, and half of one CPU (50,000 microseconds of every 100,000). A process in this group that reaches memory.max is reclaimed and then killed by the group's OOM handling, and a fork beyond 64 fails with EAGAIN. Under systemd you rarely write these by hand: MemoryMax=, TasksMax= and CPUQuota= in a unit file create the same controls and clean them up.

Resource limits do not stop an attacker from reading data, so they complement the confinement layers and do not replace them. They turn a denial-of-service attempt into a contained failure.

Layer 9: let systemd do the assembly

For a long-running service, systemd already implements most of the stack and gets the ordering right. A unit with the following directives uses a dedicated user, an empty capability set, a read-only filesystem view, private temporary files, a filtered system call set and resource caps:

Text
[Service]
ExecStart=/usr/local/sbin/imgconvd
User=imgconv
Group=imgconv
NoNewPrivileges=yes
CapabilityBoundingSet=
AmbientCapabilities=
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
PrivateNetwork=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictNamespaces=yes
RestrictAddressFamilies=AF_UNIX
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallFilter=@system-service
SystemCallArchitectures=native
ReadWritePaths=/var/lib/imgconv
MemoryMax=256M
TasksMax=64

Each line maps to a mechanism in this guide. NoNewPrivileges is no_new_privs, CapabilityBoundingSet= with nothing after it is an empty bounding set, ProtectSystem=strict and ReadWritePaths build a read-only mount view, PrivateNetwork is a network namespace, SystemCallFilter=@system-service is a seccomp allowlist of the calls ordinary services need, and MemoryMax and TasksMax are cgroup limits. The directives are documented in systemd.exec(5) and systemd.resource-control(5). The post on hardening a systemd service with sandboxing directives goes through them one at a time.

The command systemd-analyze security imgconvd.service scores a unit's exposure from 0 to 10 and lists each unset directive with its weight, which makes it a practical checklist: raise the score of the exposure you can remove, and write down the ones you cannot. A directive can break the service, so apply them one or two at a time and read the journal after each restart.

Putting it together: a launcher you can read

The layers combine into one program. This launcher creates new user, PID, mount, network, UTS and IPC namespaces, maps the caller to root inside, pivots into a prepared root filesystem, mounts /proc, drops all capabilities, sets no_new_privs, installs the baseline seccomp filter and executes the target. It uses the functions from the sections above, collected so you can see the order.

sandbox.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <seccomp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/capability.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)

struct job {
    const char *rootfs;
    char **argv;
    int sync_fd;            /* read end: parent signals when maps are written */
};

static void die(const char *what) { perror(what); _exit(1); }

static int write_file(const char *path, const char *text) {
    int fd = open(path, O_WRONLY);
    if (fd < 0) return -1;
    ssize_t n = write(fd, text, strlen(text));
    close(fd);
    return n < 0 ? -1 : 0;
}

static void enter_rootfs(const char *newroot) {
    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) die("make private");
    if (mount(newroot, newroot, NULL, MS_BIND | MS_REC, NULL) < 0) die("bind root");
    if (chdir(newroot) < 0) die("chdir");
    if (syscall(SYS_pivot_root, ".", ".") < 0) die("pivot_root");
    if (umount2(".", MNT_DETACH) < 0) die("umount old root");
    if (chdir("/") < 0) die("chdir /");
    if (mount("proc", "/proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) < 0)
        die("mount proc");
}

static void drop_caps_and_lock(void) {
    for (int cap = 0; ; cap++)
        if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0) < 0) break;
    cap_t empty = cap_init();
    if (cap_set_proc(empty) < 0) die("cap_set_proc");
    cap_free(empty);
    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die("no_new_privs");
}

static void install_filter(void) {
    int denied[] = { SCMP_SYS(ptrace), SCMP_SYS(mount), SCMP_SYS(umount2),
        SCMP_SYS(pivot_root), SCMP_SYS(unshare), SCMP_SYS(setns),
        SCMP_SYS(keyctl), SCMP_SYS(bpf), SCMP_SYS(perf_event_open),
        SCMP_SYS(init_module), SCMP_SYS(finit_module), SCMP_SYS(kexec_load),
        SCMP_SYS(reboot) };
    scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
    if (!ctx) die("seccomp_init");
    for (unsigned i = 0; i < sizeof denied / sizeof denied[0]; i++)
        if (seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), denied[i], 0) < 0)
            die("seccomp_rule_add");
    if (seccomp_load(ctx) < 0) die("seccomp_load");
    seccomp_release(ctx);
}

static int child_main(void *arg) {
    struct job *job = arg;
    char c;
    if (read(job->sync_fd, &c, 1) != 1) die("sync");     /* wait for uid_map */
    close(job->sync_fd);

    if (sethostname("sandbox", 7) < 0) die("sethostname");
    enter_rootfs(job->rootfs);
    drop_caps_and_lock();     /* after the mounts: they need capabilities */
    install_filter();         /* last: it blocks the calls used above */
    execv(job->argv[0], job->argv);
    die("execv");
    return 1;
}

int main(int argc, char **argv) {
    if (argc < 3) {
        fprintf(stderr, "usage: %s rootfs program [args...]\n", argv[0]);
        return 2;
    }
    int pipefd[2];
    if (pipe(pipefd) < 0) die("pipe");
    struct job job = { argv[1], &argv[2], pipefd[0] };

    char *stack = malloc(STACK_SIZE);
    if (!stack) die("malloc");
    int flags = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET |
                CLONE_NEWUTS | CLONE_NEWIPC | SIGCHLD;
    pid_t pid = clone(child_main, stack + STACK_SIZE, flags, &job);
    if (pid < 0) die("clone");

    char path[64], map[64];
    snprintf(path, sizeof path, "/proc/%d/setgroups", (int)pid);
    if (write_file(path, "deny") < 0) die("setgroups");
    snprintf(map, sizeof map, "0 %d 1", (int)getuid());
    snprintf(path, sizeof path, "/proc/%d/uid_map", (int)pid);
    if (write_file(path, map) < 0) die("uid_map");
    snprintf(map, sizeof map, "0 %d 1", (int)getgid());
    snprintf(path, sizeof path, "/proc/%d/gid_map", (int)pid);
    if (write_file(path, map) < 0) die("gid_map");

    write(pipefd[1], "x", 1);
    close(pipefd[1]);

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

The order of the child's steps is the part to understand. It waits for the parent to write the UID and GID maps, because the child cannot do privileged namespace operations before it has a mapped identity. It sets the host name, then pivots into the new root, which needs capabilities in the user namespace. Only after those mounts does it drop capabilities, since dropping first would make the mounts fail. The seccomp filter goes last, because it blocks mount and pivot_root, which the earlier steps used. The setgroups file is written with deny before the GID map, a requirement for an unprivileged process writing its own gid_map.

Build it with cc -o sandbox sandbox.c -lseccomp -lcap, and prepare a root filesystem with a static BusyBox, which provides a shell and tools with no library dependencies:

Shell
mkdir -p rootfs/bin rootfs/proc
cp /usr/bin/busybox rootfs/bin/busybox
for t in sh id ls cat hostname ps grep mount; do ln -s busybox rootfs/bin/$t; done
./sandbox ./rootfs /bin/sh -c 'id; hostname; ls /; grep -E "^(Seccomp|NoNewPrivs|CapEff)" /proc/self/status; mount -t tmpfs x /tmp'
Text
uid=0 gid=0
sandbox
bin   proc
CapEff:	0000000000000000
NoNewPrivs:	1
Seccomp:	2
mount: permission denied (are you root?)

The sandboxed shell believes it is user 0, has host name sandbox, sees only bin and proc, holds no capabilities, has no_new_privs set and a filter installed, and its attempt to mount is refused. The BusyBox here must be a statically linked build, which the busybox-static package provides on Debian derivatives; if yours is dynamic, copy its libraries into rootfs as well. The program names are a convenience, and the exact output formatting depends on the BusyBox build.

Using ready-made tools

You do not have to write a launcher. Bubblewrap (bwrap), the tool behind Flatpak's sandbox, builds the same namespaces and mount layout from command-line options and is designed to be safe for unprivileged use:

Shell
bwrap --unshare-all --die-with-parent \
      --ro-bind /usr /usr \
      --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 \
      --proc /proc --dev /dev --tmpfs /tmp \
      --ro-bind ./input /data/input \
      --chdir /data \
      /usr/bin/python3 convert.py

--unshare-all creates every namespace it can, including the network, so the script has no connectivity. The --ro-bind lines expose the system files and the input read-only, and --die-with-parent kills the sandbox if its controller exits. Bubblewrap does not add a seccomp filter by itself unless you pass one with --seccomp, so add one for untrusted code. Firejail, nsjail and minijail are similar tools with different defaults; nsjail and minijail were written for hosting untrusted programs and include rich limits and filters. The point of knowing the layers is that you can read any of these tools' configuration and tell what it does and what is missing.

Network access: none, proxied or filtered

The strongest network policy is no network. A new network namespace with no interfaces, or with only a downed loopback, cannot send a packet anywhere, and for a converter, a parser or a compiler that is exactly right: the data comes in through a file or a descriptor and goes out the same way. When the code genuinely needs the network, you have three choices, in order of preference.

First, pass in the connection and not the capability. The launcher opens the socket, connects it to the one destination the job needs, and hands the descriptor to the sandboxed process, which never gets permission to create sockets of its own. A seccomp filter that denies socket and connect makes this a hard rule. Second, give the sandbox a network namespace joined to the host by a virtual Ethernet pair and filter the pair on the host side with nftables, allowing only the destination addresses and ports the job needs and logging the rest. Third, run an egress proxy outside the sandbox that enforces an allowlist of host names, and put the proxy's address in the sandbox as the only reachable destination.

Whichever you choose, remember the addresses a compromised process wants first. The cloud provider's metadata service on 169.254.169.254 hands out instance credentials to anything that can reach it, and the host's loopback services often trust local callers. A rule that blocks link-local and private ranges, as well as the host's own addresses, belongs in every egress policy. And a sandbox with Unix domain sockets should be given only the ones it needs, since a reachable socket to a privileged daemon is a direct line out of the sandbox, whatever the other layers say. In the systemd directives this is RestrictAddressFamilies=, which can allow only AF_UNIX or only AF_INET and AF_INET6, and IPAddressDeny=any with a short IPAddressAllow= list, which uses a BPF program attached to the service's cgroup to filter packets without any firewall configuration.

When the sandbox breaks the program

Your first sandbox will kill the program on a call you did not know it made. The failure looks different at each layer, and recognizing it saves hours.

A seccomp ERRNO action surfaces as an EPERM or ENOSYS from a call that never normally fails, often deep in a library, and the program reports a vague error or crashes later. A KILL_PROCESS action ends the process with SIGSYS, and the shell reports Bad system call. Both leave records. With auditing enabled, the kernel writes a SECCOMP record that names the call number and the architecture, and ausyscall turns the number into a name. Without audit, run the program under strace -f in a test environment without the filter and compare its calls with the allowlist. The strace post in this cluster describes the loop.

A mount namespace failure appears as ENOENT for a file that exists on the host: a missing shared library, a missing /etc/resolv.conf, a missing certificate bundle or time zone data. The dynamic loader prints the library name, so ldd on the binary, run on a trusted copy, lists what to copy in. Programs that resolve names need /etc/resolv.conf, /etc/hosts and /etc/nsswitch.conf, and programs that verify TLS need the certificate store.

A Landlock denial is EACCES on an open, and a capability or namespace restriction is EPERM on an operation that needs privilege. Two diagnostics help across all of these. The kernel log (dmesg or journalctl -k) prints AppArmor and audit denials. And strace -f -e trace=file,process shows the exact path or call that returned the error, which is nearly always enough to see which layer said no.

The discipline is to loosen one layer by the smallest amount that fixes the failure, record why, and re-run the attacker checklist. Resist turning a layer off to see whether it is the cause for more than one test, because a sandbox with a disabled layer tends to ship that way.

A worked design: an image conversion service

To see the layers working as a set, take a service that accepts uploaded images and converts them to thumbnails with a large C library that has a record of memory-safety bugs. The input is hostile by definition. The threat is that a crafted image takes over the converter, and the goal is that the takeover yields nothing.

The converter runs as the imgconv user, which owns nothing. It starts through a small supervisor that holds the privileges needed to set up the sandbox and drops them. For each job, the supervisor creates a new user, PID, mount, network and IPC namespace, so the converter sees no host processes, no network and no host filesystem. Its root is a directory holding the converter binary and the few libraries it links, mounted read-only, plus a tmpfs scratch directory of fixed size. The input arrives as an open read-only descriptor and the output leaves through a pipe, so the converter needs no file paths at all. Capabilities and the bounding set are empty, no_new_privs is set, and a seccomp allowlist generated from recordings of the converter on a corpus of images permits about forty calls and kills the process on anything else. A cgroup caps memory at 256 MiB, processes at eight and CPU time at a few seconds, so a decompression bomb or an infinite loop ends in a clean kill. An AppArmor profile on the supervisor's binary stops a bug in the supervisor from reaching the host in the first place.

Now trace what a successful exploit of the converter gets. Arbitrary code in the process has no files to read except its own libraries, no network to send on, no other processes to signal, no capabilities to use and a short list of system calls to make, none of which reaches the kernel's more exposed parts such as bpf, userfaultfd or io_uring. It can write garbage to the pipe, and the supervisor validates what it reads from it before using it, because the output of a compromised worker is untrusted data too. It can spin until the cgroup kills it. That is a drastically worse position than the one a bare process offers, and every restriction came from a mechanism in this guide.

The residual risk is also clear. A kernel bug reachable through one of the forty allowed calls, or a flaw in the supervisor's handling of the pipe, still breaks out. You mitigate the first by keeping the allowlist short and the kernel patched, and the second by keeping the supervisor small and written in a memory-safe language where possible. And if the service were hosting code from tenants who might bring kernel exploits, this design would stop being enough, which brings us back to the hypervisor boundary.

Testing the sandbox like an attacker

A sandbox you have not tried to break is an assumption. Test from inside, as the compromised process, with a checklist run through a shell or test program placed in the sandbox:

  1. Identity. id and /proc/self/status show the expected UIDs, an empty CapEff and CapBnd, NoNewPrivs: 1 and Seccomp: 2.

  2. Filesystem. Try to read /etc/shadow, the host's home directories and your own source tree. Try to write outside the scratch directory. List /proc/self/mounts and confirm only the expected mounts exist.

  3. Processes. ps -e or a listing of /proc shows only sandbox processes. Try kill -9 1 from inside and confirm it affects only the sandbox's own PID 1.

  4. Network. Try ping, a TCP connect to a known address and a DNS lookup. With no network namespace connectivity all three fail. If the sandbox needs a network, test that only the intended destinations work.

  5. System calls. Call each denied system call and confirm the error: mount, ptrace, unshare, bpf. A program in the test set that calls them directly with syscall() is the clearest check.

  6. Resources. Run a fork loop and a memory allocation loop and confirm the cgroup stops each.

  7. Escape primitives. Check that file descriptors inherited from the launcher are closed (ls -l /proc/self/fd shows only 0, 1, 2 and what you meant to pass), that no socket to a privileged daemon is reachable, and that device nodes are absent or restricted.

Also inspect it from outside. List the process's namespaces with ls -l /proc/PID/ns: a namespace whose inode equals the host's /proc/1/ns entry is shared, not new. Record the expected state in a test that runs in CI, so a change to the launcher or a kernel update that alters behavior fails loudly.

Failure stories worth learning from

Most sandbox escapes are not kernel exploits. They are configuration mistakes, and a few recur.

A leaked descriptor. The launcher opened a log file or a directory descriptor and did not mark it close-on-exec. The sandboxed program inherits it, and a directory descriptor outside the new root lets it walk back out. Open files with O_CLOEXEC, and close everything above 2 before execve(); on Linux 5.9 and later close_range(3, ~0U, 0) does it in one call.

A sensitive socket mounted in. The sandbox bind-mounted /run or the Docker socket to let the program talk to something. A process that can reach the container runtime's socket can start a privileged container. Treat every bind mount and socket as a hole in the wall and give out the minimum.

**Shared /proc or /sys.** Mounting the host's /proc inside a new PID namespace shows the host's processes, and /proc/sys and /sys expose tunables. Mount a fresh /proc for the namespace, mask or omit /sys, and leave kernel tunables read-only.

Setuid binaries inside. A rootfs copied from a distribution contains setuid programs. With no_new_privs they do not escalate, but without it they do. Strip them or mount the tree nosuid.

A loose seccomp denylist. The filter blocked open and not openat, or socket and not the io_uring interface that does the same job. Denylists are fragile. Allowlist, and treat io_uring_setup, userfaultfd and bpf as dangerous unless needed.

Time of check, time of use in a supervisor. A user-notification supervisor that checks a path and then lets the call continue can be raced, as the supervisor post explains.

Where this guide's approach does not fit

A stack of kernel features gives a strong barrier against an attacker holding a normal process. It is the wrong tool in four cases, and each has a better one.

You host code from mutually hostile tenants. If tenants may be actively malicious and have time to find kernel bugs, share nothing: use virtual machines, or microVMs such as Firecracker, so the boundary is a hypervisor with a much smaller attack surface than the Linux system call interface. User-space kernels such as gVisor sit between the two, intercepting system calls and re-implementing them, at a cost in performance and compatibility. The decision depends on how much you trust the code and how bad a breach is.

The process needs broad access to do its job. A build tool that must read the whole source tree, run compilers and write outputs everywhere cannot be confined to a narrow view without being rebuilt around it. Confine its network and its credentials instead, and run it in a disposable environment.

You need to protect against hardware side channels. Namespaces and seccomp do nothing against Spectre-class leaks between a sandbox and its host. Those need the mitigations in the guide to CPU side channels and, for the strongest guarantees, separate hardware.

The kernel has the bug. A local privilege escalation in any reachable kernel code lets the attacker leave the sandbox. Narrowing the reachable code with seccomp reduces the chance, and keeping the kernel current reduces it more. It cannot be reduced to zero, which is the reason for the previous items.

A build order you can follow

For a new sandboxed service, apply the layers in this order and test after each. First, a dedicated user and a correct privilege drop. Second, an empty capability set and no_new_privs. Third, systemd or bwrap namespaces with a read-only, minimal filesystem. Fourth, a seccomp filter generated from a recording and tightened with logging first. Fifth, Landlock for the paths you still need to open. Sixth, cgroup limits. Seventh, an LSM profile. Between each step run the service's tests and the attacker checklist. If a layer breaks the program, the failure tells you something about what it really needs, and that knowledge is the output of the work as much as the sandbox itself.

Also inKernels
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.