Repository navigation
Studio: OS level sandbox for python/bash tool execution (macOS + Linux) - #5468
NilayYadav wants to merge 40 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces OS-level sandboxing for tool execution on macOS and Linux using Seatbelt and bubblewrap. It includes a new sandbox.py module, updates tools.py to apply sandboxing to Python and Bash tasks, and adds a startup notice for missing sandbox dependencies. Feedback pointed out redundant path processing in the Linux sandbox configuration, recommending a cleaner approach using existing helper functions.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10b1544b2c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
This PR appears to address open issue(s). The duplicate detector matched the following open issues with HIGH confidence:
If this PR fixes any of them, consider adding |
|
This PR appears to address open issue(s). The duplicate detector matched the following open issues with HIGH confidence:
If this PR fixes any of them, consider adding |
danielhanchen
left a comment
There was a problem hiding this comment.
Review summary
The direction is right — wrapping _python_exec / _bash_exec through Seatbelt or bubblewrap, plus the startup banner and test_sandbox.py, all line up with the stated threat model. Local review (12 parallel reviewers + manual read) returned a strong REQUEST_CHANGES consensus on a few concrete issues. The top three are blockers; the rest are smaller follow-ups.
P1 — Fails open when the OS sandbox is unavailable
_python_exec / _bash_exec fall back to the original unsandboxed argv whenever sandbox_available() returns False. This is a realistic trigger: on a host where /usr/bin/bwrap exists but unprivileged userns is disabled (cloud VMs with kernel.unprivileged_userns_clone=0, hardened distros, nested containers), the probe fails with bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted and the runtime silently runs the LLM's tool calls against the host filesystem — the exact threat the PR is meant to remove.
Multiple reviewers reproduced this: with pytest -q studio/backend/tests/test_sandbox.py the enforcement tests reported 1 passed, 5 skipped, and a _bash_exec("cat $HOME/<sentinel>") against the post-PR tree leaked the sentinel just like the pre-PR tree.
Suggested fix: gate _python_exec / _bash_exec to refuse to run when sys.platform in ("darwin", "linux") and sandbox_available() is False, returning a clear error and letting the unsandboxed path apply only on Windows (where there is no implementation yet) or when an operator explicitly opts in via env var.
P1 — Linux argv binds /etc wholesale
_linux_bwrap_argv() includes /etc in top_ro_dirs and ro-binds it, which exposes /etc/passwd, /etc/shadow metadata, /etc/hosts, /etc/machine-id, /etc/hostname, /etc/resolv.conf, plus any third-party application configs / tokens that landed there. The existing Python AST gate in tools.py already classifies open("/etc/passwd") / open("/etc/shadow") / /etc/ssh/ as sensitive-file reads and blocks them — the new sandbox bind silently re-grants them at the OS layer.
Suggested fix: drop /etc from top_ro_dirs and bind only the specific files the loader / TLS stack actually needs (/etc/ssl, /etc/ca-certificates, /etc/nsswitch.conf, /etc/resolv.conf, /etc/localtime, /etc/alternatives). Then add a regression test that asserts /etc/passwd and /etc/machine-id are not readable from inside the sandbox while basic Python startup still works.
P1 — Linux probe vs runtime privilege mismatch (setuid bwrap)
_linux_probe() execs bwrap directly, but _python_exec / _bash_exec set preexec_fn=_sandbox_preexec, which calls prctl(PR_SET_NO_NEW_PRIVS, 1, ...) before execing bwrap. On hosts that fall back to setuid bubblewrap (because unprivileged userns is disabled), no_new_privs blocks the setuid transition — so the probe can mark the sandbox available, cache that, and then every real tool call dies inside execve. This is the same shape as the chatgpt-codex-connector[bot] inline comment at sandbox.py:81, and is not addressed by the current code.
Suggested fix: either probe through the same _sandbox_preexec (so the probe matches runtime behavior) or skip PR_SET_NO_NEW_PRIVS specifically when the next exec is bwrap and bwrap is setuid. A fake-bwrap harness that returns success without NoNewPrivs=1 set in /proc/self/status and refuses otherwise is a good regression test.
P2 — Symlinked workdir breaks tool execution under bwrap
_linux_bwrap_argv() binds os.path.realpath(workdir) but _python_exec writes tmp_path under the original workdir path and the child runs with cwd=workdir. When ~/studio_sandbox (or any component) is a symlink — a normal setup when users move scratch space to another disk — the child's cwd and tmp_path resolve to the unmounted symlink path inside the sandbox and python <tmp_path> fails with ENOENT.
Suggested fix: keep the rw bind, but with --bind <realpath_wd> <original_workdir_path> so the symlinked path the child was handed remains valid inside the namespace.
P2 — Enforcement tests skip-pass when sandbox is unavailable
test_sandbox.py uses pytest.skip("sandbox unavailable ...") when sandbox_available() is False. The _sbtest_off control test still passes (it only asserts the sentinel is readable when the sandbox is off), so on a CI runner without working bubblewrap the file reports 1 passed, 5 skipped and the PR looks green without ever exercising the new boundary. Combined with P1, this is how the fail-open path can ship undetected.
Suggested fix: when CI (or UNSLOTH_REQUIRE_SANDBOX_TESTS=1) is set, pytest.fail instead of pytest.skip, and pin a Linux CI job that apt install bubblewrap and (if needed) enables unprivileged userns so the enforcement path is the path actually tested.
Smaller items
test_network_deniedtreats any exception during theurllib.requestimport / setup as proof of network denial. A sandbox that broke an unrelated runtime read could pass it without ever attempting a connect. Switch tosocket.create_connection(("wikipedia.org", 443))after a successfulimport socketso the assertion is about the egress, not the import path.- macOS
_safe_subpathcleanly rejects quote / backslash / newline in profile literals — that's correct. The bigger profile worry is(subpath "/private/etc")mirroring the Linux/etcissue; the same narrowing applies. - The
gemini-code-assist[bot]redundancy comment onsandbox.py:343reads more like older feedback — the current code is already a singlefor rp in _python_read_paths(): if not _is_under_top_ro(rp): ro-bindloop and looks fine.
Test results / how this was reviewed
- Malicious scan:
malicious_check.pyclean (1 chunk, no static findings). - Local reviewer pool:
reviewer.pyran 12 parallel reviewers (8 personas + 4 generic). Verdict tally: 11x REQUEST_CHANGES, 1x APPROVE. - A parallel
claude_revieworchestrator session is also running against this PR head; it has already labeled the PR and will post its own iteration findings.
Overall direction is sound and the pre-PR leak this targets is real. Suggest landing the fail-closed gate plus the /etc narrowing first, then revisiting the no-new-privs / setuid path and the symlink-workdir bind together, since they all share the same fixture once enforcement tests stop skip-passing.
|
Auto-review verdict: Changes requested Reason: Deterministic gate: accumulated test(s) regressed after post_sim_commit at iteration 1 (1 regression event(s) total) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 49cfdb1533
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| logger = get_logger(__name__) | ||
|
|
||
| _SANDBOX_EXEC = "/usr/bin/sandbox-exec" | ||
| _BWRAP_PROBE_BIN = "/usr/bin/true" |
There was a problem hiding this comment.
Avoid hardcoding /usr/bin/true in Linux sandbox probe
The Linux availability probe hardcodes _BWRAP_PROBE_BIN to /usr/bin/true, which causes sandbox_available() to return false on non-FHS layouts (for example systems where /usr/bin/true is absent but bwrap is installed and working). In that case all Python/bash tool calls run permanently unsandboxed for the process lifetime, even though bubblewrap support exists, which is a security regression relative to the intended sandboxing behavior.
Useful? React with 👍 / 👎.
Why the existing sandbox-hardening code is edited: `_sandbox_preexec` (tools.py) and its `_libc.prctl(PR_SET_NO_NEW_PRIVS)` block exist because prior commits introduced them to harden tool subprocesses. That contract is preserved: the original function is renamed to `_sandbox_preexec_impl(apply_no_new_privs)` and a same-named `_sandbox_preexec` wrapper calls it with `apply_no_new_privs=True`, so every direct caller still sets NNP. The new `_sandbox_preexec_for_bwrap` skips NNP only on the Linux+bwrap path where bwrap itself reapplies NNP to the inner payload (setuid-helper bwrap installs cannot acquire helper privileges if NNP is set before execve). Net result: the inner sandboxed program still runs with NNP=1. The `if sys.platform != "win32": popen_kwargs["preexec_fn"] = ...` / `else: popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW` blocks in `_python_exec` and `_bash_exec` are reorganised, not removed: the non-Windows path still sets `preexec_fn` and the Windows path still sets `CREATE_NO_WINDOW`. The only behavioural delta is the bwrap branch (Linux + sandbox_available) selecting `_sandbox_preexec_for_bwrap` per above. `_workdirs[key] = workdir` (tools.py:_get_workdir) is replaced with `_workdirs[key] = os.path.realpath(workdir)`. Same caching behaviour; the realpath normalization is required because the bwrap argv binds `os.path.realpath(workdir)` while `tempfile.mkstemp(dir=workdir)` builds tmp_path from the non-realpath value, so on hosts where HOME or a parent is a symlink the script path passed via inner_argv is not reachable inside the sandbox namespace. studio/backend/core/inference/sandbox.py Narrow Linux /etc bind from the whole directory to a runtime allowlist (hosts, resolv.conf, nsswitch.conf, localtime, ld.so.cache, ld.so.conf and ld.so.conf.d, ssl, ca-certificates, pki) so sandboxed tools cannot read sshd_config, machine-id, cloud-init data, etc. Narrow Seatbelt /private/etc the same way; replace the broad subpath with literal entries for hosts, resolv.conf, nsswitch.conf, localtime, protocols, services and subpaths for ssl and ca-certificates. Constrain Seatbelt allow process-exec to the same subpaths already used in file-map-executable so sandboxed Python cannot exec arbitrary system binaries such as osascript. Remove allow file-read and file-write on literal /dev/tty from the Seatbelt profile; tool output is captured via PIPE and there is no legitimate path that needs to bypass it. Gate site.getusersitepackages behind UNSLOTH_STUDIO_SANDBOX_ALLOW_USER_SITE=1 so the sandbox no longer binds the real ~/.local/lib subtree by default (HOME is already rewritten to workdir for the child). Resolve _BWRAP_PROBE_BIN via shutil.which at module load with the /usr/bin/true fallback, so the probe works on Alpine and BusyBox layouts that place coreutils under /bin instead of /usr/bin. Replace the unreachable _linux_bwrap_path-or-bwrap fallback with an assertion that names the sandbox_available contract; same for the unreachable RuntimeError in build_sandbox_argv. studio/backend/run.py Run sandbox_available on a background thread with a 2s bounded wait. On hardened kernels (unprivileged_userns_clone=0) the probe hangs for its full 5s timeout; running it inline delayed the access banner. The probe still runs (and caches) eagerly; if it has not reported back within 2s the banner is printed first and the unavailable notice is suppressed for this call.
Why the existing sandbox-hardening code is edited: `_sandbox_preexec` (tools.py) and its `_libc.prctl(PR_SET_NO_NEW_PRIVS)` block exist because prior commits introduced them to harden tool subprocesses. That contract is preserved: the original function is renamed to `_sandbox_preexec_impl(apply_no_new_privs)` and a same-named `_sandbox_preexec` wrapper calls it with `apply_no_new_privs=True`, so every direct caller still sets NNP. The new `_sandbox_preexec_for_bwrap` skips NNP only on the Linux+bwrap path where bwrap itself reapplies NNP to the inner payload (setuid-helper bwrap installs cannot acquire helper privileges if NNP is set before execve). Net result: the inner sandboxed program still runs with NNP=1. The `if sys.platform != "win32": popen_kwargs["preexec_fn"] = ...` / `else: popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW` blocks in `_python_exec` and `_bash_exec` are reorganised, not removed: the non-Windows path still sets `preexec_fn` and the Windows path still sets `CREATE_NO_WINDOW`. The only behavioural delta is the bwrap branch (Linux + sandbox_available) selecting `_sandbox_preexec_for_bwrap` per above. `_workdirs[key] = workdir` (tools.py:_get_workdir) is replaced with `_workdirs[key] = os.path.realpath(workdir)`. Same caching behaviour; the realpath normalization is required because the bwrap argv binds `os.path.realpath(workdir)` while `tempfile.mkstemp(dir=workdir)` builds tmp_path from the non-realpath value, so on hosts where HOME or a parent is a symlink the script path passed via inner_argv is not reachable inside the sandbox namespace. studio/backend/core/inference/sandbox.py Narrow Linux /etc bind from the whole directory to a runtime allowlist (hosts, resolv.conf, nsswitch.conf, localtime, ld.so.cache, ld.so.conf and ld.so.conf.d, ssl, ca-certificates, pki) so sandboxed tools cannot read sshd_config, machine-id, cloud-init data, etc. Narrow Seatbelt /private/etc the same way; replace the broad subpath with literal entries for hosts, resolv.conf, nsswitch.conf, localtime, protocols, services and subpaths for ssl and ca-certificates. Constrain Seatbelt allow process-exec to the same subpaths already used in file-map-executable so sandboxed Python cannot exec arbitrary system binaries such as osascript. Remove allow file-read and file-write on literal /dev/tty from the Seatbelt profile; tool output is captured via PIPE and there is no legitimate path that needs to bypass it. Gate site.getusersitepackages behind UNSLOTH_STUDIO_SANDBOX_ALLOW_USER_SITE=1 so the sandbox no longer binds the real ~/.local/lib subtree by default (HOME is already rewritten to workdir for the child). Resolve _BWRAP_PROBE_BIN via shutil.which at module load with the /usr/bin/true fallback, so the probe works on Alpine and BusyBox layouts that place coreutils under /bin instead of /usr/bin. Replace the unreachable _linux_bwrap_path-or-bwrap fallback with an assertion that names the sandbox_available contract; same for the unreachable RuntimeError in build_sandbox_argv. studio/backend/run.py Run sandbox_available on a background thread with a 2s bounded wait. On hardened kernels (unprivileged_userns_clone=0) the probe hangs for its full 5s timeout; running it inline delayed the access banner. The probe still runs (and caches) eagerly; if it has not reported back within 2s the banner is printed first and the unavailable notice is suppressed for this call.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5de91f97d5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| if not silent: | ||
| _emit_startup_output(host, port, display_host) | ||
| if not silent: |
There was a problem hiding this comment.
Fix indentation that prevents backend startup
With the added sandbox startup probe, this if not silent: line is indented one space deeper than the surrounding run_server block, so studio/backend/run.py no longer parses at all (python -m py_compile studio/backend/run.py raises IndentationError on this line). Any path that imports or runs the backend entrypoint will fail before the server can start; align this block with the preceding if api_only: block.
Useful? React with 👍 / 👎.
| (literal "/private/etc/services") | ||
| (subpath "/private/etc/ssl") | ||
| (subpath "/private/etc/ca-certificates") | ||
| (literal "/dev/null") |
There was a problem hiding this comment.
Allow writes to /dev/null in the macOS sandbox
On macOS, this only permits /dev/null in the file-read* block while the only file-write* allow below is the workdir, so sandboxed commands that redirect output to /dev/null (or Python code using subprocess.DEVNULL) fail with a sandbox denial even though Linux gets a writable /dev/null via --dev /dev. This affects common harmless terminal/Python tool calls such as cmd >/dev/null once the Seatbelt sandbox is available; add a write allow for /dev/null.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5448db7c0e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # to refuse instead of falling back). On Ubuntu 23.10+ bwrap still | ||
| # needs apparmor_restrict_unprivileged_userns=0; that hint is in | ||
| # the banner too. | ||
| command -v bwrap >/dev/null 2>&1 || MISSING="$MISSING bubblewrap" |
There was a problem hiding this comment.
Teach the apt verifier that bubblewrap installs bwrap
When bubblewrap is added to MISSING, _smart_apt_install later verifies each package via _is_pkg_installed; the default verifier checks command -v "$pkg", but the Debian/Ubuntu bubblewrap package provides the bwrap executable, not a bubblewrap command. On root/container installs without sudo, the first apt-get install bubblewrap can succeed and the script still concludes it is missing, then exits in the sudo is not available path. Add a package-specific _is_pkg_installed bubblewrap) case that checks command -v bwrap.
Useful? React with 👍 / 👎.
| _PIPE_OR_REDIR = frozenset({"|", "<"}) | ||
| for i, tok in enumerate(tokens): | ||
| if tok not in _PIPE_OR_REDIR or i + 1 >= len(tokens): |
There was a problem hiding this comment.
Handle stdin-fed interpreter code
This redirect scan only catches | or a literal < when the interpreter appears after the operator, so stdin-fed forms like python - <<'PY' ... os.system('curl ...') ... PY or sh <<'EOF' ... EOF never run through _INTERP_DANGER_RE or the nested shell scanner. On hosts where the OS sandbox is unavailable and Studio falls back unsandboxed by default, those commands bypass the new interpreter-code hardening and can invoke blocked operations from the terminal tool. Include here-doc/here-string and interpreter-before-redirection forms, or refuse stdin-fed interpreter execution.
Useful? React with 👍 / 👎.
| # arbitrary code in that language. `python -c "import os; os.system('rm')"` | ||
| # from the bash tool would bypass the Python AST gate (only the python | ||
| # tool entry point invokes it). awk and gawk take the script positionally. | ||
| _LANG_INTERPRETERS_DASH_C_E = frozenset({"python", "python2", "python3", "perl", "ruby", "node"}) |
There was a problem hiding this comment.
Cover versioned Python interpreter names
The new -c/-e interpreter scanner only recognizes python, python2, and python3, but users commonly invoke the exact binary on PATH such as python3.12 or python3.13. In unsandboxed fallback mode, python3.12 -c 'import os; os.system("rm x")' is not matched by this set and the dangerous code string is never checked, bypassing the hardening this block is meant to add. Match version-suffixed Python basenames (and equivalent aliases) before deciding the -c argument is safe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 25e39b9f87
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # to refuse instead of falling back). On Ubuntu 23.10+ bwrap still | ||
| # needs apparmor_restrict_unprivileged_userns=0; that hint is in | ||
| # the banner too. | ||
| command -v bwrap >/dev/null 2>&1 || MISSING="$MISSING bubblewrap" |
There was a problem hiding this comment.
Do not make optional sandbox support block installation
Adding bubblewrap to MISSING makes the installer exit on Linux hosts where bwrap is absent and the user cannot install system packages (or is on a non-apt distro), even though the new runtime path explicitly falls back to AST/blocklist/env-whitelist defenses and prints a sandbox-unavailable banner unless strict mode is set. In those environments Studio could still run, but setup now stops before reaching that fallback; treat bubblewrap as a best-effort install/warning rather than a required build dependency.
Useful? React with 👍 / 👎.
This reverts commit 17f0025.
|
Confirmed _python_exec and _bash_exec in studio/backend/core/inference/tools.py still run as plain subprocesses on main, so the OS-level isolation here is worth having, and the strict-mode gate plus tests look sound. Note #7101 is going after the same gap with its own sandbox module, so the two will need reconciling before either lands. Could you also split the install.sh non-interactive privilege prompt rework into its own PR so this one stays limited to the sandbox layer, and confirm whether you want the fail-open default kept? @Lyxot could you take a look at this one? |
|
Thanks for this, and sorry it took a while to come back to it. We ended up consolidating the OS sandbox work into #10285, which covers the same Linux Bubblewrap and macOS Seatbelt ground plus a Windows backend, a capability probe so each host reports what it can actually enforce, a network allowlist proxy, and fail-closed tiers. That PR rewrites the same functions in Closing this as superseded by #10285 rather than leaving it open indefinitely. The approach here was the right one and it shaped what went into #10285, so thank you for it. If you spot anything in #10285 that is a step back from what you had, please say so on that PR. |
Summary
python_exec/bash_exectool subprocesses in an OS level sandbox: Seatbelt (sandbox-exec) on macOS, bubblewrap (bwrap) on LinuxWhy
The python and bash tools previously ran as plain subprocesses, a tool call could read anywhere the Studio user could read, write outside the workdir, and reach the network. Seatbelt ships with macOS and bubblewrap is a one-package install on every major Linux distro.
Testing
pytest -q studio/backend/tests/test_sandbox.py~/Desktopdenied,urllib.requestraises, write inside workdir succeedsapt install bubblewrap) — python tool:ls /shows only the bound dirs (bin sbin usr lib lib64 etc proc dev tmp home), DNS fails