Engineering
Running untrusted code safely: containers, gVisor, microVMs
If your product has a Run button, a plugin system or an AI agent that writes and executes code, you are running code you did not write. This guide explains what each isolation layer actually protects against, the resource limits that matter more than people expect, and how we chose a design for ls-judge, which runs every submission in its own microVM.
The threat model in one paragraph
Assume every submission is hostile. Not because most users are attackers, but because one is enough, and because ordinary mistakes look identical to attacks: an infinite loop is a denial-of-service, a recursive function without a base case exhausts memory, and a program that writes in a loop fills the disk. A sandbox has two jobs. The first is containment: the code must not read or change anything outside its own run, including the host, the network and other users' submissions. The second is fairness: one run must not starve the others of CPU, memory, processes, disk or time.
Most incidents in public code runners come from the second job being forgotten. Teams spend weeks on kernel isolation and then let a fork bomb take the host down because nobody set a process limit.
Layer 1: processes and resource limits
Every sandbox, however strong, ends with a process running your user's program. The limits on that process are the floor of your design:
- CPU time and wall time, separately. CPU time catches busy loops; wall time catches programs that sleep or block on input forever. A judge that only measures CPU time can be held open indefinitely by
sleep(1000). - Memory, enforced by the kernel (a cgroup
memory.max), not by watching the process from outside. Polling misses short spikes and reacts after the damage. - Process count (
pids.max). Without it,:(){ :|:& };:or afork()in a loop exhausts the host's process table in milliseconds. - Output size. A program printing in a loop can produce gigabytes of stdout; cap what you read and kill the run when it overflows.
- Disk. Give the run a small writable scratch area (a size-limited tmpfs) and make everything else read-only.
On Linux, cgroups v2 provides the memory, CPU and pid controllers; setrlimit adds per-process limits such as file size and open files. These limits are necessary in every design below, including microVMs, because a VM boundary protects the host but does nothing to stop a run from wasting its own allocation slowly.
Layer 2: containers
A container is a set of Linux processes with their own view of the system: namespaces give it a private process tree, network stack, mount table and hostname, cgroups cap its resources, capabilities are dropped, and a seccomp filter blocks dangerous system calls. Docker's default seccomp profile blocks dozens of calls such as kexec_load and mount.
A reasonably hardened run with plain Docker looks like this:
docker run --rm \
--network none \
--memory 256m --memory-swap 256m \
--cpus 1 --pids-limit 64 \
--read-only --tmpfs /tmp:rw,size=16m,noexec \
--cap-drop ALL --security-opt no-new-privileges \
--user 65534:65534 \
runner-python:3.12 timeout -s KILL 5 python3 /code/main.py < /code/input.txtEvery flag earns its place: no network, memory with swap disabled so the limit is real, one CPU, a process cap, a read-only root with a small non-executable scratch directory, no Linux capabilities, no privilege escalation through setuid binaries, and an unprivileged user.
The weakness is structural: all containers on a host share one kernel. The kernel exposes hundreds of system calls, and a bug in any reachable one is a path from the container to the host. Seccomp narrows the surface but cannot remove it, because real programs need read, write, mmap, clone and friends. Container escapes through kernel vulnerabilities are found every year. For code you wrote, or code from colleagues, containers are fine. For code from anonymous strangers on the internet, the shared kernel is the part to worry about.
Layer 3: gVisor, a kernel in user space
gVisor, from Google, puts a second kernel between the program and the host. Its Sentry component implements the Linux system call interface in a memory-safe language (Go) and runs as an ordinary user-space process. The sandboxed program's system calls go to the Sentry, not to the host kernel; the Sentry itself uses only a small, filtered set of host system calls.
The result is a much smaller host attack surface while keeping a container workflow: gVisor ships as an OCI runtime called runsc, so docker run --runtime=runsc works with the same images. The costs are compatibility and speed. Not every system call or /proc file is implemented, and workloads heavy in system calls (lots of small file operations, for example) run noticeably slower than on the host kernel, because every call is serviced in user space.
Layer 4: microVMs with Firecracker
Firecracker is a virtual machine monitor written in Rust by AWS, built on Linux KVM, and used to run AWS Lambda and Fargate. Each microVM has its own guest kernel, so a kernel bug inside the guest compromises only that guest. To reach the host, an attacker must also break the hardware virtualisation boundary and the deliberately tiny device model: Firecracker emulates only a handful of devices (virtio network and block, a serial console and a minimal keyboard controller used to reset the VM).
Its documentation targets a boot to guest user space in about 125 ms and a memory overhead of under 5 MiB per microVM, which is what makes one VM per run practical. Firecracker is configured through a REST API on a Unix socket:
# Kernel and root filesystem for the guest
curl --unix-socket /tmp/fc.sock -X PUT http://localhost/boot-source \
-d '{"kernel_image_path": "vmlinux", "boot_args": "console=ttyS0 reboot=k panic=1"}'
curl --unix-socket /tmp/fc.sock -X PUT http://localhost/drives/rootfs \
-d '{"drive_id": "rootfs", "path_on_host": "python.ext4", "is_root_device": true, "is_read_only": true}'
# One vCPU and 256 MiB for this run
curl --unix-socket /tmp/fc.sock -X PUT http://localhost/machine-config \
-d '{"vcpu_count": 1, "mem_size_mib": 256}'
curl --unix-socket /tmp/fc.sock -X PUT http://localhost/actions \
-d '{"action_type": "InstanceStart"}'In production you would not boot from scratch for every run. Firecracker can snapshot a running VM and restore it, and runners usually keep a pool of pre-booted guests per language so a submission is copied into a VM that is already up. The jailer binary that ships with Firecracker additionally puts the VMM process itself in a chroot, namespaces and cgroups, so even the monitor runs with minimal privileges.
A microVM is not a replacement for the limits in Layer 1. Inside the guest you still need a time limit, an output cap and a process limit, otherwise a run safely wastes its whole VM until the outer timeout fires.
Side by side
| Container (hardened) | gVisor | Firecracker microVM | |
|---|---|---|---|
| Kernel shared with host | Yes | No (user-space kernel) | No (own guest kernel) |
| Escape requires | One kernel bug reachable through seccomp | A Sentry bug plus a host call it permits | A guest bug plus a KVM or device-model bug |
| Start-up | Tens of milliseconds | Slightly slower than a container | About 125 ms cold; faster from a warm pool or snapshot |
| System-call-heavy workloads | Native speed | Noticeably slower | Native inside the guest |
| Compatibility | Full Linux | Most of Linux; some gaps | Full Linux in the guest |
| Needs | Any Linux host | Any Linux host | Bare metal or nested virtualisation (KVM) |
The last row decides more designs than security does. Firecracker needs /dev/kvm, which most cloud VMs do not expose; you need bare-metal instances or a provider that supports nested virtualisation. gVisor runs anywhere Docker does.
Things that bite in practice
- Measure time inside the sandbox, not around it. Pulling an image or booting a VM is not the user's runtime; report only the program's own execution time, or two identical submissions will get different verdicts under load.
- Disable swap for runs. With swap, a memory-hungry program slows down instead of being stopped, and turns a memory-limit verdict into a time-limit one.
- Tell an out-of-memory kill apart from a crash. The kernel's OOM killer sends SIGKILL; check the cgroup's memory events rather than guessing from the exit code, or memory-limit failures will be reported as runtime errors.
- Make compile steps obey limits too. Compilers can be made to consume huge memory or time with a few lines of template metaprogramming; a C++ compile without a limit is a denial-of-service vector.
- Never mount the Docker socket, host paths or credentials into a runner. A single mounted socket is equivalent to root on the host.
- Rate-limit before you isolate. Strong isolation makes each run expensive; anonymous callers should hit a request limit long before they reach a VM.
How to choose
- Your own code, CI jobs, trusted teammates: hardened containers are enough.
- Untrusted code on hosts where you cannot get KVM: gVisor gives the strongest isolation that runs on an ordinary cloud VM.
- Untrusted code at scale from anonymous users (online judges, public code runners, agent sandboxes): microVMs, if you can get bare metal or nested virtualisation.
ls-judge sits in the last group, so every test case runs in a fresh Firecracker microVM drawn from a warm pool, with the per-run limits from Layer 1 applied inside the guest and no network. The engineering tour covers how batching and verdicts work on top of that, and the runtimes page lists the languages it serves.