Skip to content

sandbox

sherry-wiki edited this page Nov 22, 2026 · 12 revisions

🛡️ Tool Sandbox: Terminal, Python REPL & PTC

Sherry Wiki · English · 中文 · 日本語 · 한국어

← Back to index

How the agent confines model-initiated code execution: environment scrubbing at every spawn, an OS-native sandbox when available, and a human approval gate for deliberate bypasses.

Three tools let the model execute code on your machine: terminal (shell commands), python_repl (Python in a child process), and PTC's execute_code (a longer Python script in a child process that can call real tools over an RPC bridge). A hallucinated or prompt-injected command could read API keys from the environment, write outside the project, or touch other processes. The sandbox layer confines all three.

Source of truth: agent/tools/pub_base/env_scrub.py, agent/tools/pub_base/sandbox.py, agent/tools/pub_base/sandbox_bwrap.py, agent/tools/pub_base/sandbox_seatbelt.py, agent/tools/pub_base/sandbox_win.py, agent/tools/pub_base/shell_resolver.py, agent/tools/pub_base/path_utils.py, agent/tools/file_tools/, agent/tools/terminal/core.py, agent/tools/python_repl.py, agent/tools/ptc/runner.py, agent/middlewares/humanInTheLoop/, agent/middlewares/path_guard/.

Table of Contents

🎯 Overview & Threat Model

Exposure Without sandbox Defense
Secrets in env vars Child process inherits every variable, including *_API_KEY L1 env scrubbing
Filesystem writes Child writes anywhere the agent user can write L2 OS sandbox: AppContainer on Windows, bwrap / Seatbelt on Linux / macOS
Filesystem reads Child reads ~/.ssh, .env, credential stores L2 read-shield (sensitive-path masking, Linux / macOS; AppContainer's package identity on Windows) + sensitive-file regex (terminal)
File-tool path arguments A tool call asks read_file for a traversal or hard-denied path §5 external-path gate + §6 structural gates + §7 PathGuard (external paths still go through HITL)
Shell command arguments terminal(commands=…) / python_repl(query=…) name a credential file — those arguments are not paths, so the path gate never sees them §7 PathGuard's command screen (hard-deny floor only; every other external path is the OS sandbox's business)
Process / session scope Child shares namespaces and survives the parent L2 --unshare-all, --die-with-parent; Windows: Job Object (ActiveProcessLimit, JobMemoryLimit, KILL_ON_JOB_CLOSE)
Deliberate bypass A server-side caller requests sandbox=False Human approval gate (HITL) — skipped by a session in full_access; the LLM schemas expose no flag
Class-introspection escape ().__class__.__base__.__subclasses__() reaches os/subprocess without open/__import__ AST guard (pub_base/safe_exec.py) refuses dunder attribute access — including a dunder reached through a literal str.format/format_map field ("{0.__class__}".format(x)) — before any child spawns; a non-literal template stays allowed because formatting only ever yields a string
Programmatic tool calls (PTC) A generated execute_code child script calls real tools and could reach the filesystem directly L1 env scrub + L2 OS sandbox wrap (same backend as terminal / python_repl) + restricted builtins (no getattr/type/dir/vars) + import allowlist + the same AST guard

Two layers plus one gate — plus a separate path-defense stack for the file tools:

  • L1. Environment scrubbing (scrub_env): unconditional, at every spawn point, even when a human approved sandbox=False. It drops secret-named variables and blocks startup-hook variables outright (PYTHONPATH, BASH_ENV, ENV, …) at a precedence above its own keep list, so a child never sources a file or imports a module chosen by whoever set the parent environment; the loader variables (LD_PRELOAD, LD_LIBRARY_PATH, …) are blocked only under SHERRY_STRICT_ENV_HIJACK=1, because container runtimes set them for real and stripping them stops every child from starting.
  • L2. OS-native sandbox: bubblewrap on Linux, Seatbelt on macOS, and on Windows an AppContainer (a per-user package SID that can reach only the granted writable roots) plus a restricted token (every privilege removed) and a Job Object (process/memory caps, kill-on-close) — write containment, read isolation and an optional network cut (see §2).
  • Human approval gate: a server-side sandbox=False call bypasses only in the main session, through a HITL interrupt. The model cannot ask for one: the terminal and python_repl call schemas carry no sandbox field (2026-11-09 audit H2), so the policy stays server-owned.
  • PTC (execute_code): executor-only and exposes no sandbox flag, so it always requests sandboxing — the child argv is wrapped by the same L2 backend. SANDBOX_POLICY=required AND auto both refuse the run when no backend exists — PTC has no HITL path, so it never degrades (only an explicit off runs it unsandboxed; see Isolation §2).
  • File-tool path gate (Isolation §5–§7): resolve_project_path()'s three structural gates and O_NOFOLLOW I/O, virtual-path rendering, search containment, the six-check external-path approval flow, and the PathGuard middleware screen.

⚙️ Implementation & Architecture

Policy: SandboxPolicy

Three states parsed from the SANDBOX_POLICY environment variable:

Value Meaning
required (recommended deployment; shipped .env is auto) Backend unavailable ⇒ reject the command, never run unsandboxed
auto Backend unavailable ⇒ an interactive main-session call asks through the sandbox-bypass HITL card (headless turns auto-deny; confirm-all's card carries the note). A subagent/background call and PTC REFUSE (no HITL path); only an explicit off runs them unsandboxed
off Sandboxing disabled entirely

The unset-env fallback inside read_policy() is still auto (a running install keeps whatever it configured); the tracked .env ships auto; a deployment should opt into required, because on a host where the backend cannot run, auto routes every interactive shell command through an approval card (headless commands are denied) and PTC refuses to run at all (no HITL path) — measured, not hypothetical: a kernel without user namespaces (Ubuntu 24.04's default AppArmor policy, or a PRoot/container host) leaves a bwrap binary present but non-functional. At boot the effective policy and backend are logged (sandbox: policy=… backend=… available=…), an unusable required logs an ERROR with the fix commands, and SANDBOX_STRICT_BOOT=1 turns that into a refused start. GET /sandbox/status reports the same dict at runtime.

parse_policy strips whitespace, matches case-insensitively, and raises ValueError on unknown values: a mistyped safety setting must fail loudly, never fall back silently. read_policy() calls os.getenv on every invocation (no import-time caching), so runtime changes take effect immediately.

Backend contract and dispatch

SandboxBackend is the ABC every backend implements:

  • probe() -> bool: must never raise; backends catch their own probe exceptions and return False.
  • wrap(cmd, env, writable_roots) -> (argv, env): returns the wrapped argv plus env, to be exec'd directly in list form (no shell). writable_roots is the ONLY write surface the command gets (the calling session's project directory, plus — for terminal / python_repl — the session's own SESSIONS_DIR/<session_id> tree: plans, attachments, uploads, evicted/ previews and scratch files; TEMP_DIR is appended by the shared normalizer because the sandbox needs a writable temp). The parameter is required and an empty list raises ValueError — a default would silently restore the old "the whole ROOT_DIR is writable" behaviour at any call site that forgot it, which is the write bypass this contract closes.

get_backend(policy) resolves through a platform registry:

  1. OFF returns None immediately: no probe, no import, no subprocess.
  2. The registered factory for platform.system() builds the backend. Linux uses a composite factory: it returns BwrapBackend only when BwrapBackend.probe() succeeds, otherwise it falls back to LandlockBackend (so slim containers without bwrap keep a kernel-LSM sandbox instead of running unsandboxed). macOS → SeatbeltBackend, Windows → WinSandboxBackend. All are registered as LAZY import factories (ImportError means "unavailable", never a crash). A platform with no registered factory has no backend. register_sandbox_backend(system, factory) adds or replaces one; a duplicate registration is refused unless replace=True.
  3. If the backend exists but probe() fails: REQUIRED raises RuntimeError("Required sandbox unavailable on {system}"); AUTO / OFF return None.

Tool integration

SafeShellTool (name terminal) and TimedPythonREPLTool (name python_repl) keep an internal sandbox: bool = True parameter for server-side callers, but it is NOT in their LLM-visible tool-call schemas (2026-11-09 audit H2: a forged sandbox=false is dropped by validation). PTC's ExecuteCodeTool (name execute_code) has no sandbox parameter at all — it is executor-only and always requests the sandbox.

  • Sandboxed path: backend.sandbox_shell(cmd_str) supplies the shell, and backend.wrap(shell_argv, env, roots) wraps it. On POSIX the shell is /bin/sh -c; on Windows it is cmd.exe /c while AppContainer is active (Git Bash cannot initialise inside an AppContainer — MSYS2 needs global named objects — so the confined shell is cmd), and Git Bash again when SHERRY_WIN_SANDBOX_APPCONTAINER=0 (falling back to COMSPEC only when no bash exists). The same argv shape applies to python_repl's interpreter argv and the PTC child. The wrapped argv is exec'd as a list, with no shell kwarg at all. roots is the session's project directory (current_project_dir(session_id) / the PTC child's cwd) — the same value the command's cwd comes from, so the write surface and the working directory can never disagree, and a project bound OUTSIDE the checkout is writable (it used to be EROFS) while the checkout itself is not (it used to be, which made terminal a way around the external-path gate). terminal and python_repl then append the session's own SESSIONS_DIR/<session_id> tree (with_own_session_root, created on demand), which is private runtime state the file tools already read/write without HITL: it lets the session create, modify and delete (rm) its own files even with the project bound elsewhere. Only that ONE session directory is added — the shared sessions root and every other session stay read-only. PTC keeps its cwd.

  • Fallback path (no usable backend): when the platform has no backend, the policy is off, or probe() fails — terminal joins commands with " && " and spawns through Git Bash when present (else shell=True), python_repl spawns [sys.executable, "-c", script] as a list. On the main HITL path the degradation is approved BEFORE the tool runs; a headless turn auto-denies it, and a subagent/background call or PTC refuses outright (no approval path).

  • Unconditional on every path: env=scrub_env() and cwd=str(ROOT_DIR) (cwd clamp). Both tools enforce a 30-second timeout (TERMINAL_TIMEOUT, PYTHON_REPL_TIMEOUT) and kill the child on expiry; PTC enforces its own ptc_timeout_seconds and SIGKILLs the child's process group.

  • Error surfacing: with REQUIRED and no backend, terminal wraps the RuntimeError into a ToolException (surfaced verbatim by handle_tool_error=True); python_repl surfaces the raw RuntimeError; PTC returns a status: "sandbox_unavailable" envelope before spawning anything.

  • Degrade logging: when a sandboxed execution was wanted but no backend exists and the policy is not off, terminal / python_repl log exactly one loguru INFO line and execute unsandboxed — on the main HITL path the sandbox-bypass card was already shown and approved:

    • terminal: sandbox unavailable (policy=auto) — running unsandboxed (HITL-gated when an operator is in scope)
    • python_repl: sandbox unavailable (policy=auto) — running unsandboxed (HITL-gated when an operator is in scope)
    • PTC logs the refusal in its result envelope (status: sandbox_unavailable) and does not spawn; only SANDBOX_POLICY=off runs it unsandboxed

    A bare run is recorded: the command's evidence-ledger row carries sandboxed: false, and the sandbox-bypass approval card marks the request ⚠ UNSANDBOXED (the degraded variant says ⚠ OS SANDBOX UNAVAILABLE) with what it means. So the fact is durable in both directions — the human approving a bypass reads it, and an audit of the ledger finds it.

🛠️ Configuration & Usage

SANDBOX_POLICY

# .env or shell environment
SANDBOX_POLICY=auto      # required | auto | off (case-insensitive, default: auto)

Invalid values raise a ValueError at first use instead of silently using the default. The variable is re-read on every tool call, so you can flip it at runtime.

SANDBOX_STRICT_BOOT

# .env or shell environment
SANDBOX_STRICT_BOOT=1    # refuse to start when SANDBOX_POLICY=required is unmet

Default (unset) warns instead, so a development host without a working sandbox still starts.

SANDBOX_READ_ALLOWLIST / SANDBOX_READ_EXTRA

# .env or shell environment
SANDBOX_READ_ALLOWLIST=1              # default OFF: see scripts/sandbox_smoke.py
SANDBOX_READ_EXTRA="~/.cache:~/.local/share"

With the allowlist ON, the read surface stops being "the whole filesystem read-only": the sandbox mounts only the system trees (/usr, /bin, /lib, /etc, …), the resolved writable_roots, and SANDBOX_READ_EXTRA (default ~/.cache, where the npm/pip/uv caches live), then masks /home /root /mnt /media /srv /run with empty views (bwrap) or denies reads by default and re-opens exactly those paths (Seatbelt). It is OFF by default because neither backend was ever verified on a machine with a working sandbox: run uv run --no-sync python scripts/sandbox_smoke.py on your host first — it probes the write surface, the read surface and (with SANDBOX_READ_ALLOWLIST=1) that a non-whitelisted read fails. Without it, reading any user file stays possible inside the sandbox (only the five credential paths and .env files are shielded).

SHERRY_DENY_READ_PATHS

# .env or shell environment (os.pathsep-separated; ~ is expanded)
SHERRY_DENY_READ_PATHS="~/.kube:~/.config/gcloud"

Adds paths to the read-shield list of both OS backends (the defaults from Isolation §2 are always included). The variable is read on every wrap() call.

Windows sandbox limits (SHERRY_WIN_SANDBOX_*)

# .env or shell environment (read on every wrap() call)
SHERRY_WIN_SANDBOX_MAX_PROCESSES=50     # Job Object ActiveProcessLimit (clamped 1..10000)
SHERRY_WIN_SANDBOX_MAX_MEMORY_MB=4096   # Job Object JobMemoryLimit (clamped 64..1048576)
SHERRY_WIN_SANDBOX_BLOCK_NETWORK=0      # 1 = no internetClient capability (the AppContainer gets no network)
SHERRY_WIN_SANDBOX_APPCONTAINER=1       # 0 = restricted token + Job Object only, and the sandboxed shell returns to Git Bash

An unparseable value falls back to its default with one WARNING. The launcher reports each layer it could not apply on stderr with the Win32 error code, and the command still runs (fail-open).

What the model sees

The model sees commands / run_in_background / timeout (terminal) and query (python_repl) — no sandbox field. The switch remains on _run/_arun for server-side callers, defaults to True, and a forged sandbox=false argument from the model is discarded by schema validation. The tool then applies the policy: required denies an internal sandbox=False, subagent/background scope denies it, and the main session offers the HITL card below.

How a user approves or denies

When a server-side caller requests sandbox=False in the main session (non-YOLO), the graph suspends on a HumanInTheLoop.after_model interrupt. The strategy reads the raw call arguments, so the card still works for an internal/diagnostic call even though the model cannot produce the flag. The frontend renders the action (tool name, full args, command or query) with two decisions:

  • approve: resume with {"decisions": [{"type": "approve"}]}; the call runs immediately (env scrubbed, no OS sandbox).
  • reject: resume with {"decisions": [{"type": "reject", "message": "..."}]}; the tool result becomes an error ToolMessage (User denied: <msg>. <BLOCKED_MESSAGE>) and nothing executes.

The terminal approval card also offers Allow for Session only when the backend sends session in allowed_decisions: a cacheable ordinary command that actually reached the card. Choosing it writes the command's first two-word pattern to the session allowlist, so later matching commands skip the card; approve remains one-shot. Dangerous commands, confirm-all mode and clawhub remote execution never offer or write the session cache, and a dangerous command skips the session allowlist even when a matching pattern was stored earlier.

The landlock fallback (Linux, no bwrap)

agent/tools/pub_base/sandbox_landlock.py is the second Linux backend: when bwrap is absent (slim containers, distroless images), the kernel-level landlock LSM (Linux 5.13+) restricts the command with no external binary. The ruleset is an ALLOW-LIST — read only on the system trees (/usr /bin /sbin /lib /lib64 /etc /opt /dev /proc /sys), read+write on the caller's writable roots and /dev/null — so ~/.ssh and the other credential directories are denied by OMISSION (stronger than bwrap's mask, stricter than "whole filesystem read-only"). landlock can only restrict the CALLING process, so wrap() returns a launcher — python -I -c <loader> -- <real command> — that applies the rules (ctypes, syscall numbers 444-446, PR_SET_NO_NEW_PRIVS first) and execvps the command; the rules ride one env var that the loader pops. An init failure exits 126: the sandbox fails CLOSED, like a missing bwrap under required. Frozen builds and non-x86_64/aarch64 machines report unsupported and keep the previous dispatch. REFER (ABI v2) and TRUNCATE (ABI v3) grow the handled set with the kernel. probe() does not stop at the ABI number: it smoke-tests a real /bin/true through the launcher (like the bwrap probe) and caches the result, because a nested/containerised host can expose the ABI yet deny execve after restrict_self (seccomp/no_new_privs interaction); in that case it reports unavailable and AUTO degrades. A fixed read path absent on this distro's layout (e.g. /lib64 under usrmerge) is skipped — skipping an allow-list rule for a nonexistent path cannot widen access. Tests: tests/agent/tools/pub_base/test_sandbox_landlock.py (probe/spec/factory, including the smoke-test success and exec-denied paths; the real syscall path needs a 5.13+ kernel).

🧪 Testing

Suite Covers
tests/agent/tools/test_sandbox_matrix.py 14 tests, one per matrix-cell behavior (cells 1-5 once per tool, cell 6 four times), including the real-graph HITL interrupt and the exactly-one-info-line degrade assertion
tests/agent/tools/pub_base/test_env_scrub.py scrub rules, precedence, keep/deny edges (50 tests)
tests/agent/tools/pub_base/test_sandbox_policy.py policy parsing, strict ValueError, fresh-read semantics, dispatch
tests/agent/tools/pub_base/test_sandbox_bwrap.py / test_sandbox_seatbelt.py argv / profile construction (incl. read-shield mounts), probe caching (all subprocess mocked), plus an optional real-bwrap read-shield smoke test
tests/agent/tools/pub_base/test_sandbox_win.py config parsing / clamping / fallbacks, launcher payload fidelity (quotes, %, newlines), a layer-presence guard over the launcher source, probe caching, and — on Windows — real stdout/stderr/exit-code/cwd/env propagation, the process cap, the memory cap, kill-on-close, AppContainer write/read confinement, the network switch and the AppContainer-off fallback
tests/agent/tools/pub_base/test_terminal_tool.py / test_python_repl_tool.py tool-level guards (dangerous / sensitive-file regexes), the query-only schemas, spawn forms, restricted-builtins barrier, refused introspection before spawn
tests/agent/tools/pub_base/test_safe_exec.py the AST guard: benign code passes; dunder attributes / a literal str.format dunder field / __builtins__ / syntax errors are refused with the offending line
tests/agent/tools/pub_base/test_path_utils.py the external-path flow, the three structural gates, symlink-loop handling, virtual-path rendering
tests/agent/tools/file_tools/test_path_hardening.py / test_virtual_paths.py / test_search_containment.py / test_search_bounds.py symlink / TOCTOU refusal via O_NOFOLLOW, virtual paths, search-result containment, scan bounds
tests/agent/middlewares/test_path_guard.py PathGuard screening: traversal components, hard-deny floor, external-path pass-through, structured error ToolMessage
tests/agent/middlewares/humanInTheLoop/test_hitl_characterization.py 19 tests locking pre-sandbox HITL / terminal legacy behavior
tests/agent/middlewares/humanInTheLoop/test_hitl_sandbox_bypass.py 17 tests for the bypass approval flow, YOLO pass-through, scope stamping
tests/agent/tools/subagent/test_inherited_tool_policy.py caller_scope="subagent" stamping
tests/agent/tools/ptc/test_rpc_auth.py / test_sandbox_integration.py / test_runner_hardening.py / test_runner.py PTC RPC one-time-token handshake; the PTC sandbox-policy mapping; runner token lifecycle and backend wrap; introspection escapes refused before spawn

Matrix tests patch subprocess.Popen globally, stub get_backend at the tool-module seam, and set SANDBOX_POLICY through the environment so the real read_policy runs in every cell.

⚠️ Honesty & Limitations

  • bwrap and Seatbelt construction logic is unit-tested but not verified on real Linux/macOS machines. The backend source docstrings state this explicitly ("only the construction logic is verified, never run on a real Linux/macOS box"); all backend tests mock subprocess, and the read-shield has one optional real-bwrap smoke test that skips when the probe fails. Trust the wrap output, not yet a real containment guarantee.
  • On Windows the three layers are live, with one deliberate shell change. An AppContainer profile (per user, created once) gives the command a package SID; the launcher grants it write access on writable_roots (inherited by new and existing children) and read+execute on the shell and on a venv's base interpreter (via pyvenv.cfg), so a venv python.exe still works. The restricted token removes every privilege, the Job Object caps processes/memory and kills the tree on launcher death, and omitting the internetClient capability cuts the network. Real end-to-end tests cover write/read confinement, the network switch, stdout/stderr/exit codes, the caps and kill-on-close. Git Bash (MSYS2) cannot start inside an AppContainer, so the confined shell is cmd.exe — POSIX-only syntax (;, $(), export) does not work there; set SHERRY_WIN_SANDBOX_APPCONTAINER=0 to get Git Bash back (losing file/network confinement, keeping the restricted token + Job Object). The DACL grants are persistent on the granted roots (read/write for the package SID only) and the AppContainer profile is never deleted at runtime.
  • The sensitive-file regex is a mitigation, not a barrier. It matches literal command shapes; dd, sed, python -c "open(…)", $(< file), variables, and globs bypass it by design of the layer. The OS read-shield is the actual read barrier where a backend exists.
  • python_repl has no sensitive-file regex. The terminal-only gates (Isolation §3) do not cover it; its wrapper script instead restricts builtins (no open / __import__ / getattr / type / dir / vars), and pub_base/safe_exec.py refuses dunder attribute access before the child spawns — a different, narrower control that the OS sandbox must still back on a read-sensitive host.
  • PTC inherits the same backend caveats. execute_code wraps its child with the L2 backend whenever one is usable, and refuses introspection escapes statically (no getattr/type/dir/vars in the restricted set, no dunder attributes); under SANDBOX_POLICY=auto with no usable backend it now REFUSES the run (PTC has no HITL middleware, so the degrade was never approval-gated) — only an explicit off runs it unsandboxed; PTC passes allow_network=True, so bwrap adds --share-net beside --unshare-all to keep the loopback RPC bridge reachable; on Windows the same flag suppresses SHERRY_WIN_SANDBOX_BLOCK_NETWORK (the AppContainer gets internetClient) so a PTC child keeps outbound network even with that variable set to 1 — file/read confinement is unchanged; terminal and python_repl keep the private network namespace. PTC's one-time RPC token and its /proc/<pid>/environ residual are documented on the PTC page.
  • The degrade path is approval-gated on the main path, tool-layer-only elsewhere. auto + no backend: terminal / python_repl in the main session show the sandbox-bypass card before running unsandboxed, headless turns auto-deny, confirm-all's own card carries the note, and YOLO bypasses by design (activation logs a warning). The child chain, background graphs and PTC have no HITL middleware, so under auto without a backend they now REFUSE before the spawn (_deny_unsandboxed_degrade); only an explicit off keeps the unsandboxed path. The tracked .env ships auto; set required for a hard guarantee, and SANDBOX_STRICT_BOOT=1 additionally refuses to start.
  • The command-path screen is a mitigation, not a barrier. It refuses a command that literally names a hard-denied path (credential/system files, the YOLO deny list) and lets everything else through to the sandbox; base64 -d | sh, variable indirection built from pieces, and cd + relative paths all evade it by construction. The OS sandbox is the boundary.
  • Env scrubbing is name-based. A secret stored under a name without any blocked substring (and not on the deny list) passes through. There is no value scanning or dynamic secret detection, and that is deliberate.
  • No network sandboxing, seccomp, or AppArmor profiles are claimed or configured. Isolation comes from the bwrap / Seatbelt constructions exactly as shown in Isolation §2, plus the Windows AppContainer + restricted token + Job Object, nothing more. SHERRY_WIN_SANDBOX_BLOCK_NETWORK removes the AppContainer's internetClient capability (no outbound network); it is not a per-host firewall.

Clone this wiki locally