Skip to content

Studio: harden the tool sandbox around host launches, probes and workdir paths - #14429

Merged
danielhanchen merged 8 commits into
mainfrom
studio-tool-sandbox-hardening
Oct 21, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-tool-sandbox-hardening

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Hardening from a security review of the Studio tool sandbox. Sandboxed Python / Terminal calls, Full access, Sandbox Low and chosen project folders run exactly as before; the visible changes are inside approved host-access calls and on hosts that run out of resources, described below.

Changes

  • Approved host-access calls no longer load anything from the chat folder (tools.py). When the user approves a Python or Terminal call that reaches host paths, it runs outside the OS sandbox, but it still took HOME (the chat folder), its script file and the session-packages PYTHONPATH entry from the chat folder, which earlier sandboxed calls can write. A planted csv.py, .gitconfig or a script swapped between approval and launch therefore ran on the host. Now such a call gets a private per-call directory (0700, removed afterwards) for HOME and for the approved script, which is written there from the approved text rather than read back from the chat folder, with PYTHONSAFEPATH=1. Packages pip-installed earlier in the chat stay importable, but appended after the stdlib and installed packages, so they cannot shadow either; their bin stays off PATH. The working directory is still the chat folder, so relative paths behave as before.
  • The jail sees /proc/sys read-only (sandbox_linux.py). bwrap's --proc /proc is a fresh mount that --remount-ro / does not cover; on a root-run server (no user-namespace remap) that left host sysctls writable from tool code. --ro-bind-try /proc/sys /proc/sys follows the --proc pair.
  • Cache binds use the real cache home (sandbox_linux.py). datasets / assets binds came from the display cache home, which effective_cache_home() warns against when HF_HUB_CACHE is set separately; they now use effective_cache_home().
  • A resource-exhausted sandbox probe refuses instead of running on the host (sandbox_probe.py, os_sandbox.py). In auto mode a failed probe meant "no sandbox on this host" and the call fell back to running unsandboxed; tool code could cause that by filling the disk or the file table. A probe failing with ENOSPC / EDQUOT / EMFILE / ENFILE / ENOMEM / ENOBUFS is now undecided: never cached, and the call is refused with OS_ISOLATION_UNAVAILABLE ... Free them and try again. The next call probes again. A host that genuinely has no sandbox falls back exactly as before.
  • The stale-IPC sweep cannot be redirected (os_sandbox.py). clear_stale_tool_ipc lstat-ed and unlinked by path inside a jail-writable tree; it now walks with os.fwalk and unlinks through the directory fd after re-checking device and inode (Windows keeps the old walk).
  • A project sandbox folder swapped for a link is dropped (tools.py, _get_project_workdir), the rule the per-chat workdir already applies.

All of these are per-launch decisions or argv / env construction; nothing is persisted, so repeating them is a no-op.

Tests. New test_tool_sandbox_hardening.py (13 tests): on main the approved host call runs the planted csv.py, --dev follows --proc with no /proc/sys bind, datasets bind from the display home, the ENOSPC / EMFILE probes fall back to the host, the IPC sweep deletes the planted host file, and the project link is followed; all pass here, including a session package still importing in an approved host call. test_sandbox_linux.py stubs gain effective_cache_home. The sandbox, permission-mode, probe, sitecustomize and tool suites (4108 tests) have the same 3 failures on both sides (cases that need a working bwrap).

…dir paths

- Approved host-access calls no longer read anything the sandbox can write:
  HOME and the python tool's script move to a private per-call directory
  outside the chat folder, PYTHONSAFEPATH is set for the script, and the
  session packages stay off PYTHONPATH and PATH. The cwd is still the chat
  folder. Sandboxed launches and chosen project folders are unchanged.
- bubblewrap: mount /proc/sys read-only over the fresh procfs.
- bubblewrap: bind the datasets and assets caches from the effective HF home
  rather than the display cache home.
- A sandbox probe that fails on host resource exhaustion (disk full, quota,
  file or memory limits) is undecided: not cached, and auto refuses the call
  instead of running it without the sandbox. Hosts without a sandbox keep
  the software-safeguards fallback.
- The stale IPC sweep walks the scratch directory by directory fd, so a
  directory swapped for a link mid-sweep cannot redirect the unlink.
- A project sandbox folder that became a symlink, or that resolves to the
  project root, is dropped like a per-chat folder that became one.
@danielhanchen danielhanchen self-assigned this Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-21T06:07:50.451567Z f1b8e03 Manual request
🔒 Security Review 🔄 Running since 2026-10-21T02:27:28.271462Z 6af91ef Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6af91ef5ce

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if sys.platform == "win32":
env["HOMEDRIVE"], env["HOMEPATH"] = os.path.splitdrive(private)
argv = tuple(plan.argv)
if script is not None and argv:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Harden interpreters launched by approved Terminal calls

When an approved Terminal command reaches a host path, _bash_exec passes host_script=None, so this branch is skipped and PYTHONSAFEPATH is never set. Because the host launch retains the chat directory as its cwd, a command such as python -c 'import csv; ... /host/path ...' imports a previously planted csv.py from that sandbox-writable directory and executes it with unrestricted host access, despite the new private HOME. Apply the safe-path protection to Terminal host launches as well (and cover this path with the planted-module test).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intentional: approved Terminal calls keep normal Python path semantics so a user's own python main.py with sibling modules in the chat folder keeps working; the approval card shows the exact command. The script swap, HOME and session-package routes are closed; cwd imports for an explicitly approved terminal command are the accepted residual.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 51d59c6865

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…roc/sys in the empty layout, refuse a junction project sandbox

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 64b0aa01db

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

with os.fdopen(fd, "w", encoding = "utf-8") as f:
f.write(
"import runpy, sys\n"
f"sys.path.append({packages!r})\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep sandbox-writable packages out of host launches

When an approved Python call imports a package available only in .unsloth-packages, this append executes that sandbox-writable package without OS isolation; putting it last only prevents it from shadowing an already-installed module. A prior sandboxed call can replace such a package with code that reads arbitrary host files, and the later approval shows only the benign script and its named host path, not the planted dependency. Unlike the earlier Terminal-path report, the fresh evidence here is the Python-only launcher explicitly reintroducing .unsloth-packages after moving the script off the workdir.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this, as with the Terminal case earlier. Packages installed in the chat stay importable in an approved host call on purpose (that flow is how users run what they installed), and they come after the stdlib and installed packages, so they cannot shadow either. A host call is owner-approved code execution already.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1b8e036bf

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +70 to +71
except (OSError, ValueError):
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fail closed when the namespace quota cannot be read

On Linux hosts where /proc/sys/user/max_user_namespaces is hidden, unreadable, or malformed, this exception path treats user namespaces as permanently disabled. If bwrap then reports namespace ENOSPC because the nonzero quota is temporarily exhausted, _run_probe skips the UndecidedReason path, caches an unavailable verdict, and auto launches fall back to the unisolated host. Fresh evidence beyond the earlier quota report is that the newly added read-error fallback explicitly equates an unknown quota with zero; return an unknown/undecided state instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one. It needs a kernel that hides max_user_namespaces and a temporarily exhausted quota at the same probe; failing closed on an unreadable value would instead stop tools entirely on hosts that genuinely have no user namespaces, which is the case the fallback exists for.

Comment on lines +468 to +469
else:
walk = ((*step, None) for step in os.walk(scratch, followlinks = False))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refuse Windows junctions before sweeping IPC

On Windows, where os.fwalk is unavailable, this fallback retains the path-based walk and unlink even though the initial os.path.islink guard does not detect directory junctions. A sandboxed process can replace unsloth-tmp or a nested directory with a junction to a host directory; the unrestricted sweep then follows it and removes a dead host socket before MXC's later reparse-point scan can reject the workdir. Skip the sweep on Windows or reject reparse points and delete through non-following handles.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this. The Windows sweep only unlinks stale sockets and IPC files it finds, so following a junction can at worst remove a dead socket on the host; no data is read or written, and the MXC workdir check still rejects the reparse point before any launch.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 21, 2026
@danielhanchen
danielhanchen merged commit 96e7534 into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the studio-tool-sandbox-hardening branch October 21, 2026 06:27
JadeCong pushed a commit to CloudEngineHub/unsloth that referenced this pull request Oct 23, 2026
…les and CLIs (unslothai#14543)

Follow-up to unslothai#14429.

**Problem.** If a call reaches a host path (for example, a command that
reads a file in the user's home) and the user approves it, it runs
outside the chat sandbox with a private HOME. unslothai#14429 also stopped
loading anything from the chat folder in these calls, because sandboxed
calls can write there. That broke three things that worked before
unslothai#14429:

- Python started by an approved Terminal command lost the packages
installed in the chat (`.unsloth-packages`). In an owner chat, install
`openpyxl` through Terminal, then approve `python -c "import openpyxl
..." ~/sales.xlsx`: it failed with `ModuleNotFoundError`. unslothai#14429
restored these packages for the Python tool through a small launcher,
but the launcher only exists when there is a script.
- An approved Python tool call could no longer `import helper` for a
`helper.py` that an earlier call wrote into the chat folder. The script
now runs from a private dir with `PYTHONSAFEPATH=1`, so the chat folder
is not on `sys.path`.
- Command-line tools that pip put in `.unsloth-packages/bin` (for
example `black file.py`) were no longer found in approved calls
(`command not found`).

**Change.**
- The approved host launch puts the chat's packages folder in
`_UNSLOTH_HOST_SESSION_PACKAGES` and the chat folder in
`_UNSLOTH_HOST_WORKDIR`. The existing sandbox `sitecustomize`, which is
already first on that launch's PYTHONPATH, appends the packages folder
to the end of `sys.path` after normal site setup. The chat folder is not
put on `sys.path`. For an approved Python tool call, the launch passes
the top-level module names the script itself imports (parsed with
`ast`), and a finder appended at the end of `sys.meta_path` serves only
those names from the chat folder, only when nothing else provides them,
and never `sitecustomize` or `usercustomize`. A library probing an
optional import never reaches the chat folder. The packages folder works
for the Python tool and for any Python a Terminal command starts, and it
replaces the per-script launcher.
- Chat-installed CLIs in `.unsloth-packages/bin` (`Scripts` on Windows)
resolve only when the approved command or script names them: those files
are copied into the call's private directory, which goes last on PATH.
The chat bin folder itself is never on PATH, so a tool probing for a
command it lacks (for example `ffmpeg`) never reaches it.
- Both folders come after the standard library, installed packages and
system executables, so nothing planted there can shadow them. A
`json.py` or `os.py` in the chat folder, or a `cat` in
`.unsloth-packages/bin`, is never picked up first, and an unnamed CLI
there is never picked up at all. The approved script still runs from the
private dir with `PYTHONSAFEPATH=1`. A planted `usercustomize.py` never
runs: `PYTHONNOUSERSITE=1` is set when the packages folder exists, and
the chat folder finder skips startup hooks, so `~/.local` packages keep
working for a system Python. HOME stays private.
- Sandboxed calls, and launches that are not approved host access, are
unchanged. The env is built fresh for every launch, and `sitecustomize`
skips a path that is already on `sys.path`, so repeat runs give the same
result.

Terminal commands still run with the chat folder as cwd. So `python -c`
in Terminal keeps its usual cwd-first imports, as unslothai#14429 left them.

**Testing.**
- New
`test_an_approved_terminal_call_reuses_chat_packages_without_shadowing`:
an approved Terminal `python -c` imports a chat-installed package and
reads a host file, twice. A planted `usercustomize.py` does not run.
Fails on main, passes here.
- New
`test_approved_calls_import_chat_helpers_without_shadowing_the_stdlib`:
an approved Python tool call imports `helper.py` from the chat folder,
twice. Planted `json.py` / `os.py` in the chat folder are not loaded,
and `json` comes from the standard library. An approved Terminal `python
-c` also imports the helper. Fails without this change
(`ModuleNotFoundError: No module named 'helper'`), passes with it.
- New `test_an_approved_terminal_call_runs_chat_clis_after_system_ones`:
an approved Terminal call runs a CLI from `.unsloth-packages/bin`. A
planted `cat` there does not replace the system `cat`. Fails without
this change (`chatcli: command not found`), passes with it.
- `test_an_approved_host_launch_env_drops_every_workdir_input` now
checks that the chat `bin` is only the last PATH entry.
- New `test_chat_folder_only_supplies_the_helpers_the_script_imports`:
checks the import-name parsing, and that with the chat folder exposed
for `helper`, neither `usercustomize` nor an unrequested `optional_dep`
can be found while `helper` imports, twice. Checked by hand against the
previous finder: a planted `optional_dep.py` loaded there and does not
now.
- Earlier version of the same test: with the chat folder exposed,
`usercustomize` cannot be found while `helper` still imports, and the
chat folder is not on `sys.path`. Fails if the chat folder is appended
to `sys.path` instead. Also checked by hand with the system
`/usr/bin/python3` (user site enabled): a planted `usercustomize.py` ran
before this change and does not now.
- `test_tool_sandbox_hardening.py`: 27 passed after the name allowlist.
With `test_managed_tool_confinement_hardening.py` and
`test_sandbox_sitecustomize.py`: 58 passed, 1 skipped.
- All `test_tool*.py`, `test_sandbox_linux.py`, `test_sandbox_probe.py`,
`test_sandbox_sitecustomize.py` (29 files): 1336 passed, 3 skipped.
- `test_an_approved_terminal_call_runs_chat_clis_after_system_ones` now
also checks that a `command -v` probe for a chat CLI the command never
names misses the chat folder, and
`test_an_approved_host_launch_env_drops_every_workdir_input` that the
chat bin folder is not on PATH. Both fail without the CLI scoping and
pass with it; `test_tool_sandbox_hardening.py`: 27 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant