返回 CodeWhale
SANDBOX.md
根目录 / docs / SANDBOX.md
1 # Sandbox threat model
2
3 > 阅读简体中文版:[zh_hans/SANDBOX.md](zh_hans/SANDBOX.md)。
4
5 Codewhale can launch shell commands proposed by a model. Approval policy,
6 workspace-aware tools, and an operating-system command wrapper are separate
7 controls: an approval is not a sandbox, and selecting `workspace-write` does
8 not prove that the current platform has an OS wrapper available.
9
10 This document describes only behavior wired into the command execution path.
11 See [Authorization order](AUTHORIZATION_ORDER.md) for the policy layers that
12 run before execution reaches this boundary.
13
14 ## Platform overview
15
16 | Mechanism | Platform | Selection | What Codewhale reports |
17 |---|---|---|---|
18 | Seatbelt (`sandbox-exec`) | macOS | Automatic when the runtime probe succeeds | `macos-seatbelt` |
19 | Bubblewrap (`/usr/bin/bwrap`) | Linux | Default when installed and a wrapped probe run succeeds; `prefer_bwrap = false` opts out | `linux-bwrap` |
20 | No OS wrapper | Linux without usable bwrap, or opted out | `prefer_bwrap = false`, or bwrap absent/unusable | `none` |
21 | No OS wrapper | Windows | Current implementation | `none` |
22 | OpenSandbox-compatible service | Any supported host | `sandbox_backend = "opensandbox"` | External execution path |
23
24 The repository also contains a future Windows helper contract. It is not
25 wired into child-command launch, so Codewhale does not advertise it as an
26 active sandbox. Source-only sandbox code is not evidence that a command was
27 restricted.
28
29 ## macOS: Seatbelt
30
31 Codewhale probes `/usr/bin/sandbox-exec` by running a minimal profile. When the
32 probe succeeds and the selected `SandboxPolicy` requests a sandbox, the child
33 command is wrapped with a generated Seatbelt profile.
34
35 The profile can provide:
36
37 - broad filesystem reads;
38 - writes limited by the selected policy, including the workspace and specific
39 runtime/cache paths needed by supported tools;
40 - network access only when the policy enables it. A `read-only` policy with
41 network (the agent `read_only: true` shell mode) gets outbound IPv4 and the
42 system DNS resolver only. IPv6 and the host's own addresses, loopback
43 included, are denied, except the port of a local proxy named in
44 `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, and other local sockets stay
45 denied.
46
47 A shell command under the `read-only` policy (for example the agent
48 `read_only: true` mode) gets one private, empty, writable temporary directory as
49 `TMPDIR` (also `TMP`, `TEMP` and zsh's `TMPPREFIX`), created under the Darwin
50 per-user temporary directory (falling back to `/private/tmp`, outside the
51 working directory), protected against unlinking the root itself, and deleted
52 when the command ends, so `zsh` heredocs (`<<EOF` via `TMPPREFIX`),
53 `mktemp -p "$TMPDIR"` and tools that honor `TMPDIR` work. A bare `mktemp`
54 on macOS and here-documents (`<<EOF`) in macOS `/bin/sh` or `/bin/bash` ignore
55 `TMPDIR` for the shared per-user or `/var/tmp` directories and are refused.
56 Nothing else is writable: the workspace, home, Git metadata and caches stay
57 read-only, so `git fetch` (which writes `.git/FETCH_HEAD`) is refused;
58 `git ls-remote` reads remote refs without writing. Keychain reads through the
59 system security service are not blocked, so `gh` finds its stored token when
60 the run has network. Seatbelt never starts a setuid program in any sandbox, so
61 `ps` and `top` fail with `Operation not permitted`; `pgrep -lf` and `lsof` list
62 processes instead. Signals reach only processes in the same sandbox.
63
64 If the probe fails or `sandbox-exec` is unavailable, Codewhale reports no OS
65 sandbox and launches the command without a Seatbelt wrapper. It does not set a
66 Seatbelt marker on that fallback.
67
68 ## Linux: default bubblewrap
69
70 Linux command sandboxing is on by default whenever bubblewrap works. Set the
71 top-level configuration key to opt out:
72
73 ```toml
74 prefer_bwrap = false
75 ```
76
77 Codewhale selects bubblewrap only when `/usr/bin/bwrap` is a regular
78 executable file AND a wrapped probe run proves it can create its namespaces
79 on this host — the exec bit alone lies where user namespaces are restricted
80 (e.g. Ubuntu 24.04 with `kernel.apparmor_restrict_unprivileged_userns`),
81 where every wrapped command would fail rather than run unsandboxed. The
82 wrapper derives its mounts and network namespace from the resolved
83 `SandboxPolicy`:
84
85 ```text
86 /usr/bin/bwrap \
87 --unshare-all \
88 [--share-net] \
89 --ro-bind / / \
90 --dev /dev \
91 --proc /proc \
92 --tmpfs /tmp \
93 [--dev-bind <device-root> <device-root> ...] \
94 --bind <writable-root> <writable-root> ... \
95 --ro-bind <protected-descendant> <protected-descendant> ... \
96 [--ro-bind <extra-ro-root> <extra-ro-root> ...] \
97 --chdir <cwd> \
98 -- <program> <args>
99 ```
100
101 The sandbox always gets a private `/dev` (fresh device nodes, so `>/dev/null`
102 works), a private `/proc`, and a tmpfs `/tmp` (#5410). A `workspace-write`
103 policy then binds the host `/tmp` (and `TMPDIR`) over that tmpfs unless it
104 excludes them, so by default a sandboxed command shares the host's `/tmp`,
105 writable, with the usual sticky-bit rules. Two optional top-level
106 config keys extend the mounts: `bwrap_ro_roots` (extra host paths bind-mounted
107 read-only, applied last so they can narrow a policy-writable path) and
108 `bwrap_dev_roots` (host character/block device nodes bind-mounted read-write;
109 directories are never honored). Missing paths are skipped silently.
110
111 That gives the child a read-only root view. For `workspace-write`, every safe,
112 existing policy root is mounted read-write: the working directory, configured
113 additional roots, `/tmp` and `TMPDIR` unless excluded, and verified Git
114 worktree metadata roots. Existing `.codewhale` and `.deepseek` descendants are
115 remounted read-only after their writable parent. Missing paths, non-directory
116 paths, and `/` are not promoted to writable mounts.
117
118 For `read-only`, there are no writable binds, so the working directory remains
119 inside the read-only root view; `TMPDIR` (with `TMP`, `TEMP` and `TMPPREFIX`)
120 points at the private tmpfs `/tmp`, which disappears with the sandbox. The PID
121 namespace is private too, so `ps` lists only the command's own processes. `--unshare-all` isolates the network namespace
122 by default. Codewhale adds `--share-net` only when the policy's
123 `network_access` is true. The agent `read_only: true` shell mode turns it on
124 only in Full Access (see [Subagents](SUBAGENTS.md)); it then shares the host
125 network namespace, including loopback and abstract unix sockets, like a
126 networked `workspace-write` shell. Bubblewrap does not filter either.
127 `danger-full-access` and `external-sandbox` bypass the local wrapper entirely.
128
129 If the user opts out, or `/usr/bin/bwrap` is missing, non-executable, or
130 cannot actually confine a child, Codewhale reports `none` and launches the
131 command without a Linux OS wrapper. There is no marker-only fallback to a
132 different Linux sandbox.
133
134 Install bubblewrap separately to get enforcement on Linux:
135
136 - Ubuntu/Debian: `apt install bubblewrap`
137 - Fedora: `dnf install bubblewrap`
138 - Arch: `pacman -S bubblewrap`
139
140 Codewhale does not vendor bubblewrap.
141
142 ### Running tools as another user
143
144 A host that must keep tool commands away from the Engine's own files (a cloud
145 computer, for example) can run every sandboxed command as a separate Linux
146 user. The managed configuration sets an argv prefix that changes user, and
147 pins a sandboxed mode beside it:
148
149 ```toml
150 sandbox_mode = "workspace-write"
151 tool_launcher = ["/usr/bin/sudo", "-n", "-u", "agent", "--", "/usr/local/bin/agent-exec"]
152 ```
153
154 The launcher goes in front of bubblewrap, not inside it: every unprivileged
155 confinement sets no-new-privileges, and a setuid program started under it
156 cannot switch user. The command becomes
157 `<launcher...> /usr/bin/bwrap ... -- <program> <args>`, so the tool runs as the
158 other user, with no-new-privileges, inside the same mounts, masks and network
159 namespace a local command gets. `--die-with-parent` stays, so a cancel or
160 timeout that kills the launcher ends the whole sandbox.
161
162 The key is read only from the managed configuration file named by
163 `CODEWHALE_MANAGED_CONFIG_PATH`, or from the default managed path, only on
164 Linux, and only when neither that file nor any directory above it can be
165 changed by the Engine's own user. A managed file at any other path (for
166 example one a user config points at through `managed_config_path`) is refused.
167 In a user `config.toml` or a profile the key is a load error. The managed
168 file must also set `sandbox_mode` itself; a sandboxed mode from a user config
169 does not count. Without the key, nothing on this page changes.
170
171 A host that relies on the launcher puts the managed file in a root-owned
172 place and sets `CODEWHALE_MANAGED_CONFIG_PATH` to it for the Engine's service.
173 The variable outranks a user config's `managed_config_path`, and a Fleet local
174 worker (a child `codewhale exec`) gets the parent's variable even though its
175 environment is otherwise cleaned; a worker request cannot replace it. Any
176 other `codewhale` process sees a file named only by the variable when it is
177 started with the variable. An MCP server entry that runs `codewhale serve
178 --mcp` is started with a cleaned environment and does not get it. A host that
179 relies on the launcher therefore also keeps the file at the default managed
180 path, or sets the variable in every such entry. A file named by the variable
181 or by `managed_config_path` that is missing or cannot be read is a load error,
182 not "no managed layer", and a user config cannot point `managed_config_path`
183 away from an existing file at the default managed path.
184 Only a missing file at the default path, with nothing naming another, means no
185 managed layer. A file in another ordinary user's home also passes the
186 "Engine's user cannot change it" check, so the file should be root-owned.
187 Check `sandbox.tool_launcher` in `GET /v1/runtime/info`: the route
188 reads the live configuration, but a check made once at start does not cover a
189 later reload, so ask again after a reload.
190
191 The launcher's first program runs as the Engine's user with the Engine's
192 allow-listed environment, the model-chosen working directory and stdin, so it
193 must ignore all three (a setuid switcher such as `sudo -n`, not a shell
194 script).
195
196 With a launcher configured:
197
198 - **Fail closed.** A command runs under bubblewrap or not at all. The Engine
199 probes the launcher (its user and groups, then one wrapped `/bin/true` with
200 the deny masks) before the first command; a failed probe,
201 `prefer_bwrap = false`, or a policy that would skip the sandbox
202 (`danger-full-access`, `external-sandbox`, including an approved per-command
203 escalation) refuses the command with the reason, and nothing runs. The
204 managed `sandbox_mode` must be `workspace-write` or `read-only`.
205 - **Masks for the other user.** Bubblewrap creates each mask as the
206 launcher's user, so every command's masks and binds are computed for that
207 user: a denied path below a directory it cannot search is masked at the
208 highest such directory, and a bind it cannot reach is dropped. The built-in
209 deny list stays on; it also guards the Engine's own file tools.
210 - **Private `/tmp`.** Each command gets a fresh tmpfs `/tmp`; the host `/tmp`
211 and `TMPDIR` are not bound, so the tool user cannot leave files there for the
212 Engine's user. Scratch files that must outlive one command belong in the
213 workspace.
214 - **Network** follows the policy as everywhere else: a managed
215 `sandbox_network_access = true` adds `--share-net`, and then only the host's
216 own firewall rules for the tool user fence it.
217 - **Runtime info.** `GET /v1/runtime/info` reports `sandbox.kind`
218 (`linux-bwrap` once the launcher probe passed) and `sandbox.tool_launcher`.
219
220 Limits: only commands the sandbox manager prepares (shell commands, terminal
221 sessions, workspace runners, `code_execution` and the Python kernels) go
222 through the launcher. In-process file tools,
223 MCP servers, hooks, LSP servers, the plugin host, external ACP agents and
224 the Engine's own `git`, formatter and diagnostic helpers still run as the
225 Engine's user. A language server starts only in a folder you trusted
226 permanently and approved for that server (`/lsp approve <name>`); once
227 approved it can run the project's build scripts, plugins and toolchain files.
228 A Fleet local worker is its own Engine, so its shell commands
229 go through the launcher only because it loads the same managed file.
230 `codewhale serve --mcp` does not run commands through the launcher. When the
231 managed file it loads sets a launcher, it does not expose `shell` or
232 `exec_shell`, whatever its own `expose_tools` lists; its file tools use the
233 built-in read deny list only. With `sandbox_backend = "opensandbox"` a shell command goes to
234 the remote backend before the launcher is consulted, so a launcher host pins
235 `sandbox_backend = "none"`, `prefer_bwrap = true` and `sandbox_network_access`
236 in the managed file. A `tool_launcher` in a project config stops an
237 interactive launch with an error; `serve` and `exec` do not read project
238 config, so there the key is ignored. Deny-list exceptions are not applied
239 under a launcher. Search rights come from mode bits and group membership, not
240 ACLs. Processes keep running after the Engine itself dies, until bubblewrap's
241 parent exits.
242
243 ## Windows: no advertised OS sandbox
244
245 The Windows command path currently reports no OS sandbox. The source tree has
246 a future helper contract for Job Object process-tree cleanup, but it is not
247 wired into selection and must not be described as any of the following:
248
249 - read-only filesystem or workspace-write enforcement;
250 - network blocking;
251 - registry isolation;
252 - restricted-token or AppContainer isolation.
253
254 Windows host permissions and approval policy still apply, but they are not a
255 Codewhale OS command sandbox.
256
257 ## Linux process hardening is not a command sandbox
258
259 At startup on Linux, Codewhale best-effort applies `PR_SET_DUMPABLE=0`,
260 `PR_SET_NO_NEW_PRIVS=1`, and `RLIMIT_CORE=0` to its own process. Each failure is
261 logged and startup continues. These controls reduce process-inspection,
262 privilege-escalation, and core-dump risk; they do not create filesystem or
263 network isolation for a child command and are not listed as a sandbox backend.
264
265 The one exception is the startup posture itself: when the startup sandbox mode
266 resolves to `danger-full-access` (via `CODEWHALE_SANDBOX_MODE` or the config
267 file's `sandbox_mode` key), `PR_SET_NO_NEW_PRIVS` is skipped so that
268 `sudo`/`su`/setuid helpers keep working from the agent shell (#5723) — "full
269 access" means it. Every narrower posture keeps the flag as defense-in-depth,
270 and `CODEWHALE_NO_NEW_PRIVS` overrides the posture in both directions
271 (#5413): a falsey value always skips the flag, a truthy value always sets it.
272 The flag is irreversible for the process tree, so the decision can only be
273 made at launch; per-call sandbox escalation inside a session cannot lift it.
274
275 ## External OpenSandbox execution
276
277 When `sandbox_backend = "opensandbox"` is configured, shell execution is sent
278 to the configured OpenSandbox-compatible HTTP endpoint instead of starting a
279 local child. Codewhale validates the request/response contract, but isolation
280 guarantees belong to the configured service and its operator.
281
282 ```toml
283 sandbox_backend = "opensandbox"
284 sandbox_url = "http://localhost:8080"
285 sandbox_api_key = "YOUR_API_KEY"
286 ```
287
288 `sandbox_backend = "none"` (or omitting the key) keeps local execution.
289 Unsupported backend settings refuse shell execution; they never silently select
290 local execution. Choose a supported backend or explicitly select `none`.
291
292 ## Policies and fallbacks
293
294 ### Named sandbox profiles
295
296 Codewhale defines four named sandbox profiles (`SandboxProfile`):
297
298 | Profile | Policy | Default | Notes |
299 |---|---|---|---|
300 | `workspace` | `workspace-write` (no network) | **Default-on** when OS probe succeeds | Writes inside the workspace and temp dirs; `~/.ssh`, `~/.aws`, `.env`, and `.env.*` stay blocked by default |
301 | `read-only` | `read-only` (no network) | | Blocks shell writes; reads stay subject to deny globs |
302 | `strict` | `workspace-write` (no network, excludes `/tmp` and `TMPDIR`) | | Tightest writable posture; no shared host temp dirs and no network |
303 | `off` | `danger-full-access` | | Bypasses the local OS wrapper entirely |
304
305 ### Project overlay (`.codewhale/sandbox.toml`)
306
307 A workspace may ship an optional `.codewhale/sandbox.toml` overlay to customize
308 the active sandbox profile and kernel-enforced rules:
309
310 ```toml
311 extends = "strict" # workspace | read-only | strict | off
312 restrict_network = true # false allows network; Linux uses network namespace isolation (--unshare-all / --share-net)
313 read_only = ["docs"] # narrowed to read-only even inside a writable workspace
314 read_write = ["target"] # additional writable directories
315 deny = ["secrets/*.key", "**/*.pem"]
316 ```
317
318 - **Monotonic tightening:** A repository `.codewhale/sandbox.toml` can only
319 narrow the active caller policy — it can never widen `workspace` or
320 `read-only` to `off`, cannot enable network when the caller disabled it, and
321 confines `read_write` strictly inside the workspace (ignoring `read_write` in
322 `read-only` mode). Symlinked `.codewhale` directories or `sandbox.toml` files
323 and control characters are rejected.
324 - **Default deny globs:** `~/.ssh`, `~/.aws`, `.env`, and `.env.*` remain
325 blocked by default for every sandboxed profile (with or without an overlay).
326 - **macOS (Seatbelt):** `read_only` emits last-match-wins `(deny file-write* (subpath ...))`
327 rules and `deny` globs compile to anchored `(deny file-read* file-write* (regex #"..."))`
328 rules enforced by the kernel.
329 - **Linux (bubblewrap):** `read_only` paths are remounted with `--ro-bind` after
330 writable binds, `deny` globs are expanded to matching paths and masked with
331 `--tmpfs` (directories) or `--ro-bind /dev/null` (files), and network
332 namespace isolation (`--unshare-all` without `--share-net`) is Linux-only.
333 - **Windows:** No local OS sandbox wrapper is advertised; `.codewhale/sandbox.toml`
334 does not create OS-level filesystem or network isolation on Windows.
335
336 The local `sandbox_mode` values are:
337
338 ```toml
339 sandbox_mode = "workspace-write" # read-only | workspace-write | danger-full-access | external-sandbox
340 ```
341
342 - `read-only` and `workspace-write` are enforced by Seatbelt or bubblewrap only
343 when that wrapper is selected and available.
344 - The configured value can only narrow the sandbox the permission mode
345 picks: Full Access (`yolo`) runs without the wrapper, Ask and [Auto-Review](AUTO_REVIEW.md)
346 use `workspace-write`, and Plan uses `read-only`. A configured
347 `danger-full-access` or `external-sandbox` therefore takes effect only in
348 Full Access; it never loosens Ask or Auto-Review.
349 - `danger-full-access` deliberately bypasses the local OS wrapper. On Linux it
350 also skips the `PR_SET_NO_NEW_PRIVS` process-hardening flag at startup so
351 `sudo`/setuid workflows keep running (#5723); see the process-hardening
352 section above.
353 - `external-sandbox` declares that execution is already externally isolated
354 and bypasses a second local wrapper.
355 - When no wrapper is selected, the shell command runs without Codewhale OS
356 isolation. Approval rules and workspace-aware native file tools remain
357 separate controls.
358 - The persistent Python kernels (`rlm` sessions, inline `repl` fences) obey the
359 same policy: they start through the launcher `code_execution` uses, so a
360 configured `sandbox_mode` that narrows Full Access narrows them too, a
361 read-only policy with no enforcing wrapper refuses to start one, and an
362 `opensandbox` backend starts no local kernel. A kernel is dropped when the
363 sandbox policy it started under changes; dropping it stops the
364 interpreter, not a background process its code already started. Its long
365 input travels over stdin, so a private `/tmp` or a read-only filesystem does
366 not hide it.
367
368 Canonical environment overrides exist for `sandbox_mode` and the external
369 backend:
370
371 - `CODEWHALE_SANDBOX_MODE`
372 - `CODEWHALE_SANDBOX_BACKEND`
373 - `CODEWHALE_SANDBOX_URL`
374 - `CODEWHALE_SANDBOX_API_KEY`
375
376 `CODEWHALE_PREFER_BWRAP` (legacy alias `DEEPSEEK_PREFER_BWRAP`) overrides the
377 preference explicitly; the top-level `prefer_bwrap` config key is the durable
378 setting.
379
380 ## Diagnostics and failure attribution
381
382 `codewhale setup --status`, `codewhale doctor`, `codewhale doctor --json`, and
383 the `diagnostics` tool report the locally available wrapper after applying the
384 resolved bubblewrap preference. An individual command can still bypass that
385 wrapper when its policy does not request sandboxing. On Linux, merely finding
386 a sandbox-related syscall or source module does not make `sandbox_available`
387 true.
388
389 Denial attribution is intentionally conservative:
390
391 - Seatbelt uses its wrapper-specific denial patterns.
392 - Bubblewrap setup errors must be prefixed by `bwrap:`; a read-only-filesystem
393 error from the bwrap filesystem view can also identify the boundary.
394 - A child command's generic `Permission denied` or `Operation not permitted`
395 is not, by itself, proof that Codewhale's sandbox blocked it.
396 - Unsandboxed command failures are never labeled sandbox denials.
397
398 ## Limitations
399
400 - Local stdio MCP servers are started as ordinary child processes with a
401 scrubbed environment and no OS sandbox wrapper, and Codewhale does not check
402 MCP tool arguments against the workspace boundary, the read deny-list
403 (`sandbox_denied_read_paths`), or repository law. Approval, exact-name
404 permission rules (with no `path`), and `enabled_tools` / `disabled_tools` on
405 the server are what apply; see [MCP](MCP.md#safety-notes).
406 - Availability is checked before launch; the selected wrapper can still fail
407 because of host policy, container restrictions, or a race after the probe.
408 - Bubblewrap ignores a configured writable root if it is missing, is not a
409 directory, or canonicalizes to `/`; a path can also disappear between policy
410 resolution and wrapper launch.
411 - Seatbelt profiles are generated at runtime and must be tested against the
412 commands they are expected to support.
413 - No current local wrapper is advertised on Windows.
414 - An external sandbox backend is only as strong as its configured service.
415 - No sandbox protects against kernel vulnerabilities or all resource-exhaustion
416 and side-channel attacks.
417
418 ## Implementation references
419
420 - `crates/sandbox/src/lib.rs` — truthful selection and public capability markers
421 - `crates/sandbox/src/seatbelt.rs` — macOS wrapper and availability probe
422 - `crates/sandbox/src/bwrap.rs` — Linux wrapper and functional availability probe
423 - `crates/sandbox/src/process_hardening.rs` — Linux parent-process hardening
424 - `crates/sandbox/src/backend.rs` — external backend selection
425 - `crates/engine/src/tools/diagnostics.rs` — machine-readable diagnostics
426
426 lines MARKDOWN