Kernel-enforced sandboxing for untrusted agent code in Rust | B4N1

Kernel-enforced sandboxing for untrusted agent code in Rust

17 hours ago · B4N1 AI Tiempo de lectura: 1 min

Threat model: what "untrusted agent code" actually means

An agent runtime that executes model-generated code faces a threat profile that differs from ordinary software engineering. The code being run is not a vetted dependency; it is an artifact produced by a probabilistic system, potentially steered by prompt injection, malformed inputs, or adversarial content retrieved from external sources. The operational goal is not to prove the code correct, but to bound the damage it can cause: which files it can read or modify, which network destinations it can reach, which processes it can signal, which kernel resources it can exhaust, and which new privileges it can acquire. A defensible posture assumes the sandboxed program will, at some point, execute arbitrary attacker-chosen instructions. Safety therefore cannot rest on the inner code's good behavior; it must rest on mechanisms the inner code cannot influence.

The word "kernel-enforced" is the crux. User-space checks — a wrapper that inspects a path before calling open, a policy layer that validates a syscall's arguments, a library convention that "nothing writes outside the workspace" — are advisory. They are subject to time-of-check/time-of-use races, symlink swaps, integer truncation, and outright bypass by code that does not use the wrapper. The only boundary that reliably constrains an arbitrary process is the operating system kernel, which sits on every syscall and every object access. Rust's contribution is not to replace that boundary but to implement the supervisor side correctly: safe abstractions around unsafe syscall wrappers, precise fd and environment hygiene, structured concurrency, and explicit lifetime management of child processes. This article analyzes the kernel mechanisms on Linux, how they compose, and the Rust-specific engineering required to use them soundly.

Rust memory safety is not a sandbox

Rust eliminates whole classes of bugs in the sandboxing supervisor itself: use-after-free, data races, uninitialized reads, and many buffer overflows. It does not, by itself, confine a workload. A sandboxed process can contain unsafe blocks, call C libraries through FFI, spawn subprocesses, execute build.rs scripts and procedural macros at compile time, or simply be a prebuilt binary that Rust never vetted. Even purely safe Rust can read any file the process's credentials allow, open sockets, allocate until OOM, fork until the system stalls, or send signals to peers in its process group. Memory safety of the inner program reduces exploitation probability; it does not reduce authority. Conversely, the supervisor can be perfectly safe Rust and still misconfigure a sandbox. Kernel enforcement exists precisely because it does not trust the inner code's language, runtime, or honesty. Two practical corollaries follow. First, if the agent's output is Rust source, compilation itself — rustc, cargo, build.rs, proc-macros, rustdoc tests — must run inside the sandbox, because compilation executes attacker-influenced code. Second, #![forbid(unsafe_code)] in the supervisor and minimal, audited FFI shims reduce the supervisor's own attack surface, but no forbid attribute can substitute for kernel confinement of the workload.

The syscall boundary as the choke point

On Linux, everything a process can do to the outside world is mediated by syscalls. A process has a set of credentials (uid/gid, supplementary groups, capabilities), a root and working directory, a set of open file descriptors, namespace memberships, a resource-limit context, and possibly a seccomp filter and LSM policy attached. The kernel checks these on every relevant operation. Kernel-enforced sandboxing is the discipline of arranging those contexts so that the set of reachable outcomes is small, then letting the kernel reject everything else. Rust changes none of these semantics; it only affects how faithfully the supervisor constructs them. The remaining question is which mechanisms to combine, in what order, and with what failure behavior.

seccomp-bpf: syscall filtering

seccomp-bpf attaches a classic-BPF program to a thread that is evaluated on every syscall, returning one of several verdicts: allow; reject with a specified errno; kill the process (or thread); generate a signal; or, with SECCOMP_RET_USER_NOTIF, hand the call to a userspace supervisor for mediation. The canonical configuration is an allowlist: permit the small set of syscalls the workload actually needs, deny everything else. Filters compare syscall number and scalar arguments; they are compiled once and installed with no_new_privs set (an unprivileged thread cannot install a filter otherwise). Filters are inherited across fork/clone, persist across execve, and stack cumulatively — later filters can only further restrict. seccomp is cheap, requires no root, and blocks entire syscall classes (for example io_uring_setup, bpf, userfaultfd, perf_event_open, ptrace, mount, kexec_load, init_module, setns, unshare, keyctl, pivot_root) for a workload that does not need them.

Two limitations matter analytically. First, seccomp cannot safely inspect user memory. Scalar arguments are captured atomically at syscall entry, but any pointer argument refers to memory the calling thread can concurrently mutate from another thread; checking *buf and then letting the kernel re-read it is a TOCTOU hole. Sound filters therefore restrict syscall number and non-pointer scalars, and leave object-level access decisions to an LSM. Second, seccomp is not itself an object policy: allowing openat does not restrict which paths may be opened; allowing kill does not restrict which pids may be signaled; allowing socket does not restrict networking. seccomp reduces attack surface; it does not provide filesystem or network confinement. SECCOMP_RET_USER_NOTIF can route selected syscalls to a supervisor, but the supervisor then inherits responsibility for the same race discipline, so it is best reserved for logging, policy telemetry, or emulation of a few well-understood calls, not as the primary confinement mechanism.

Landlock: unprivileged object-level access control

Landlock is a Linux security module designed precisely for unprivileged sandboxing. A thread builds a ruleset describing which accesses are permitted on which filesystem objects (for example read, write, execute, read-directory, refer/rename across directories, truncate), applies it to itself, and from then on the kernel checks every filesystem access against the ruleset — including accesses from syscalls no user-space wrapper can intercept, and including accesses performed after execve. No root or CAP_SYS_ADMIN is required. Successive restrict_self calls only narrow rights; they cannot widen them. Because checks happen in the kernel on the resolved object at access time, symlink races and .. traversal cannot escape the policy the way they can defeat user-space path filtering. Recent ABI versions extend scoping beyond the filesystem, adding network restrictions (such as binding or connecting sockets) and inter-process scoping, so a ruleset can be explicit about what crosses the boundary. Landlock is orthogonal to seccomp: seccomp reduces which syscalls exist; Landlock reduces which objects those syscalls can reach. A robust design uses both. The honest limitation is that Landlock mediates access; it does not replace resource limits, capability dropping, or network-namespace isolation, and a kernel without Landlock support means the restriction cannot be applied — which should be a startup error, not silent fallback.

Namespaces: changing what the process can see

Linux namespaces virtualize kernel resources per process group. Mount namespaces give a private filesystem view: bind mounts, read-only remounts, tmpfs, pivot_root, masking sensitive paths like /proc, and hiding everything not explicitly exposed. PID namespaces hide processes outside the namespace and renumber inside; a sandboxed process cannot signal a process it cannot see, though signal restrictions and dumpable/ptrace rules still apply. Network namespaces give a separate stack with no interfaces, or a veth pair to a controlled upstream; absent any interface, network syscalls cannot reach anywhere. User namespaces map uids so that "root inside" is unprivileged outside; combined with mount and PID namespaces they enable full rootless sandboxing, but kernels increasingly restrict unprivileged CLONE_NEWUSER, so the implementation must probe support and fail loud. IPC and UTS namespaces isolate shared-memory segments, semaphores, message queues, and hostname; cgroup namespaces hide the cgroup hierarchy. Ordering is load-bearing: create a user namespace first, then map ids, then create mount/network/PID namespaces, perform mounts, then apply Landlock and seccomp last, immediately before execve. Namespaces change visibility; they are not a substitute for seccomp (a syscall can still be invoked on visible objects) or for capability dropping.

Capabilities, no_new_privs, and privilege acquisition

Root historically bypassed permission checks; capabilities decompose that power. A sandboxed process should drop unnecessary capabilities from the effective, permitted, and inheritable sets, clear the bounding set so execve cannot re-acquire them, clear ambient capabilities, and set securebits appropriately. no_new_privs is the linchpin: once set, execve can never grant more privileges than the caller had — no setuid binaries, no file capabilities, no LSM transitions that increase privilege — and it is a prerequisite for installing seccomp unprivileged. no_new_privs persists across execve and cannot be unset. Its honest scope is privilege acquisition across exec; it does not by itself confine filesystem, network, or resource use. Rust code should set it via a minimal syscall wrapper, verify the return value, and treat failure as fatal rather than proceeding unsandboxed. A robust design combines no_new_privs, capability clearing, seccomp, and Landlock; any one alone leaves gaps.

Resource governance: cgroups v2 and rlimits

Confinement of authority is half the problem; availability is the other half. An untrusted process can fork-bomb, allocate memory until the OOM killer fires indiscriminately, spin CPU, fill the disk, or open file descriptors until nothing else runs. cgroups v2 applies limits to an entire process tree: memory.max, memory.swap.max, pids.max, cpu.max, io.max, plus OOM policy and cgroup-level kill. Process-local rlimits (RLIMIT_AS, RLIMIT_CPU, RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_FSIZE, RLIMIT_CORE=0, RLIMIT_STACK) add per-process bounds. rlimits are not a security boundary against a determined adversary — a process can often reset soft limits within hard limits and limits are per-process rather than per-tree — but they compose with cgroups. In Rust, limits are applied in the child before execve, and any failure to apply them should abort the child rather than run unbounded. A wall-clock timeout enforced by the supervisor, killing the whole process group, is a policy-level backstop, not a kernel feature, and should be paired with SIGKILL escalation after SIGTERM grace.

Architecture in Rust: supervisor, launcher, child

A robust Rust design separates concerns. A single-threaded supervisor owns policy; a small launcher process constructs the sandbox and then execves the untrusted program; the sandboxed child runs with no inherited fds, a cleared environment, a controlled working directory, its own process group (and typically session), closed stdio or explicitly routed pipes, and no ability to undo what was applied. Splitting launcher from child avoids the async-signal-safety trap in pre_exec. Rust's std::os::unix::process::CommandExt exposes pre_exec, process_group, exec, and related knobs, but pre_exec runs in a forked child of a possibly multithreaded parent where only async-signal-safe operations are permitted; allocating, locking, or panicking there can deadlock or corrupt state. Prefer fork+exec of a dedicated launcher, or re-exec self in a helper mode, so the sandbox-construction code runs in a fresh, single-threaded process. Rust's Stdio plumbing, CLOEXEC (default on Command), env_clear, and explicit fd-passing reduce accidental leaks; output capture should drain pipes on separate threads and cap bytes, because a child that fills a pipe and is not drained deadlocks against a supervisor that is waiting. The child must be reaped; on timeout, kill the group (negative pid), then wait, removing the whole process tree.

use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};

// Supervisor-side sketch. The launcher re-execs to a helper mode that
// applies namespaces -> caps -> no_new_privs -> Landlock -> seccomp,
// then execs the untrusted program. Failure anywhere is fatal.
let mut cmd = Command::new(launcher);
cmd.env_clear()
    .current_dir(workdir)
    .stdin(Stdio::null())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .process_group(0);          // own group; kill(-pid) on timeout
    // fds are CLOEXEC by construction; unshare/close_range happen
    // inside the launcher before execve.

let mut child = cmd.spawn()?;
// drain stdout/stderr concurrently with bounded buffers;
// on deadline: kill(-child.id(), SIGKILL); child.wait();

Ordering inside the launcher is the soundness argument. First create namespaces and mounts while still privileged enough; then drop capabilities and clear bounding/ambient sets; then no_new_privs; then apply Landlock rulesets; finally install the seccomp allowlist; then execve. Landlock and seccomp persist across execve, so ordering before exec is what makes them effective against the untrusted program; anything applied after exec is not the sandbox. Fail-closed is the universal rule: unknown kernel feature, missing Landlock ABI, seccomp installation failure, namespace creation failure, fd scrubbing failure, or inability to apply cgroup limits must abort the sandboxed run. Silent degradation — "if Landlock is unavailable, run anyway" — converts a security control into a liability.

Rust ecosystem and correctness pitfalls

Rust provides raw syscall access (libc, or thinner rustix-style layers) and, in production practice, safe wrappers around namespaces, seccomp, Landlock, and capabilities in maintained crates; the sound pattern is to keep FFI unsafe shims tiny, document SAFETY invariants, and fuzz the wrappers. CommandExt::pre_exec signature correctness and Send/Sync discipline around Arc in output drainers matter. Pitfalls worth naming analytically: TOCTOU on any user-space path check (Landlock exists partly to fix this); symlink races inside the sandbox root; seccomp arg filtering on pointers; filter ordering versus namespace/capability changes; leaving fds open (CLOEXEC, close_range, O_PATH); environment leakage (env_clear, removing LD_*, RUST_BACKTRACE, secrets); dynamic-loader concerns if the untrusted binary is dynamically linked against attacker-controlled paths; PR_SET_DUMPABLE and ptrace scoping; pid reuse and reaping; group-kill correctness; and forgetting that compile-time execution (build.rs, proc-macros) runs inside the boundary too. Every one of these is testable. A sandbox needs negative tests: attempt a forbidden syscall and expect EPERM or kill; write outside the allowed root; read a planted secret; escape via symlink and ..; rename across boundaries; signal pid 1; open a socket; re-acquire privilege via a setuid helper; exceed pids.max; and verify output truncation and group kill. The sandbox itself should be built as a separate, minimal, forbid(unsafe_code)-where-possible component whose policy is data, not code embedded in the agent runtime.

Layers beyond native sandboxing

Kernel primitives are the innermost layer, not the whole answer. WASM provides a complementary capability model: no ambient authority, explicit host imports, linear memory, and runtime-enforced fuel/epoch limits; wasm32-wasip1-style targets plus a WASI-capability runtime can sandbox untrusted logic without native syscalls at all, but any host call the runtime exposes must itself be safe, and WASM does not replace OS sandboxing for native artifacts. A plain container is not a security boundary by default: shared kernel, often root inside, broad capabilities, and host-networking mistakes defeat it. Syscall-interposition sandboxes (userspace-kernel designs) reduce kernel attack surface reachable by the workload; microVM isolation runs the workload in a separate guest kernel behind hardware virtualization, moving the boundary further away from the host. Sound architectures layer: inner Rust forbid(unsafe), then kernel sandboxing (seccomp + Landlock + namespaces + capabilities + no_new_privs + cgroups), then optional container hardening, then optional syscall interposition or microVM isolation for high-risk workloads. Each layer should fail closed; defense in depth is not redundancy, it is the assumption that any single layer can fail.

Conclusion

Kernel-enforced sandboxing for untrusted agent code in Rust is, at bottom, an ordering-and-lifetime discipline imposed around an arbitrary process. The kernel — not Rust type checking, not a user-space policy layer, not the agent's cooperation — is the enforcement boundary. seccomp-bpf reduces syscall surface; Landlock confines object access unprivileged; namespaces limit what is visible; capabilities and no_new_privs block privilege acquisition; cgroups v2 and rlimits bound resource consumption; process-group lifecycle, fd hygiene, environment sanitization, and reaping prevent leakage and escape through ordinary Unix mechanics. Rust's role is to implement the supervisor soundly: safe wrappers around unsafe, CLOEXEC, env_clear, a dedicated single-threaded launcher before execve, pre_exec used with async-signal-safety awareness, output draining, and process_group + group kill on timeout. The analytically honest posture is fail-closed: any unsupported kernel feature, any inability to apply a restriction, any setup error aborts the run. Rust memory safety improves the supervisor; it never substitutes for kernel confinement of workloads that may contain unsafe, FFI, subprocesses, compile-time execution, or entirely foreign binaries. For agents generating and executing code, kernel-enforced sandboxing in a small, auditable Rust launcher is the appropriate baseline, with WASM, container hardening, or microVM isolation added in proportion to the adversary.


¿Tienes preguntas?

Hablemos

Contáctame en LinkedIn