14. Operating-System Sandboxes

The sandbox is the control Codex trusts; approval only decides when a command may leave it. The codex-sandboxing crate compiles one permission profile into a per-platform strategy: a generated Seatbelt policy on macOS, bubblewrap plus seccomp on Linux, and a restricted token, a dedicated sandbox user, or MXC on Windows.

Chapter 13 showed that under the default on-request policy, a command that no rule matches runs without a prompt. That is safe only because the command runs inside an operating-system sandbox that the command cannot talk its way out of. A prompt asks a person to predict what make test will do. A sandbox lets the kernel refuse the write to ~/.ssh when it happens.

This chapter explains how Codex builds that sandbox on each platform: why it comes first, how the codex-sandboxing crate selects a backend, and how macOS, Linux, and Windows enforce the profile. It then covers the exec-server’s integrity checks, the process hardening some Codex binaries apply to themselves, and codex sandbox, which lets you try a policy by hand.

The picture

The tool orchestrator hands a permission profile to the SandboxManager, which selects a backend: on macOS it generates an SBPL policy and runs /usr/bin/sandbox-exec; on Linux it runs the codex-linux-sandbox helper, which builds a bubblewrap view, re-executes itself inside it, installs seccomp, and runs the command; on Windows it uses a restricted token, an elevated runner under a sandbox user, or the MXC SDK.

ToolOrchestrator decides that a command needs a sandbox and passes the active PermissionProfile to SandboxManager::transform, which picks one backend per command. On macOS the profile becomes policy text for sandbox-exec. On Linux the command is wrapped in a call to codex-linux-sandbox, which builds a bubblewrap view and installs a seccomp filter. On Windows, the unelevated level spawns the command directly with a restricted token, the elevated level hands the spawn to a runner process that runs as a dedicated sandbox user, and the MXC backend (dashed) calls a native SDK.

Why the sandbox comes first

The code states its trust order in comments. Under never, render_decision_for_unmatched_command_for_platform allows an unmatched command with the note “We allow the command to run, relying on the sandbox for protection.” Under on-request with a restricted filesystem, it skips the prompt and says “let the sandbox enforce restrictions without a user prompt.” assess_patch_safety keeps even an auto-approved patch inside the sandbox, because its paths may be “hard links to files outside the writable roots.”

Two reasons for this order are the book’s reading of the design. A static check sees text, while the sandbox sees effects: a script can build a path at run time or call a helper that writes elsewhere. And a prompt is worth more when it is rare. The third reason is in the code: approval is reserved for leaving the sandbox. require_escalated, with_additional_permissions, and the unsandboxed retry after a denial each need a decision, and Chapter 13 showed that a Guardian verdict on the sandboxed command does not carry over to the escape.

The sandbox also produces the signal that starts an escalation. After a sandboxed run, is_likely_sandbox_denied in codex-rs/sandboxing/src/denial.rs decides whether a failure looks like a denial:

Here is the SandboxType, is the exit code, and is true when stdout, stderr, or the aggregated output contains one of seven keywords, matched without case: “operation not permitted”, “permission denied”, “read-only file system”, “seccomp”, “sandbox”, “landlock”, or “failed to write file”. The early return for exit codes 2, 126, and 127 runs after the keyword check, so it never hides a keyword match. The doc comment admits the limit: “We don’t have a fully deterministic way to tell if our command failed because of the sandbox.” A test that prints “permission denied” for its own reasons looks like a real denial.

One crate, one strategy per platform

Choosing a backend

SandboxType in codex-rs/protocol/src/sandbox.rs names the five possible outcomes: None, MacosSeatbelt, LinuxSeccomp, WindowsRestrictedToken, and WindowsMxc. get_platform_sandbox in codex-rs/sandboxing/src/manager.rs returns Seatbelt on macOS and LinuxSeccomp on Linux unconditionally, but returns the Windows backend only when the Windows sandbox is enabled.

Each tool declares a SandboxablePreference: Auto, Require, or Forbid. Under Auto, should_require_platform_sandbox_for_convention in codex-rs/sandboxing/src/policy_transforms.rs decides. Managed network requirements always need a sandbox. A restricted network needs one unless an external caller isolates the filesystem. With network enabled, only a restricted filesystem without full-disk write needs one. So :danger-full-access runs unsandboxed, and :workspace with network off is always sandboxed. If a tool says Require and the host has no backend, transform fails with SandboxTransformError::SandboxUnavailable rather than running the command bare.

The strategy seam

SandboxManager::transform turns a command and a profile into a SandboxExecRequest, the argv and environment to launch. After selection, it delegates to one implementation of a small trait in manager.rs:

pub(super) trait SandboxBackend {
    fn prepare(
        &mut self,
        exec: &mut SandboxExecRequest,
        cwd: &AbsolutePathBuf,
        policy_cwd: &AbsolutePathBuf,
    ) -> Result<(), SandboxTransformError>;
}

Seatbelt, Linux, WindowsToken, and Mxc implement it. This is the strategy pattern: the orchestrator, approvals, and retries never branch on the operating system, and a new backend needs only a new prepare that rewrites the request in place.

A doc comment on SandboxExecRequest fixes where this happens: “Build this only at the execution boundary: in exec-server, or in its logical equivalent within app-server.” On a remote executor, the exec-server calls transform in prepare_exec_request_with_telemetry, so paths and the available backend come from the machine that runs the command (see Chapter 10).

macOS: Seatbelt

A fixed binary and a generated policy

Seatbelt is the macOS kernel sandbox, driven by policies in the Sandbox Profile Language (SBPL). Codex runs it through one binary, named by a constant in codex-rs/sandboxing/src/seatbelt.rs:

/// When working with `sandbox-exec`, only consider `sandbox-exec` in `/usr/bin`
/// to defend against an attacker trying to inject a malicious version on the
/// PATH. If /usr/bin/sandbox-exec has been tampered with, then the attacker
/// already has root access.
pub const MACOS_PATH_TO_SEATBELT_EXECUTABLE: &str = "/usr/bin/sandbox-exec";

create_seatbelt_command_args_with_profile builds the policy from sections and returns the argv -p <policy> -D<KEY>=<VALUE>... -- <command>. The static sections are four .sbpl files compiled in with include_str!. seatbelt_base_policy.sbpl starts from (deny default), allows process creation and same-sandbox signals, and lists the sysctl names that build tools need. seatbelt_network_policy.sbpl adds the Mach services that Transport Layer Security (TLS) and name resolution use. seatbelt_preferences_policy.sbpl is added only with unrestricted reads, because “Preferences IPC can expose data outside the filesystem read roots.” seatbelt_read_only_platform_defaults.sbpl supplies system read paths when a profile asks for :minimal.

Parameters instead of paths

The dynamic sections never contain a path. build_seatbelt_access_policy writes a reference such as (param "WRITABLE_ROOT_0") into the policy text and passes the real path as -DWRITABLE_ROOT_0=/repo. A protected subpath becomes WRITABLE_ROOT_0_EXCLUDED_0 with two clauses, literal and subpath, because, as the comment says, “subpath alone leaves a gap for first-time creation of the protected directory itself, such as mkdir .codex.” The book’s reading is that parameters also keep path text out of the policy grammar, so a directory name with quotes or parentheses cannot change the policy’s structure.

The fragment below was assembled by hand from the strings in seatbelt_base_policy.sbpl and create_seatbelt_command_args_with_profile for a workspace profile with one writable root and a protected .git. It was not captured from a run, and the real policy has more sections.

(version 1)
(deny default)
(allow process-exec)
(allow process-fork)
(allow signal (target same-sandbox))
; allow read-only file operations
(allow file-read*)
(allow file-write*
(require-all (subpath (param "WRITABLE_ROOT_0"))
  (require-not (literal (param "WRITABLE_ROOT_0_EXCLUDED_0")))
  (require-not (subpath (param "WRITABLE_ROOT_0_EXCLUDED_0"))) )
)
(deny file-write-unlink (require-all (literal (param "WRITABLE_ROOT_0")) (vnode-type DIRECTORY)))
(deny mach-lookup (xpc-service-name-prefix ""))
(deny system-fcntl (fcntl-command 80 110))

The matching invocation is /usr/bin/sandbox-exec -p '<policy>' -DWRITABLE_ROOT_0=/repo -DWRITABLE_ROOT_0_EXCLUDED_0=/repo/.git -- bash -lc 'make test'.

Closing the side doors

Several denies close paths that a file-write rule alone would leave open. Each writable root gets (deny file-write-unlink ...) on its own directory, because “a sandboxed process must not be able to replace an authority boundary.” Ancestors of protected paths get the same deny, so renaming a parent cannot carry .git out of its carve-out. Without full-disk write, fcntl commands 80 and 110 (F_MAKECOMPRESSED and F_TRANSFEREXTENTS) are denied because they “mutate files through read-only descriptors.” Every policy denies all XPC service lookups. A command that inherits the terminal also gets (deny file-ioctl (ioctl-command N)), where N is the numeric value of libc::TIOCSTI, so it cannot type into the shell that resumes after it.

Network rules come from dynamic_network_policy_for_network. With no network grant, (deny default) blocks all sockets. With a managed proxy, it allows outbound traffic only to localhost:<port> for each proxy port, or to any loopback port when local binding is allowed. With plain network access, it adds (allow network-outbound) and (allow network-inbound). Chapter 16 covers the proxy itself.

Linux: bubblewrap, seccomp, and an arg0 helper

Reaching the helper

Linux has no standard sandbox command, so Codex ships a helper inside the main binary. At startup, arg0_dispatch in codex-rs/arg0/src/lib.rs creates a temporary directory, adds symlinks to the current executable named apply_patch and, on Linux, codex-linux-sandbox, and puts the directory on PATH. When a process starts with that name as argv0, the dispatcher runs the helper instead of the CLI:

if exe_name == CODEX_LINUX_SANDBOX_ARG0 {
    // Safety: [`run_main`] never returns.
    codex_linux_sandbox::run_main();
}

This is the multicall-binary pattern: one file, several programs, chosen by name. The Linux backend in codex-rs/sandboxing/src/linux.rs writes the command as codex-linux-sandbox --sandbox-policy-cwd <dir> --command-cwd <dir> --permission-profile <json> -- <command> and sets exec.arg0 to codex-linux-sandbox, so the trick works even when the path is the real binary. Windows reuses the idea with flags instead of names: codex.exe --run-as-windows-sandbox for callers that need an argv-shaped launcher, and --__codex-windows-mxc for MXC.

Two stages

run_main in codex-rs/linux-sandbox/src/linux_run_main.rs runs twice. The outer stage builds bubblewrap arguments and starts bwrap, which re-executes the helper inside the new namespaces with the hidden flag --apply-seccomp-then-exec. The inner stage checks that it holds no effective or permitted capabilities, applies PR_SET_NO_NEW_PRIVS, installs seccomp, and calls execvp on the command.

The bubblewrap stage builds the filesystem view. With full-disk read, it starts from --ro-bind / / and a minimal --dev /dev; with restricted reads, it starts from an empty --tmpfs / and binds only the readable roots. Writable roots are layered on with --bind, and protected subpaths such as .git and .codex are bound read-only again. The arguments always include --new-session, --die-with-parent, --unshare-user, --unshare-ipc, and --cap-drop ALL, add --unshare-pid by default, and add --unshare-net when the network is restricted.

The seccomp stage filters system calls. Matched calls fail with EPERM, which is one reason the denial keywords in (14.1) catch them. From codex-rs/linux-sandbox/src/seccomp.rs:

if mode != NetworkSeccompMode::VmSocketRestricted {
    deny_syscall(&mut rules, libc::SYS_ptrace);
    deny_syscall(&mut rules, libc::SYS_process_vm_readv);
    deny_syscall(&mut rules, libc::SYS_process_vm_writev);
    // request_key can invoke host helpers that perform network requests
    // outside the sandbox's network namespace and proxy policy.
    deny_syscall(&mut rules, libc::SYS_request_key);
}
// io_uring can create AF_VSOCK sockets without a socket() syscall, so
// keep it unavailable in every mode with socket-family restrictions.
deny_syscall(&mut rules, libc::SYS_io_uring_setup);
deny_syscall(&mut rules, libc::SYS_io_uring_enter);
deny_syscall(&mut rules, libc::SYS_io_uring_register);

With a restricted network, the filter also denies connect, bind, listen, sendto, and related calls, and allows socket only for AF_UNIX. With the managed proxy, it allows IP sockets inside the private network namespace, where the only reachable endpoint is Codex’s bridge to the proxy. The function should_install_network_seccomp keeps a managed session “fail-closed even for policies that would normally grant full network access.”

Finding bubblewrap, and Landlock

The README in codex-rs/linux-sandbox/README.md records the discovery rules. Codex prefers the first bwrap on PATH outside the current working directory, which, the book infers, keeps a checked-out repository from supplying its own. If none exists, it falls back to the bundled codex-resources/bwrap and shows a startup warning. Windows Subsystem for Linux (WSL) version 2 works like Linux; WSL1 cannot create user namespaces, so Codex rejects sandboxed commands there. Landlock, the kernel’s own file-access API, remains only as a legacy mode behind the DEPRECATED use_legacy_landlock flag. The helper rejects it for filesystem-restricted policies because, in the README’s words, it “cannot isolate app-server Unix sockets.”

Windows: tokens, a sandbox user, and MXC

Three levels

[windows] sandbox in config.toml accepts elevated, unelevated, or mxc, and allow_mxc = false blocks MXC. WindowsSandboxLevel::from_config in codex-rs/core/src/windows_sandbox.rs maps unelevated to RestrictedToken, elevated to Elevated, and leaves the level Disabled otherwise. With the level Disabled, get_platform_sandbox returns no backend. Execpolicy then treats every unmatched command under a restricted profile like a dangerous one, asking under on-request and rejecting under never, because without a backend the restrictions are “only a policy shape.”

The restricted token

The unelevated backend runs the command as the current user with a reduced token. create_token_with_caps_from in codex-rs/windows-sandbox-rs/src/token.rs calls CreateRestrictedToken with DISABLE_MAX_PRIVILEGE | LUA_TOKEN | WRITE_RESTRICTED and a list of restricting security identifiers (SIDs) in a fixed order: capability SIDs, extra SIDs, the logon SID, then Everyone. Write access comes from capability SIDs. CapSids in cap.rs keeps one per workspace, keyed by the canonical working directory, and one per extra writable root. Before launch, apply_legacy_session_acl_rules adds allow-write access control entries (ACEs) for those SIDs on the writable roots and deny-write ACEs on protected paths. The new token’s default access control list (DACL) names only the logon SID, because “filesystem and route capabilities may be shared between launches” and must not reach another launch’s processes.

Network control on this level is weak. When the profile restricts the network, apply_no_network_to_env only rewrites the child’s environment: proxy variables that are not already set point at 127.0.0.1:9, package managers go offline, and stub ssh and scp scripts go first on PATH. The kernel enforces none of it, and transform refuses managed networking unless the level is Elevated.

The elevated setup and the sandbox user

The elevated backend moves the command to a different account. run_elevated_setup in codex-rs/windows-sandbox-rs/src/setup.rs starts codex-windows-sandbox-setup.exe with the runas verb, which raises a User Account Control prompt. The setup creates two local users, CodexSandboxOffline and CodexSandboxOnline (SETUP_VERSION is 5). For the offline user it installs Windows Firewall rules that block non-loopback outbound and inbound traffic, plus Windows Filtering Platform (WFP) filters for ICMP, DNS on ports 53 and 853, and SMB on ports 445 and 139. It grants read access to the children of the user profile except credential folders such as .ssh, .gnupg, .aws, .azure, .kube, and .docker.

At run time, codex-command-runner runs as the sandbox user. Its module comment describes the loop: connect to the parent’s named pipes, read a framed SpawnRequest, derive a restricted token from the sandbox user, spawn the child through ConPTY or pipes, and stream output back. A separate crate, windows-sandbox-service, can do the same provisioning as an installed Windows service; its feature flag windows_sandbox_service is UNDER DEVELOPMENT and off.

MXC

The third backend, in the mxc-sandbox crate, routes the command “directly into Microsoft’s public MXC V1 SDK,” in the words of its README. It “never invokes MXC’s AppContainer dispatcher, edits host ACLs, creates sandbox users, runs setup, or requests elevation.” Filesystem rules come from the same PermissionProfile, and managed network access allows only IPv4 and IPv6 loopback. windows.sandbox = "mxc" is strict, and command failures never fall back to another backend. The UNDER DEVELOPMENT prefer_mxc flag selects MXC automatically when it is available.

The three platforms side by side

The table compares the backends on the points that decide what a sandboxed command can do.

Aspect macOS Linux Windows
Mechanism Seatbelt via /usr/bin/sandbox-exec bubblewrap, then seccomp Restricted token, sandbox user, or MXC
Entry point Wrapped argv codex-linux-sandbox (argv0) Token spawn, runner, or MXC flag
Filesystem SBPL rules with -D params Bind mounts in a user namespace ACLs on capability SIDs
Network off (deny default) --unshare-net plus seccomp Env rewrite, or firewall for the sandbox user
Managed proxy Loopback only; proxy ports unless local binding is on Bridge in a private namespace Elevated or MXC only
Setup needed None bwrap (bundled fallback) Elevated: admin setup

The exec-server and sandbox integrity

The exec-server also hosts code that checks whether a sandbox matches its policy. Its review contract, codex-rs/exec-server/src/sandbox_integrity/AGENTS.md, opens with the state: “Runtime integrity checks are paused at the shared runner entry point.” The runner enforces the pause with a constant, INTEGRITY_CHECKS_ENABLED: bool = false, in runner.rs.

The contract defines the checks as pure observers. When enabled, they “emit telemetry only,” and findings “must not change sandbox construction, permissions, approvals, or command execution.” They cover Seatbelt, bubblewrap, and MXC; legacy Windows is out of scope. Blocking work runs under a five-second caller timeout, and telemetry must “never emit paths, environment values, or error text.” Approved escalations that keep only deny-read rules are skipped before any work. The contract also lists its blind spots: hard-link aliases and glob nuances “are not fully modeled.” The book’s reading of the design: a checker that could alter enforcement would become a second sandbox that could disagree with the first.

Process hardening

pre_main_hardening in codex-rs/process-hardening/src/lib.rs hardens the calling process itself, not its children. Its doc comment says it is “designed to be called pre-main() (using #[ctor::ctor]).”

Platform Steps Exit code on failure
Linux, Android PR_SET_DUMPABLE 0, RLIMIT_CORE 0, remove LD_* 5 (prctl), 7 (rlimit)
macOS ptrace(PT_DENY_ATTACH), RLIMIT_CORE 0, remove DYLD_* 6 (ptrace), 7 (rlimit)
FreeBSD, OpenBSD RLIMIT_CORE 0, remove LD_* 7
Windows Nothing yet (a TODO in the code) none

A repository search at commit 081295be9d finds two callers. responses-api-proxy calls it from a #[ctor::ctor] function, and voice-host calls it on the first line of main. The Linux sandbox helper calls the narrower disable_process_dumping. The main codex CLI does not call pre_main_hardening: no call appears in its source, and none of the cli, exec, tui, or app-server crates lists codex-process-hardening as a dependency. This was measured with a text search, not by inspecting a built binary.

Trying a policy

codex sandbox runs one command under the host’s sandbox, resolving the same configuration and permission profiles the agent uses. The host decides the backend: the flags come from SeatbeltCommand, LinuxSandboxCommand, or WindowsCommand in codex-rs/cli/src/lib.rs. With --permission-profile (-P) it applies a named profile. Without one, and with a legacy config, it uses read-only, as a comment in debug_sandbox.rs explains, instead of the ambient sandbox_mode.

Try it. On macOS, watch Seatbelt refuse a write and print the denial:

codex sandbox --log-denials -- touch /etc/codex-test
codex sandbox -P dev -C ~/code/app -- cargo test
codex sandbox --include-managed-config -P dev -- git status

--log-denials captures denials through log stream and prints them after the command exits. On Linux, the README’s example routes TCP through the proxy: codex sandbox --transparent-tcp --permission-profile db -- psql -h pg.example. At this commit codex debug has no sandbox subcommand; use codex execpolicy check for rule questions (see Chapter 15).

Status at commit 081295be9d. Seatbelt, bubblewrap with seccomp, and the Windows restricted-token and elevated backends: IMPLEMENTED, PLATFORM-SPECIFIC. MXC backend: IMPLEMENTED, Windows only; prefer_mxc is UNDER DEVELOPMENT and off. windows_sandbox_service: UNDER DEVELOPMENT, off. use_legacy_landlock: DEPRECATED, off. use_linux_sandbox_bwrap, experimental_windows_sandbox, and elevated_windows_sandbox: REMOVED. Sandbox integrity checks: paused. Read in code, not run.

What breaks

Symptom Cause Check
Startup warning about a missing bwrap No system bubblewrap; the bundled copy is used which bwrap; system_bwrap_warning
Every sandboxed command fails on WSL WSL1 cannot create user namespaces uname -r; the Linux sandbox README
use_legacy_landlock config fails for a restricted profile Landlock cannot isolate app-server sockets Remove features.use_legacy_landlock
Writes to .git or .codex fail inside the workspace Protected subpaths stay read-only -D...EXCLUDED_... params; --ro-bind
A test fails and Codex calls it a sandbox denial Output contains a denial keyword SANDBOX_DENIED_KEYWORDS
Windows network block does not stop a raw socket Unelevated mode only rewrites the environment Use [windows] sandbox = "elevated"
“managed networking requires the elevated Windows sandbox backend” Proxy enforcement with the unelevated level WindowsSandboxLevel
Replacing sandbox-exec on PATH has no effect The path is fixed to /usr/bin MACOS_PATH_TO_SEATBELT_EXECUTABLE

Code map

What it is Path Identifier
Backend selection and strategy seam codex:codex-rs/sandboxing/src/manager.rs SandboxBackend
Seatbelt policy and argv codex:codex-rs/sandboxing/src/seatbelt.rs create_seatbelt_command_args_with_profile
Denial heuristic codex:codex-rs/sandboxing/src/denial.rs is_likely_sandbox_denied
Multicall dispatch codex:codex-rs/arg0/src/lib.rs arg0_dispatch
Seccomp filter codex:codex-rs/linux-sandbox/src/seccomp.rs set_no_new_privs
Windows restricted token codex:codex-rs/windows-sandbox-rs/src/token.rs create_token_with_caps_from
Windows sandbox users codex:codex-rs/windows-sandbox-rs/src/setup.rs OFFLINE_USERNAME
Process hardening codex:codex-rs/process-hardening/src/lib.rs pre_main_hardening

Recall check

Why does Codex run unmatched commands without a prompt under on-request?
The sandbox enforces the profile at run time, so approval is kept for escaping the sandbox.

How does the Linux helper get started without a separate executable?
arg0_dispatch symlinks codex-linux-sandbox to the Codex binary and runs codex_linux_sandbox::run_main when argv0 has that name.

Why does Seatbelt receive paths as -D parameters?
The policy text stays fixed and refers to (param ...) names, so paths never enter the SBPL grammar.

What is the difference between unelevated and elevated Windows sandboxing for network?
Unelevated only rewrites the environment; elevated runs as CodexSandboxOffline behind firewall rules and WFP filters.

Does the main codex CLI call pre_main_hardening at this commit?
No; only responses-api-proxy and voice-host call it, and the CLI crates do not depend on it.