Skip to content

Sandboxing and Confinement

A sandbox limits the damage that a defect or an attacker can cause in a running program. This guide tells you how to confine a Rust application with operating system (OS) controls. Use two independent layers. The first layer is a sandbox that the binary applies to itself at startup. The second layer is a policy that you ship with the package and that the OS applies. The two layers fail independently, so one layer stays active when the other layer fails.

Threat model and when to sandbox

A sandbox does not prevent a defect. It limits what a compromised process can do after the defect. Identify the assets and trust boundaries first. Refer to Secure development lifecycle.

Add a sandbox when one or more of these conditions apply:

  • The program parses untrusted input, such as files, network frames, archives, images, or documents.
  • The program operates as a long-running service or daemon.
  • The program loads plugins or starts child processes that run untrusted code.
  • The program has access to secrets or user files.

Apply these principles to all sandboxes:

  • Deny by default. Allow only the files, ports, and system calls that the program uses.
  • Make a sandbox failure visible. Do not let a configuration error make the sandbox weaker without a log message.
  • Apply the sandbox in the application main. Do not apply a sandbox from a library crate. A library can export a rule set that the application adds to its policy.
  • Keep each policy file in the same repository as the code.
  • Do not make the security of the program depend on a tool that the operator installs. Document these tools as options.

Memory safety does not make a sandbox unnecessary. Logic defects, unsafe code, C libraries, and compromised dependencies can give an attacker control. Refer to Supply chain security.

In-process sandbox on Linux

An unprivileged Linux process can confine itself. Root, setuid helpers, and user namespaces are not necessary. Use three kernel features:

Feature Controls Rust crate
no_new_privs Stops privilege gain through setuid binaries and file capabilities after execve rustix (thread::set_no_new_privs), or the landlock crate
Landlock File system access, TCP and UDP ports, abstract Unix sockets, and signals landlock
seccomp-bpf The system calls that the process can make seccompiler or libseccomp

Landlock and seccomp are different controls. Landlock controls access to resources. Seccomp decreases the kernel attack surface. Use the two controls together.

Landlock

Landlock is a deny-by-default allowlist. Each kernel release can add new access rights. The ABI version tells you which rights the kernel supports.

ABI Mainline kernel New controls
1 5.13 File system access rights
2 5.19 Rename and link across directories (Refer)
3 6.2 File truncation
4 6.7 TCP bind and connect for each port
5 6.10 ioctl on device files
6 6.12 Scopes for abstract Unix sockets and signals
7 6.15 Audit log control
8 7.0 Enforcement on all threads (TSYNC)
9 7.1 Pathname Unix sockets
10 7.2 UDP bind and send, and log flags
11 7.3 LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS: set no_new_privs only if enforcement succeeds
12 7.4 (not released in early December 2026) Capability and namespace use (unshare, clone3, setns)

Distribution kernels do not follow the mainline numbers. For example, RHEL 9.6 has a 5.14 kernel with ABI 5. Do not calculate the ABI from uname.

Use the official landlock crate from the landlock-lsm organization. Version 0.4.8 supports ABI 1 to ABI 10. It does not support ABI 11 or ABI 12. In the past, a new ABI came to the crate 1.5 to 3.5 months after the kernel release. Before you use a newer ABI, examine the crate changelog.

Set one constant for the highest ABI that you wrote and tested the code for. Rights that later ABIs add stay allowed until you change the constant. Change the constant only in a reviewed pull request with tests.

The crate has three compatibility levels (CompatLevel):

Level Result on a kernel that does not support a right Use
BestEffort (default) The crate drops the right and continues. Rights that give more protection but that the program can operate without
SoftRequirement The crate drops the full request and continues. Optional groups of rules
HardRequirement The call returns an error. Rights that your threat model depends on, and all tests

Do the check on the result of restrict_self(). The ruleset field is FullyEnforced, PartiallyEnforced, or NotEnforced. Write a log message if the status is not FullyEnforced.

use std::path::Path;
use landlock::{    path_beneath_rules, Access, AccessFs, AccessNet, CompatLevel, Compatible, NetPort,    Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetError, RulesetStatus, Scope, ABI,};
/// The highest Landlock ABI that this code was written and tested for.const LANDLOCK_ABI: ABI = ABI::V10;
/// Confines file system and network access. `fs_level` is `BestEffort` in/// production and `HardRequirement` in tests.pub fn apply_landlock(data_dir: &Path, fs_level: CompatLevel) -> Result<RulesetStatus, RulesetError> {    let abi = LANDLOCK_ABI;    let status = Ruleset::default()        // The threat model depends on denial of outbound TCP. Fail on        // kernels before ABI 4. ConnectTcp does not control UDP.        .set_compatibility(CompatLevel::HardRequirement)        .handle_access(AccessNet::ConnectTcp)?        .set_compatibility(fs_level)        .handle_access(AccessFs::from_all(abi))?        .scope(Scope::AbstractUnixSocket | Scope::Signal)?        .create()?        .add_rules(path_beneath_rules(["/usr", "/etc/ssl"], AccessFs::from_read(abi)))?        .add_rules(path_beneath_rules([data_dir], AccessFs::from_all(abi)))?        .add_rule(NetPort::new(443, AccessNet::ConnectTcp))?        // `restrict_self` also sets no_new_privs by default.        .restrict_self()?;
    if status.ruleset != RulesetStatus::FullyEnforced {        eprintln!("landlock: sandbox is {:?}", status.ruleset);    }    Ok(status.ruleset)}

Landlock has limits. Know them before you depend on it:

  • A process can have a maximum of 16 stacked Landlock layers. Do not apply a new ruleset for each request.
  • Landlock does not control stat, chdir, chmod, chown, flock, or access. It does not deny chroot.
  • The network rules control only TCP and UDP ports. Use seccomp to block raw sockets, AF_PACKET, netlink, and other socket families.
  • The example controls only TCP connects. It does not control UDP binds or sends. ABI 10 adds LANDLOCK_ACCESS_NET_BIND_UDP and LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP. On older kernels, use seccomp to control UDP. Refer to the kernel Landlock documentation.

Seccomp

Seccomp-bpf filters system calls before the kernel does the work. Select one of these crates:

Crate Use Notes
seccompiler Default for new code Pure Rust. Works with musl. Supports x86_64, aarch64, and riscv64.
libseccomp Many architectures, or syscall names that resolve at run time Bindings to the C library
extrasafe Prototypes only x86_64 only. No changes since July 2024.

The seccompiler code is now in the rust-vmm monorepo with the same crate name. Version 0.5.0 has syscall tables up to kernel 6.12. For newer system calls, use the libc constants.

Read the kernel documentation for seccomp before you write a filter (seccomp_filter):

  • Always check the architecture value. seccompiler adds this check from the TargetArch value.
  • Do not allow ptrace in a seccomp sandbox.
  • Do not use KillThread as the action. It can stop one thread and leave the process in a bad state.
  • Return ENOSYS for system calls that the filter does not allow. With ENOSYS, libc can use a fallback call, for example clone after clone3.

seccompiler 0.5 has one match action and one mismatch action for each filter. This example allows a list of system calls and returns ENOSYS for all other calls.

use std::collections::BTreeMap;
use seccompiler::{BpfProgram, SeccompAction, SeccompFilter, SeccompRule};
pub fn build_filter() -> Result<BpfProgram, Box<dyn std::error::Error>> {    let mut allowed: Vec<i64> = vec![        libc::SYS_read,        libc::SYS_write,        libc::SYS_close,        libc::SYS_futex,        libc::SYS_mmap,        libc::SYS_munmap,        libc::SYS_madvise,        libc::SYS_brk,        libc::SYS_sigaltstack,        libc::SYS_rt_sigreturn,        libc::SYS_exit,        libc::SYS_exit_group,        // Add the calls from the strace sweep for each target.    ];    #[cfg(target_arch = "x86_64")]    allowed.push(libc::SYS_poll);    #[cfg(target_arch = "aarch64")]    allowed.push(libc::SYS_ppoll);
    // An empty rule vector matches the call with all arguments.    let rules: BTreeMap<i64, Vec<SeccompRule>> =        allowed.into_iter().map(|nr| (nr, vec![])).collect();
    let filter = SeccompFilter::new(        rules,        SeccompAction::Errno(libc::ENOSYS as u32), // mismatch action        SeccompAction::Allow,                      // match action        std::env::consts::ARCH.try_into()?,    )?;    Ok(filter.try_into()?)}

Apply the program with seccompiler::apply_filter_all_threads(&program). This function uses the kernel TSYNC flag. Use seccompiler::apply_filter to confine only the calling thread. The kernel accepts a filter only after the process sets no_new_privs or has CAP_SYS_ADMIN.

System calls that you do not call directly

Most allowlists fail on system calls from libc, the allocator, the Rust standard library, or the async runtime. Examples on glibc 2.44 and x86_64:

  • An empty fn main() {} makes rseq, getrandom, sched_getaffinity, poll, sigaltstack, prlimit64, and set_robust_list calls.
  • A new thread adds clone3, futex, and madvise(MADV_GUARD_INSTALL) for the stack guard page. A filter that limits madvise to old advice values stops thread creation.
  • fs::metadata uses statx. Command::status uses clone3(CLONE_VM|CLONE_VFORK).
  • tokio adds epoll_*, eventfd2, socketpair, pidfd_open, prctl for thread names, and sched_yield.

The C library and the architecture change the list:

Target Differences
glibc Uses clone3, rseq, statx, set_robust_list, and prlimit64
musl Uses none of the glibc calls above. Uses clone for threads and for Command, and pipe2 and epoll_pwait. On x86_64, uses open, stat, and fstat.
aarch64 Has no poll, open, stat, or access system calls. Uses ppoll, openat, newfstatat, and faccessat.

A musl allowlist is a different list, not a smaller copy of the glibc list. For example, the Firecracker musl filter has no clone3, rseq, or statx. Do not copy it for a glibc binary. No authoritative list for the Rust standard library exists. Make your own list:

  1. Build the binary for each target triple that you ship.
  2. Run the integration tests under strace -f -c for each target.
  3. Add the result to the allowlist for that target.
  4. Do the sweep again in CI when you update Rust, libc, or tokio.

qemu-user gives incorrect results for some aarch64 calls, such as clone3. Make the aarch64 list on aarch64 hardware or in a full VM.

Startup order

The order of the steps is more important than each single setting.

  1. Do all setup that uses broad access. Read the configuration, load TLS certificates, open files, and bind sockets. Landlock does not remove access from a file descriptor that is already open. Before step 4, close each descriptor that the service does not need after setup. For each descriptor that you keep, such as the listener, know what access it gives.
  2. Drop privileges. Clear capabilities with the caps crate. Set RLIMIT_CORE to 0 and make the process non-dumpable with rustix or nix.
  3. Set no_new_privs.
  4. Apply Landlock.
  5. Apply seccomp last. A seccomp filter that you apply first can block the Landlock system calls.
  6. Start the tokio runtime, rayon, or other worker threads.

Do not use #[tokio::main] in a sandboxed binary. The macro starts the runtime and its worker threads before your main code runs. Build the runtime after the sandbox.

use landlock::CompatLevel;
fn main() -> Result<(), Box<dyn std::error::Error>> {    // 1. Setup with broad access.    let config = load_config()?;    let listener = std::net::TcpListener::bind(config.addr)?;
    // 2. Drop capabilities if the process has any. `caps::clear` calls    //    `capset`, which a unit with `SystemCallFilter=~@privileged` blocks.    if !caps::read(None, caps::CapSet::Permitted)?.is_empty() {        caps::clear(None, caps::CapSet::Effective)?;        caps::clear(None, caps::CapSet::Permitted)?;    }
    // 3. no_new_privs.    rustix::thread::set_no_new_privs(true)?;
    // 4. Landlock.    apply_landlock(&config.data_dir, CompatLevel::BestEffort)?;
    // 5. Seccomp last.    seccompiler::apply_filter_all_threads(&build_filter()?)?;
    // 6. Start threads only now.    let runtime = tokio::runtime::Builder::new_multi_thread()        .enable_all()        .build()?;    runtime.block_on(serve(listener))}

Firecracker uses a different design. It applies a filter to each thread before the untrusted phase of that thread.

Threads and TSYNC

Landlock and seccomp attach to the calling thread. New threads and child processes get the same restrictions. Threads that already exist do not get them, unless you use TSYNC.

  • Before Landlock ABI 8, sibling threads stay unconfined.
  • all_threads(true) (from the RestrictSelfAttr trait) requests TSYNC. With BestEffort, the crate silently drops this request on kernels before ABI 8. If TSYNC is necessary, set HardRequirement before the call.
  • seccompiler::apply_filter_all_threads returns an error if a thread already has a different filter.

The safest rule is to apply the sandbox before the process starts a second thread.

Tests for the sandbox

A process cannot remove its sandbox. Thus, each sandbox test must operate in a new process.

  • Use cargo-nextest. It runs each test in a separate process. Refer to Testing.
  • In tests, use CompatLevel::HardRequirement and assert that the status is FullyEnforced.
  • Do a test of the denial, not only the status. Try an access that the policy does not allow and assert the error.

Mark each kernel-specific test #[ignore]. A normal cargo nextest run then skips them, and each VM job selects only the test for its kernel.

use landlock::{CompatLevel, RulesetStatus};
// Run only in the VM with a kernel at ABI 9 or later.#[test]#[ignore = "needs a kernel at Landlock ABI 9 or later"]fn landlock_is_fully_enforced() {    let dir = tempfile::tempdir().expect("create temp dir");    let status = apply_landlock(dir.path(), CompatLevel::HardRequirement)        .expect("apply landlock");    assert_eq!(status, RulesetStatus::FullyEnforced);
    let err = std::fs::read_to_string("/etc/passwd").expect_err("read must fail");    assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);}

GitHub-hosted runners can have a kernel with an old Landlock ABI. Run the kernel-specific tests in VMs with known kernels.

The example policy requests filesystem rights through ABI 9, TCP connect (ABI 4), and the ABI 6 scopes. Thus, a kernel at ABI 9 or later (Linux 7.1 or later) reports FullyEnforced. A kernel at ABI 4 to ABI 8 (Linux 6.7 to 7.0) reports PartiallyEnforced with CompatLevel::BestEffort. On that kernel, HardRequirement returns an error, so use the production level. On a kernel before ABI 4, apply_landlock returns an error, because the example makes network denial a hard requirement.

VM kernel Command Expected result
Linux 7.1 or later cargo nextest run --run-ignored only -E 'test(landlock_is_fully_enforced)' FullyEnforced
Your oldest supported kernel, Linux 6.7 to 7.0 cargo nextest run --run-ignored only -E 'test(landlock_is_partially_enforced)' PartiallyEnforced

Refer to CI/CD.

// Run only in the VM with a kernel at ABI 4 to ABI 8.#[test]#[ignore = "needs a kernel at Landlock ABI 4 to 8"]fn landlock_is_partially_enforced() {    let dir = tempfile::tempdir().expect("create temp dir");    let status = apply_landlock(dir.path(), CompatLevel::BestEffort)        .expect("apply landlock");    assert_eq!(status, RulesetStatus::PartiallyEnforced);
    let err = std::fs::read_to_string("/etc/passwd").expect_err("read must fail");    assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);}

Packaged confinement

The package can carry a policy that the OS applies when the program starts. This policy stays active if the in-process sandbox has a defect or the kernel is old. Refer to Packaging for the package formats.

systemd units

A hardened systemd unit gives the most protection for the least work for a daemon. It adds no dependency. Ship a hardened unit with each service.

[Unit]Description=myapp daemon
[Service]ExecStart=/usr/bin/myapp --config /etc/myapp/config.tomlDynamicUser=yesStateDirectory=myappCacheDirectory=myappLogsDirectory=myappConfigurationDirectory=myappCapabilityBoundingSet=NoNewPrivileges=yesProtectSystem=strictProtectHome=yesPrivateTmp=yesPrivateDevices=yesProtectKernelTunables=yesProtectKernelModules=yesProtectKernelLogs=yesProtectControlGroups=yesProtectClock=yesProtectHostname=yesProtectProc=invisibleProcSubset=pidRestrictNamespaces=yesRestrictRealtime=yesRestrictSUIDSGID=yesLockPersonality=yesMemoryDenyWriteExecute=yesRemoveIPC=yesUMask=0077RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6SystemCallArchitectures=nativeSystemCallFilter=@system-service @sandboxSystemCallFilter=~@privileged @resourcesSystemCallErrorNumber=EPERM
[Install]WantedBy=multi-user.target

SystemCallFilter=~@privileged blocks capset. Under this unit, do not call caps::clear unconditionally. The unit already removes all capabilities with CapabilityBoundingSet=. The @sandbox group allows the Landlock and seccomp system calls. Some systemd versions do not include them in @system-service. systemd 254 added @sandbox. On older systemd, replace @sandbox with landlock_create_ruleset landlock_add_rule landlock_restrict_self seccomp.

Change the unit for the service:

  • If the service binds a port below 1024, set CapabilityBoundingSet=CAP_NET_BIND_SERVICE and AmbientCapabilities=CAP_NET_BIND_SERVICE. The startup example then calls caps::clear after the bind. Add the line SystemCallFilter=capset after the ~@privileged line, so that the process can drop the capability.
  • If the service does not use the network, set PrivateNetwork=yes. If the peers are known, set IPAddressDeny=any and IPAddressAllow= for the peers.
  • MemoryDenyWriteExecute=yes is correct for Rust code without a JIT compiler.

Newer systemd releases add more directives. For example, systemd 260 adds PrivateUsers=managed, which gives the unit a transient range of UIDs. systemd 261 adds RestrictFileSystemAccess=, which requires BPF-LSM. Examine the systemd NEWS file for the versions that your target distributions ship. No systemd directive applies Landlock.

Check the unit in CI with systemd-analyze security. The --offline=yes option reads the unit file without a running systemd.

Terminal window
systemd-analyze security --offline=yes --threshold=20 packaging/myapp.service

The command fails if the exposure score is more than the threshold. The command shows the score from 0.0 to 10.0, but --threshold= uses a scale from 0 to 100. Thus, --threshold=20 is a limit of 2.0. systemd gives no recommended threshold. A score of 2.0 or less is a good target for a new daemon. The score measures only the unit file, not the code. PrivateNetwork= and DynamicUser= have the largest weights (analyze-security.c).

Containers

For a server image, use these rules:

  • Run the process as a non-root user.
  • Make sure that the image operates under rootless Podman with the default seccomp profile.
  • Do not require --privileged or seccomp=unconfined.
  • Drop all capabilities that the program does not use.

The Docker default seccomp profile blocks approximately 44 dangerous system calls, for example unshare, mount, ptrace, and io_uring_*. Do not change it. For a single-host Podman service, use a Quadlet unit with NoNewPrivileges=, DropCapability=all, ReadOnly=, and UserNS=.

A distroless image has a smaller attack surface, but it is not a sandbox. Refer to Web APIs and Packaging.

Flatpak and Snap

For GUI applications, the Flatpak default sandbox is strong. The application can write only to its own ~/.var/app directory. It has no network, no devices other than /dev/null, no X11, and no system bus (Flatpak sandbox permissions).

  • Keep finish-args small.
  • Use portals and read-only (:ro) XDG directories. Do not use --filesystem=home or --filesystem=host.
  • Do not use --socket=system-bus or --socket=session-bus. The Flatpak documentation calls them a security risk.
  • --share=network also gives access to host abstract Unix sockets.

Snap strict confinement uses AppArmor, seccomp, device cgroups, and mount namespaces. It depends on AppArmor support in the distribution. Classic snaps require a manual store review. Refer to Desktop GUI applications and Packaging.

Mandatory access control policy

SELinux and AppArmor confine a program from outside the process with a policy that the distribution loads. This policy stays active after an attacker gets full control of the process. In mainline Linux, SELinux and AppArmor cannot operate together. Landlock can operate with each of them.

Distribution family Default MAC Ship
Fedora, RHEL, CentOS Stream SELinux <pkg>-selinux subpackage
openSUSE Tumbleweed, Leap 16.0, SLES 16.0 SELinux <pkg>-selinux subpackage
Debian, Ubuntu AppArmor AppArmor profile
Arch Linux, NixOS None Nothing. Landlock and seccomp operate.

SUSE uses SELinux for new installations (Leap 16.0 release notes).

SELinux

On Fedora and RHEL, ship the policy in a separate noarch <pkg>-selinux subpackage (Fedora wiki: IndependentPolicy):

  • Build the module from .te, .fc, and .if files with /usr/share/selinux/devel/Makefile.
  • Install the module at priority 200 with the %selinux_relabel_pre, %selinux_modules_install, and %selinux_relabel_post macros.
  • Add a rich dependency in the main package. Systems without SELinux and containers then do not install the subpackage.
Requires: (%{name}-selinux if selinux-policy-%{selinuxtype})

container-selinux and mysql-selinux use this pattern.

Note: The Fedora IndependentPolicy page is a draft. The Fedora Packaging Committee did not approve it (FPC issue #726). It is the usual practice, not a requirement. Speak to the Fedora SELinux team before you submit a policy module.

AppArmor

On Debian and Ubuntu, install the profile into /etc/apparmor.d/. Call dh_apparmor with --profile-name= in debian/rules. This command creates the /etc/apparmor.d/local/<profile> file for local changes. It also loads the profile again in postinst.

abi <abi/4.0>,include <tunables/global>
profile myapp /usr/bin/myapp {  include <abstractions/base>  include <abstractions/ssl_certs>
  /usr/bin/myapp mr,  /etc/myapp/** r,  /var/lib/myapp/** rwk,  network inet stream,  network inet6 stream,
  include if exists <local/myapp>}

AppArmor 4.1 is the long-term support line. AppArmor 5.0 adds features that older releases do not parse (AppArmor releases). For a profile that must load on Ubuntu 24.04, use 4.x syntax.

Authoring and tests for MAC policy

  • Start with sepolicy generate for SELinux or aa-genprof for AppArmor.
  • Do not ship the output of audit2allow or aa-logprof without a review. These tools change each logged denial into an allow rule. A denial can come from a compromised process.
  • Do the MAC tests in a VM with the LSM in enforcing mode. A container cannot load a host policy. Run the integration tests and fail the job on each AVC record or apparmor="DENIED" log line.

Ubuntu user namespace restriction

Since Ubuntu 23.10, and by default in 24.04 LTS, an unprivileged process can create a user namespace only if its AppArmor profile has a userns, rule (Canonical blog, LWN). Tools that use bubblewrap, Chromium, and Electron fail without a profile.

  • If your binary or a helper creates user namespaces, ship an AppArmor profile in the .deb package. Add the userns, rule for the installed path.
  • AppImages and tarballs cannot install a profile without root.
  • Do not tell users to use --no-sandbox or to disable the sysctl.

Landlock and seccomp are not affected by this restriction, because they do not create a namespace.

BPF-LSM

A BPF-LSM program requires CAP_BPF or CAP_SYS_ADMIN and a resident agent. It is a system-wide policy for fleet tools, not a sandbox for one program. Ubuntu 24.04 does not enable BPF-LSM.

Sandbox wrappers

Wrappers apply namespaces and seccomp when they start a program. Operators select these tools. Do not make your program depend on them.

Tool Best fit Privilege model Ship it?
bubblewrap Internal helpers and build steps Unprivileged user namespaces only, since 0.12.0 Only as an internal helper
firejail Desktop hardening by the user setuid root No. At most, send a profile upstream.
nsjail Untrusted code with strict CPU, memory, and time limits User namespaces, or root and then a privilege drop No. Document it.
minijail ChromeOS and Android services Library and launcher No. Its Rust bindings are not on crates.io.
gVisor Adversarial multi-tenant code User-space kernel as an OCI runtime No. Document it.

bubblewrap is a small tool with no built-in policy. Flatpak uses it. After two CVEs in 2026, bubblewrap removed setuid builds in 0.12.0 (bubblewrap releases).

firejail is a setuid-root binary. It has a history of local root vulnerabilities, for example CVE-2022-31214. Its installation adds a privilege escalation surface for all users. Do not make your project depend on firejail.

If you document nsjail, specify version 3.6 or later. Version 3.5 could make policies weaker (nsjail releases). gVisor keeps most of the host kernel out of reach, but some ioctl calls and raw sockets do not operate. Use gVisor or a microVM only when the product runs adversarial code.

Other operating systems

No maintained cross-platform Rust sandbox crate is ready for production. gaol has had no release since 2019, and birdcage is archived. nono is active but pre-1.0 and has no Windows backend. If you use nono, pin the exact version.

Write one project-owned policy type with one small backend for each OS. OpenAI Codex and Anthropic srt use this design.

OS Mechanism Rust crate Use
OpenBSD unveil(2), pledge(2) unveil, pledge Call unveil for each path, then unveil(NULL, NULL) to lock the list. Then call pledge with the smallest set of promises.
FreeBSD Capsicum capability mode capsicum Open all descriptors, limit them with RightsBuilder, and then call enter().
macOS App Sandbox entitlements None The supported method. Requires a signed bundle.
macOS Seatbelt (sandbox-exec) None Deprecated. Use only as an additional layer.
Windows Mitigation policies, restricted tokens, Job objects windows, win32job Confine a child process.
All Capability-based handles cap-std Prevents path traversal and symlink escapes
All WebAssembly with WASI wasmtime Plugins get only the directories that the host gives

macOS

Apple supports only the App Sandbox. The Mac App Store requires it. An embedded helper tool must have only the com.apple.security.app-sandbox and com.apple.security.inherit entitlements (Apple Developer Forums).

sandbox-exec and <sandbox.h> are deprecated, and Apple does not support them (Apple Developer Forums). sandbox-exec operates on macOS 26, and Codex and Homebrew use it. If you use Seatbelt profiles, obey these rules:

  • Use Seatbelt as an additional layer, never as the only control.
  • Call /usr/bin/sandbox-exec with an absolute path. Then PATH cannot change the binary.
  • Do the sandbox tests again on each macOS 26.x point release.

No maintained Rust crate wraps sandbox_init safely. The crates.io seatbelt crate is not related to the macOS sandbox.

The Hardened Runtime that notarization requires is an exploit mitigation, not a resource sandbox. Refer to Packaging for code signing and notarization.

Windows

A running Windows process cannot effectively decrease its own file access. Use these controls:

  • Early in main, call SetProcessMitigationPolicy. Set DynamicCode if the program has no JIT compiler. Also set ImageLoad, Signature, StrictHandleCheck, and ExtensionPointDisable.
  • Start untrusted work in a child process with a restricted token from CreateRestrictedToken. Put the child in a Job object.
  • AppContainer gives strong isolation, but it can stop tools that use paths in the user profile. The AppContainer crate rappct is new and has no known audit.

The Codex Windows sandbox is an example. It uses a dedicated sandbox user, a WRITE_RESTRICTED token, and explicit ACLs. An Authenticode signature does not confine the program.

cap-std and WASI

cap-std replaces ambient std::fs and std::net access with handles. A Dir handle can open only paths below it. Open the handles at startup and give them to the code that uses them. Block std::fs calls on untrusted paths with the Clippy disallowed_methods lint.

Wasmtime with WASI runs plugins with no direct system calls. These two layers do not stop native code in the same process that calls libc directly. Use them with an OS sandbox.

The layers start with the least expensive and most general controls. Each layer assumes that the layer above it can fail.

Layer Applies to Action CI check
0. Capability-based code All crates Use cap-std Dir handles. Block std::fs on untrusted paths. Path traversal tests and lints
1. Startup hygiene All binaries Make the process non-dumpable (Linux) or set PT_DENY_ATTACH (macOS). Set RLIMIT_CORE=0. Remove LD_* and DYLD_* variables. Drop capabilities. Set Windows mitigation policies. Smoke test
2. In-process kernel sandbox Binaries that read untrusted input Linux: Landlock, then seccomp, before threads start. OpenBSD: unveil and pledge. FreeBSD: Capsicum. FullyEnforced tests, strace sweep for each target, oldest kernel in a VM
3. Packaged confinement Daemons, GUI applications, server images Hardened systemd unit, small Flatpak finish-args, non-root image systemd-analyze security --offline=yes --threshold=N, rootless Podman run
4. Distribution MAC policy Distribution packages, and binaries that create user namespaces <pkg>-selinux subpackage, AppArmor profile VM job in enforcing mode
5. Isolation of untrusted children or plugins Agents, build tools, plugin hosts Broker process with a sandboxed child, network through a proxy, WASI for plugins Escape tests on each OS
6. Operator options Operators gVisor, nsjail, microVMs None. Document them.

The Codex process-hardening crate is an example of layer 1.

Apply these rules to the full stack:

  • Put all backends behind one project-owned Policy type. Report the enforcement level for each OS.
  • Treat an incorrect sandbox configuration as a fatal error.
  • Review the policy files in each release. Refer to Release automation.
  • Add a sandbox policy review to each change to a trust boundary. Refer to Development and release checks.

For a tool that runs untrusted children, use a broker design. A privileged parent keeps the secrets and the network access. The child runs in the OS sandbox with no network. A proxy in the parent sends the network traffic of the child and enforces a domain allowlist. Kernel controls cannot filter by domain name. Refer to CLI and TUI applications.

Checklist

Further reading