Repository navigation
Studio: harden software sandbox against credential exfil and dynamic-path bypasses - #5603
danielhanchen wants to merge 48 commits into
Conversation
…(Patch A)
Static-string resolution in _extract_string_from_node was limited to bare
ast.Constant. Concatenated string literals and f-strings with constant
parts evaluated to ast.BinOp / ast.JoinedStr and slipped past the
open() sensitive-file check, so:
open('/etc/' + 'shadow') # ALLOWED before
open(f'/etc/{"shadow"}') # ALLOWED before
open('/etc/passwd') # BLOCKED before (literal)
The helper now resolves ast.BinOp(Add) of two resolvable strings and
ast.JoinedStr whose parts are themselves resolvable. The open()
sensitive-file check uses the helper instead of an inline ast.Constant
isinstance check, so the same widening covers concatenated/f-string
paths without changing what was already blocked.
Resolution is depth-capped at 6 to keep adversarial deep nesting from
blowing the stack. All other call sites of the helper
(_check_args_for_blocked, dynamic-arg shell-escape detection, HF upload
path-shape inspection) automatically inherit the broader resolution.
Closes open() gaps #4 and #6 from the documented 13-gap audit. Does not
attempt to model variable flow (gap #5 stays open by design — the OS
sandbox is the right layer for runtime flow).
Regression: 131/131 studio/backend/tests/test_sandbox_tools.py pass.
…ch B)
Adds _find_sensitive_paths() and wires it into _bash_exec (alongside the
existing _find_blocked_commands check) and into _check_args_for_blocked
(so the Python AST gate catches os.system('cat ~/.ssh/id_rsa') the same
way bash $ cat ~/.ssh/id_rsa is caught).
The pattern set is intentionally narrow — only clear-cut credential and
process-state targets:
Home-anchored (must be prefixed by ~, $HOME, ${HOME}, /home/<u>,
/root, /Users/<u>):
.ssh/id_rsa, .ssh/id_ed25519, .ssh/id_ecdsa, .ssh/id_dsa, .ssh/identity
.aws/credentials, .docker/config.json, .kube/config
.config/gcloud/{application_default_credentials,access_tokens,credentials}
.pypirc, .npmrc, .cargo/credentials
.netrc, .password-store, .gnupg/private-keys-v1.d
Absolute system targets (match anywhere):
/etc/shadow, /etc/sudoers, /etc/ssh/ssh_host_*
/proc/{self,<pid>}/{environ,mem,maps,auxv}
/proc/kcore, /proc/kallsyms
/var/spool/cron/
The home-anchored category uses a regex that requires a HOME-equivalent
prefix, so project-local rc files like ./project/.npmrc remain readable
while ~/.npmrc is denied. Legitimate LLM-developer-tool paths
(~/.gitconfig, ~/.bashrc, ~/.ssh/config, ~/.ssh/known_hosts, /etc/hosts,
~/.cache/, ~/.bash_history, project rc files) are intentionally NOT in
the list and still flow through unchanged.
Closes gaps #1, #2, #3, #12, #13 from the documented 13-gap audit.
Regression sweep:
* 131/131 studio/backend/tests/test_sandbox_tools.py pass
* 24 legitimate-use cases verified ALLOWED
* 17 attack patterns verified BLOCKED
The AST gate previously had no special handling of eval() / exec(),
so a literal payload would slip past every detector:
exec("import os; os.system('sudo whoami')") # ALLOWED before
exec("open('/etc/shadow').read()") # ALLOWED before
eval("__import__('blocked_mod').dangerous()") # still allowed (chained-call gap)
payload = '...'; exec(payload) # ALLOWED before
Both visitors (SignalEscapeVisitor and NetworkAndIoVisitor) now share
the same gate at the top of visit_Call: when the call is bare-name
eval / exec, try to resolve the first argument via the shared
_extract_string_from_node helper (Patch A); if it resolves, parse it
and recursively visit so every existing detector runs on the inner
code — signal tampering, shell escape, sensitive-file open, network
policy, upload denylist, etc.
When the payload is not statically resolvable, SignalEscapeVisitor
appends a `shell_escape_dynamic` finding — eval/exec of runtime data
is the textbook code-injection vector and there is no legitimate LLM
tool-call reason to dynamically eval an external string. Static
literals (eval('1 + 2'), exec('x = 1\\ny = 2')) are unchanged because
the recursive visit only flags what the rest of the AST gate would
already flag at top level.
Each visitor caps recursion at depth 3 (own counter on the instance)
so adversarial nested eval('eval(...)') cannot blow the stack.
Closes gaps #7, #8 (partial), #11 (partial) from the 13-gap audit.
Out-of-scope chained-call cases (__import__('os').system(...),
getattr(os, 'sys'+'tem')()) stay documented gaps — the OS sandbox is
the intended backstop, see PR 5468.
Regression: 131/131 studio/backend/tests/test_sandbox_tools.py pass.
Legitimate eval/exec on literal expressions (eval('1+2'),
exec('print("hi")'), exec('exec("print(1)")')) verified ALLOWED.
124 tests across 7 classes:
* TestPatchA_DynamicPaths — open() with concatenated literals + f-strings.
Pins 7 attack patterns BLOCKED, 6 legitimate dynamic paths ALLOWED,
12-level deep concat doesn't crash.
* TestPatchB_FindSensitivePathsHomeAnchored — ~/.ssh/id_*, ~/.aws/,
~/.docker/, ~/.kube/, ~/.pypirc/.npmrc, ~/.netrc, ~/.password-store,
~/.gnupg/private-keys-v1.d across ~, $HOME, /home/<u>, /root,
/Users/<u>. Pins 21 attack paths BLOCKED, 15 legitimate paths
(~/.gitconfig, ~/.bashrc, ~/.ssh/{config,known_hosts}, ~/.npm,
project-local rc files, /tmp/.npmrc) ALLOWED.
* TestPatchB_FindSensitivePathsAbsolute — /etc/shadow, /etc/sudoers,
/etc/ssh/ssh_host_*, /proc/{self,<pid>}/{environ,mem,maps,auxv},
/proc/kcore, /proc/kallsyms, /var/spool/cron/. Pins 12 attacks
BLOCKED, 11 legit paths (/etc/hosts, /etc/resolv.conf, /proc/cpuinfo,
/proc/meminfo, …) ALLOWED.
* TestPatchB_PythonShellExec — same surface flows through os.system /
subprocess.run. 6 attacks BLOCKED, 11 legitimate tool-calls ALLOWED.
* TestPatchD_EvalExecLiteralPayload — exec/eval with a literal payload
parsed and re-checked. 5 attack payloads BLOCKED, 6 legit
expressions (eval('1+2'), exec('print("hi")'), nested innocuous
exec) ALLOWED.
* TestPatchD_EvalExecDynamicPayload — non-literal eval/exec args
flagged as dynamic shell escape. 4 patterns BLOCKED.
* TestPatchD_NestedDepthCap — 10-level nested exec(exec(...)) caps
at depth 3, doesn't crash, doesn't false-positive.
* TestCrossCuttingNoRegression — 6 pre-existing BLOCK patterns still
fire (sudo, signal tampering, /etc/passwd literal, untrusted host,
metadata host); 7 pre-existing ALLOW patterns still pass (print,
json.loads, trusted host, dataclass, legitimate open()).
Result on the rebuilt scaffold:
131/131 pre-existing tests in test_sandbox_tools.py pass
124/124 new hardening tests pass
255/255 combined, zero regressions
The "must remain ALLOWED" cases form the non-regression floor that
prevents the patches from making LLM tool calling dumber.
There was a problem hiding this comment.
Code Review
This pull request enhances the sandbox security hardening by improving static analysis of dynamic paths and eval/exec payloads. Key changes include: adding a sensitive path allow-list to prevent access to credentials while allowing legitimate tool usage, implementing recursive AST inspection for eval/exec calls to catch hidden malicious payloads, and adding a comprehensive suite of regression tests. The review feedback suggests refining the regex for home directory environment variables and refactoring the duplicated eval/exec inspection logic into a shared helper method to improve maintainability.
I am having trouble creating individual review comments. Click here to see my feedback.
studio/backend/core/inference/tools.py (195)
The regex for matching $HOME and ${HOME} appears to be incorrect. The current pattern \${?HOME}? is too broad and could lead to false negatives or unexpected behavior. It should be more specific to match either $HOME or ${HOME} explicitly.
r"|\$HOME|\${HOME}"
studio/backend/core/inference/tools.py (1106-1140)
The logic for handling eval/exec is duplicated between SignalEscapeVisitor.visit_Call and NetworkAndIoVisitor.visit_Call. This duplicated code should be extracted into a helper method to improve maintainability and reduce redundancy. Both visitors can then call this shared helper.
References
- Centralize recurring or complex logical checks into a single helper function and reuse it across the codebase to ensure consistency and simplify maintenance.
Round-2 fixes for ten issues surfaced by a 20-reviewer code review of
the initial hardening patches. Every change is detection-widening or a
false-positive narrowing; legitimate tool calls keep working.
Direct Python open now flows through _find_sensitive_paths so
open('/home/u/.aws/credentials').read() is gated the same as
os.system('cat ~/.aws/credentials'). The previous wiring covered only
the bash and shell-exec sides.
Both SignalEscapeVisitor and NetworkAndIoVisitor fail-closed once the
eval / exec literal recursion cap is reached. Wrapping a payload in
four or more nested literal exec layers no longer silently bypasses
inspection.
_find_sensitive_paths scans three projections of the command (raw,
backslash-normalised, shlex-dequoted) and recurses into nested
bash -c and cmd /c shells. Quote-spliced and Windows-backslash forms
of credential paths are all caught.
_HOME_PREFIX_RE adds Windows-style home prefixes (USERPROFILE,
HOMEDRIVE HOMEPATH, env:USERPROFILE, drive-letter Users) so cross-OS
hardening actually applies on Windows. Both sensitive-path regexes
now have a path-token start anchor so project-local lookalike paths
under workspace, fixtures, and tmp are not blocked.
Network host validation for sock.connect and the requests / urllib
FQ-prefix branch now use _extract_string_from_node instead of raw
ast.Constant checks, so concatenated and f-string literal hosts
resolve the same way the open gate already did.
pathlib.Path('/etc/shadow').open() is now inspected; the path is
extracted from the receiver constructor when node.args is empty.
The static-string resolver depth cap moves from 6 to 64, removing the
single-character literal-concat bypass while leaving the recursion
well inside CPython's default frame limit.
The SSH private-key regex gains a filename-end boundary so reading a
public ".pub" key stays allowed (legit developer action) while the
matching private key is still denied.
New regression tests cover one class per finding (TestFinding1 through
TestFinding10) plus updated nested-depth coverage; the previous
test_nested_depth_does_not_crash assertion was inverted by the
fail-closed change and has been replaced. Local sweep: 336 passed
(131 upstream + 205 hardening).
…ai/unsloth into studio-sandbox-hardening # Conflicts: # studio/backend/core/inference/tools.py
Pulls the round-2 fixes from unslothai#5603 into the self-contained hardening_ci/ scaffold so the Linux / macOS / Windows matrix exercises: - direct Python open() wired to _find_sensitive_paths - SignalEscapeVisitor + NetworkAndIoVisitor depth-cap fail-closed - shlex-dequoted + Windows-backslash-normalised path scan with nested bash -c / cmd /c recursion - Windows USERPROFILE / drive-letter home prefixes - path-token start anchor to allow project-local lookalikes - network host validation via _extract_string_from_node - pathlib.Path('/etc/shadow').open() receiver-side detection - static-string resolver depth cap raised to 64 - SSH private-key end boundary so .pub keys stay readable - TestFinding1 through TestFinding10 regression coverage Local: 336 / 336 pass.
On Windows runners shlex.split(posix=False) leaves splice quotes in place, so cat /etc/sha''dow tokenises to ['cat', "/etc/sha''dow"] and the dequoted scan projection still misses the credential. The threat model is POSIX-shell quote splicing in either bash invoked on Windows or POSIX shells on Linux/macOS; the dequote always wants POSIX semantics. Pre-normalise backslashes so Windows drive paths survive POSIX shlex's escape handling.
Round-3 follow-up on the same hardening PR after a second 20-reviewer
pass. Every change is detection-widening; legitimate tool calls remain
allowed.
Pathlib readers (Path.open, Path.read_text, Path.read_bytes) now share
one extraction path. The new _extract_pathlib_target helper resolves
Path(a), Path(a, b, ...), Path(...).joinpath(b), and Path(...) / b
through statically-resolvable string parts. NetworkAndIoVisitor tracks
Path aliases (from pathlib import Path as P) and pathlib module aliases
(import pathlib as pl) so the aliased forms hit the same gate. For
receiver-side reads the path is taken exclusively from the receiver --
Path('/etc/shadow').open('r') no longer mis-reads the mode flag as a
path.
The credential-path regex set now matches the POSIX ~user/ expansion
(cat ~ubuntu/.aws/credentials), and the SSH private-key end anchor
includes > so that redirect-attached forms (cat ~/.ssh/id_rsa>... )
are not split-tokenised through the gate. A new
_SENSITIVE_ROOT_WITH_EXPANSION_RE detects sensitive root prefixes
followed by $(...) or backtick substitution, and _find_sensitive_paths
now enumerates bash brace expansion {a,b} plus small glob char classes,
and runs every projection through path-separator normalisation that
collapses // and /./.
Network host validation reaches keyword arguments (url=, host=,
hostname=, address=), host-first APIs whose first positional arg is the
host (socket.create_connection, socket.getaddrinfo,
http.client.HTTPConnection, http.client.HTTPSConnection), and the
url-second APIs (requests.request, httpx.request).
builtins.exec, builtins.eval, and __builtins__.eval flow through the
same literal-payload recursion as the bare forms, including aliased
import builtins as b. open(file=...) and io.open(file=...) keyword
forms are gated alongside the positional form, and the open() path
candidates run through both backslash normalisation and the
//-collapse projection so equivalent spellings (/etc//shadow,
/etc/./shadow) cannot bypass.
Tests grow from 205 to 281 hardening cases (TestR2Finding1 through
TestR2Finding16) and from 131 + 205 = 336 to 131 + 281 = 412 in the
local sweep. Negative cases for every fix continue to ensure
legitimate tool use (Path('data.csv').open(), open(file='logs/today.log'),
requests.get(url='https://wikipedia.org/'), find src/, etc.) stays
allowed.
Round-4 follow-up on the hardening PR after a third 20-reviewer pass.
Closes the high-impact items from that review while preserving the
"do not regress legitimate tool calling" floor; lower-vote items that
would have measurable regression on legit code paths (broad shell
glob ?/*, $VAR in dynamic paths, ANSI-C $'...') are intentionally
deferred.
Parent-directory traversal: _normalize_path_separators now follows
.. segments through posixpath.normpath and reattaches the tilde or
${HOME} prefix, so cat /etc/apt/../shadow and
Path('/proc/self/fd/../environ').read_text() both reach the
canonical regex.
Built-in open() accepts PathLike: open(Path('/etc/shadow')) and
open(file=Path('/etc/shadow')) now flow through the pathlib resolver
the same way receiver reads do.
Pathlib home and transforms: Path.home() resolves to ~ so
(Path.home() / '.aws/credentials') hits the home regex;
.expanduser() / .resolve() / .absolute() are pass-throughs.
Pathlib semantics: _join_path_parts() now matches pathlib's
absolute-segment reset so Path('/tmp') / '/etc/shadow' resolves to
/etc/shadow as it does at runtime.
from builtins import exec as e: tracked in both visitors via
eval_exec_aliases so the aliased call still routes through the
literal-payload recursion.
Process state extensions: /proc/self/cmdline,
/proc/thread-self/*, and /proc/<pid>/task/<tid>/* are added to
_ABSOLUTE_SENSITIVE.
Numeric f-strings: f'/proc/{1}/environ' folds to a literal because
numeric ast.Constant values inside ast.FormattedValue are now
stringified.
os.path.join / os.path.expanduser: resolved statically by
_extract_string_from_node so the stdlib-helper construction paths
do not hide sensitive targets.
Variable assignment tracking: a pre-pass collects ``name = literal``
and ``name = eval`` / ``name = exec`` bindings; the visitors and the
pathlib resolver consult those bindings. The trusted-host gate
intentionally uses a separate strict literal extractor so legit
patterns like ``url = some_input; requests.get(url)`` still pass.
shutil.copyfile / copy / copy2 / copytree / move: the source argument
is gated the same way open() is, blocking file-copy exfil.
Concrete pathlib classes: PosixPath / WindowsPath / PurePath / etc.
are registered in path_aliases by default.
requests.request positional+keyword: for URL-second APIs, args[0] is
the HTTP method (not the URL); when there is only one positional, the
URL extraction falls through to the url= keyword instead of grabbing
the method.
Tests grow from 281 to 357 hardening cases; combined sweep 487 / 487.
Every fix has positive and negative coverage; legit tool calls
(open(Path('data.csv')), os.path.join('logs', 'today.log'),
url = some_input; requests.get(url), shutil.copyfile('a.txt', 'b.txt'))
continue to pass.
…ai/unsloth into studio-sandbox-hardening # Conflicts: # studio/backend/core/inference/tools.py
|
Reviewed the hardening end-to-end. This is a real improvement and looks regression-free on legitimate Studio workflows — safe to land. Tests on No false positives observed against the legitimate workflows the gate is meant to allow. Confirmed allowed by ad-hoc probing of
Bypass class that remains (worth tracking, not blocking this PR — the runtime layer in
Suggest a followup issue to (a) track the Cross-OS validation pinned in danielhanchen#137. |
|
Cross-OS validation finished in danielhanchen#137.
Same gate behavior on all three platforms — |
Closes two static-bypass classes flagged during round-3 review:
1. __import__('os').system(...) / importlib.import_module('os').popen(...)
bypassed the bare os.system / subprocess.* gate because the receiver
was an ast.Call rather than an ast.Name in os_aliases. Adds
_resolve_dynamic_module_name() so:
* inline __import__('os').system(...)
* inline importlib.import_module('os').system(...)
* import importlib; mod = importlib.import_module('os'); mod.popen(...)
* m = __import__('subprocess'); m.run([...], shell=True)
all flow through the same shell-escape detection as
import os; os.system(...). Legit dynamic imports of safe modules
(json, pathlib, ...) remain allowed.
2. /proc/<pid>/cwd and /proc/<pid>/root are symlinks to the process
working directory and the filesystem root. The form
open(/proc/self/cwd/../../etc/shadow) bypassed
_normalize_path_separators because .. was collapsed against the
literal path, not the symlinked target. The form
open(/proc/self/root/etc/shadow) bypassed any chroot-style
defence. Adds matching entries to _ABSOLUTE_SENSITIVE so the bash
gate and the AST open() gate both block any access via these
symlink prefixes. Legitimate /proc/self/status etc. introspection
still flows.
Tests:
TestFollowup_DynamicImportShellEscape (2 cases, 10 parametrised)
TestFollowup_ProcSelfSymlinkTraversal (3 cases, 16 parametrised)
pytest studio/backend/tests/test_sandbox_hardening.py -q
-> 382 passed in 0.67s (was 356).
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8fff7559c0
ℹ️ 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".
| for m in _SENSITIVE_ROOT_WITH_GLOB_RE.finditer(text): | ||
| if _glob_can_reach_sensitive_path(m.group(0)): | ||
| found.add(m.group(0)) |
There was a problem hiding this comment.
Preserve shell quoting when evaluating sensitive globs
When a glob-shaped path is quoted or escaped, such as printf '%s\n' '/etc/shad*' or echo /etc/shad\*, Bash prints the literal text and performs no filesystem expansion. However, _find_sensitive_paths runs this check over shlex-dequoted projections, so both commands reach this branch as /etc/shad* and are rejected by _bash_exec. Restrict glob reachability checks to projections that preserve whether the wildcard was active.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e97da8e. Sensitive glob checks now use only shell-active wildcard tokens; quoted and escaped literals remain allowed.
| def visit_AnnAssign(self, node): | ||
| if node.value is not None: | ||
| self._record_constructed_binding([node.target], node.value) | ||
| self.generic_visit(node) |
There was a problem hiding this comment.
Clear stale aliases on annotated rebinding
When an imported network alias is replaced with an annotated assignment, for example import requests as client; client: object = LocalClient(); client.get('https://private.example'), this visitor records only newly recognized constructors and never removes client from network_module_aliases. The later local method call is consequently analyzed as requests.get and blocked as an untrusted network request, unlike the equivalent ordinary assignment handled by visit_Assign; apply the same unconditional alias-clearing and propagation logic to AnnAssign.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e97da8e. Unconditional annotated rebinding now clears stale network and file aliases, while conditional rebinding remains conservative.
| # ``./workspace/home/u/.aws/credentials`` or ``/tmp/home/u/.npmrc`` -- | ||
| # those are project-local lookalikes, not host credentials. The negative | ||
| # lookbehind keeps matches anchored to a real shell token boundary. | ||
| _PATH_TOKEN_START = r"(?<![A-Za-z0-9_./~$%-])" |
There was a problem hiding this comment.
Recognize sensitive paths embedded in file URLs
When no effective filesystem sandbox is present, a permitted interpreter command such as python -c "import urllib.request; print(urllib.request.urlopen('file:///etc/shadow').read())" reads the protected file, but _find_sensitive_paths returns an empty set. In file:///etc/shadow, the sensitive /etc segment is preceded by another slash, so this token-start lookbehind rejects it; add a projection or explicit handling for local file: URLs, matching the file-URL protection already applied by the Python AST visitor.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e97da8e. Local file URLs are projected to decoded filesystem paths before sensitive-path matching, including percent-encoded paths.
| if len(node.args) > 2: | ||
| source_nodes.append(node.args[2]) |
There was a problem hiding this comment.
Inspect positional base_dir in make_archive
When shutil.make_archive receives all four positional arguments, this branch records only positional root_dir and silently ignores positional base_dir. For example, shutil.make_archive('/tmp/keys', 'zip', './project', '/root/.ssh') passes the new source gate because only ./project is inspected, while make_archive uses the absolute fourth argument as the directory to archive; without an effective filesystem sandbox this exposes the complete credential directory. Resolve and inspect node.args[3] as base_dir as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e97da8e. shutil.make_archive now inspects positional root_dir and base_dir as well as both keyword forms.
| f = node.func | ||
| if isinstance(f, ast.Name) and f.id in ("__import__", "import_module"): | ||
| return arg0.value | ||
| if isinstance(f, ast.Attribute) and f.attr == "import_module": | ||
| return arg0.value |
There was a problem hiding this comment.
Require a tracked importlib callable before resolving modules
When sandboxed code defines an unrelated callable named import_module, such as def import_module(name): return LocalRunner(), a later import_module('os').system('sudo whoami') is treated as os.system and rejected even though it only invokes the local object's method. This helper accepts every bare import_module name and every .import_module attribute without verifying an importlib import or tracked alias, and the visitor-aware resolver calls it before consulting its alias set. Limit these branches to known importlib receivers and aliases.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e97da8e. Dynamic import resolution now requires tracked importlib imports or aliases; unrelated local callables and methods are allowed.
|
@codex review |
|
Maintainer review update for exact head e97da8e:
Remote status is still pending, not green: 2 checks passed, 34 queued, 0 failed at the latest observation, and the fresh Codex review request timed out without a result. No readiness or merge claim yet. |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/core/inference/tools.py
Lines 15653 to 15654 in e97da8e
The host-policy surface includes urllib.request.urlopen but not the equally standard opener API. urllib.request.build_opener().open('http://169.254.169.254/latest').read() and the same call through an assigned opener both pass _check_code_safety, because the constructor is not mapped to a network instance and its .open() is instead treated as a benign file-reader-shaped call. Since _sandbox_preexec deliberately leaves the network namespace enabled, recognize build_opener/OpenerDirector calls and apply the URL host policy to their open method.
unsloth/studio/backend/core/inference/tools.py
Lines 15974 to 15978 in e97da8e
HF upload recognition compares a bare call's local name directly with _UPLOAD_HF_METHODS, so ordinary aliases bypass the path and credential checks. For example, from huggingface_hub import upload_file as send; send(path_or_fileobj='/root/.ssh/id_rsa', path_in_repo='x', repo_id='a/b') passes _check_code_safety, as does f = huggingface_hub.upload_file; f(...), while the unaliased call is rejected. Record from-import and assignment aliases to canonical HF upload operations before applying _hf_upload_violation.
ℹ️ 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".
| ): | ||
| bindings.pop(target, None) | ||
| shutil_module_aliases.discard(target) | ||
| self._record_constructed_binding([node.target], node.value) |
There was a problem hiding this comment.
Propagate annotated callable aliases
Although annotated rebinding now clears stale aliases, it does not propagate a newly assigned callable alias. For example, import io; reader: object = io.open; reader('/etc/shadow').read() passes _check_code_safety, because _record_constructed_binding only recognizes constructor calls and reader is never restored to file_reader_aliases. On hosts without an effective filesystem sandbox, this permits direct credential reads; apply the same callable/module alias propagation used by visit_Assign to annotated assignments.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4e97c47 by sharing callable and module alias propagation between normal and annotated assignments. Added coverage for io, codecs, os, requests, and pathlib aliases, plus benign project reads.
| path_lit = _extract_pathlib_target( | ||
| node.args[0], self.path_aliases, self.pathlib_aliases | ||
| ) | ||
| if path_lit is None: | ||
| path_lit = _extract_string_from_node(node.args[0]) |
There was a problem hiding this comment.
Expand literal splats before checking reader paths
When a file reader receives a statically known starred argument, node.args[0] is an ast.Starred, so both path extractors return None. Consequently open(*['/etc/shadow']).read() and pathlib.Path(*['/etc/shadow']).read_text() pass _check_code_safety even though they deterministically read the protected file. Without an effective filesystem sandbox, expand bounded literal list/tuple splats before applying the sensitive-path policy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, but marking this down under the strict practical-trigger bar. A literal one-element splat is deliberate indirection, and this sensitive-path spelling is already caught by the high-risk approval boundary. No analyzer expansion here.
| a0 = node.args[0] | ||
| if isinstance(a0, ast.Tuple) and a0.elts: | ||
| host_arg = _extract_string_literal(a0.elts[0]) | ||
| elif fq in _HOST_FIRST_FQ: | ||
| host_arg = _extract_string_literal(a0) |
There was a problem hiding this comment.
Expand literal splats before enforcing the host policy
For a statically unpacked URL such as requests.get(*['http://169.254.169.254/latest']), a0 is an ast.Starred, _extract_url_literal returns None, and _check_code_safety allows the metadata request. The same applies to other URL-first APIs handled here, so the newly added literal-host policy can be bypassed without any genuinely dynamic input; inspect bounded literal tuple/list splats before selecting the URL argument.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, but marking this down under the strict practical-trigger bar. Passing a literal URL through a one-element splat is an exotic encoding rather than an ordinary request shape. The normal URL-first and method-first APIs remain covered.
| candidates = {path_lit} | ||
| if "\\" in path_lit: | ||
| candidates.add(path_lit.replace("\\", "/")) | ||
| candidates.add(_normalize_path_separators(path_lit)) |
There was a problem hiding this comment.
Account for working-directory changes before path checks
Fresh evidence distinct from the previously reported dir_fd case is import os; os.chdir('/etc'); open('shadow').read(): _check_code_safety allows it because the reader gate evaluates shadow without the statically known current directory. On hosts without an effective filesystem sandbox, this reads /etc/shadow; track literal os.chdir/os.fchdir effects or conservatively reject relative reader paths after such a directory change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4e97c47. The analyzer now tracks straight-line literal os.chdir calls, including imported aliases, and resolves later relative reads against that directory. Tests cover sensitive targets, safe project reads, safe /etc/hosts, and changing back to a safe directory.
| # File-copy / file-move APIs read the source path just like | ||
| # ``open()`` does, and the copy gives the attacker a second | ||
| # exfil channel (rename/print/upload the destination). Gate | ||
| # the source argument with the same sensitive-path checks. |
There was a problem hiding this comment.
Block sensitive targets used to create symlinks
A statically created symlink bypasses the literal reader-path check: os.symlink('/etc/shadow', 'x'); open('x').read() and the equivalent Path('x').symlink_to('/etc/shadow') both pass _check_code_safety. Because creating the link requires no permission to read its target, the later benign-looking path exposes the credential whenever filesystem isolation is unavailable; reject sensitive literal symlink targets or carry the target binding into subsequent reads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, but marking this down under the strict practical-trigger bar. This is deliberate two-step indirection that explicitly names the protected path, and it already triggers the high-risk approval boundary. Blocking link creation itself would also reject cases that never read the target.
| _FILE_COPY_FUNCS = frozenset( | ||
| { | ||
| "shutil.copyfile", | ||
| "shutil.copy", | ||
| "shutil.copy2", | ||
| "shutil.copytree", | ||
| "shutil.move", | ||
| "shutil.make_archive", |
There was a problem hiding this comment.
Gate stdlib archive source paths
The copy/archive gate covers shutil.make_archive but not the direct standard-library archive APIs. For example, with tarfile.open('keys.tar', 'w') as t: t.add('/root/.ssh') and ZipFile('keys.zip', 'w').write('/root/.ssh/id_rsa') pass _check_code_safety; the resulting archive is then exposed as a sandbox-created artifact. Without filesystem isolation, inspect TarFile.add and ZipFile.write source arguments with the same sensitive-file and sensitive-directory policy.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4e97c47. TarFile.add and ZipFile.write sources now use the sensitive file and directory policy, restricted to receivers proven to come from tracked stdlib archive constructors. Benign project archives and unrelated add methods remain allowed.
| if not ( | ||
| isinstance(node, ast.Call) | ||
| and isinstance(node.func, ast.Name) | ||
| and node.func.id == "getattr" | ||
| and len(node.args) >= 2 | ||
| ): | ||
| return None |
There was a problem hiding this comment.
Resolve literal module-dictionary callable lookups
The new callable resolver handles literal getattr but not the equivalent statically known module dictionary form. Thus os.__dict__['system']('cat /etc/shadow'), builtins.__dict__['open']('/etc/shadow').read(), and requests.__dict__['get']('http://169.254.169.254/latest') all pass _check_code_safety. These are literal attribute names on already tracked modules, so canonicalize module.__dict__['name'] alongside getattr(module, 'name') before the shell, file, and network gates.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, but marking this down under the strict practical-trigger bar. Literal module dictionary dispatch is deliberate metaprogramming and already triggers the high-risk approval boundary; broad matching also risks treating user-defined dictionaries as privileged modules.
| method = node.func.attr | ||
| if method in ("connect", "connect_ex") and node.args: | ||
| address_node = node.args[0] | ||
| elif method == "sendto" and len(node.args) >= 2: | ||
| address_node = node.args[-1] | ||
| elif method == "sendmsg" and len(node.args) >= 4: |
There was a problem hiding this comment.
Shift socket addresses for unbound method calls
The address-position logic assumes every connect/connect_ex call is bound. With s = socket.socket(); socket.socket.connect(s, ('169.254.169.254', 80)), however, args[0] is the receiver and the address is args[1], so this branch extracts no host and _check_code_safety allows the metadata connection. Detect the unbound socket.socket.<method> form and account for its explicit receiver when selecting the address argument; sendmsg has the same positional shift.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced, but marking this down under the strict practical-trigger bar. Calling socket descriptors as unbound class methods is an exotic spelling; ordinary bound connect, connect_ex, sendto, and sendmsg forms remain covered without broadening matches to unrelated classes.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4e97c472ef
ℹ️ 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 self._archive_constructor_name(item.context_expr) is not None and isinstance( | ||
| item.optional_vars, ast.Name | ||
| ): | ||
| self.archive_instance_aliases.add(item.optional_vars.id) |
There was a problem hiding this comment.
Track network clients bound by context managers
With normal context-manager usage such as with httpx.Client() as client: client.get('http://169.254.169.254/latest'), this visitor records only archive instances from optional_vars and never calls _record_constructed_binding for the recognized network constructor. Consequently client is absent from network_instance_aliases, the call remains client.get, and the literal-host policy is skipped; because _sandbox_preexec explicitly leaves networking enabled, this can reach the metadata service. Bind recognized network clients for both with and async with variables.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 516c2c0. Recognized network constructors now bind context-manager targets for sync and async with blocks, with identity restored after the block. Coverage includes HTTPX, aiohttp, trusted hosts, and non-leaking context state.
| if constructor == "requests.Session": | ||
| return "requests" |
There was a problem hiding this comment.
Recognize clients returned by requests.session
When sandboxed code uses the public Requests factory, for example s = requests.session(); s.get('http://169.254.169.254/latest'), this mapping recognizes only requests.Session, so _record_constructed_binding does not register s as a Requests instance. The later s.get therefore bypasses the metadata/untrusted-host checks and can make unrestricted network requests; treat requests.session as returning the same instance type.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 516c2c0. requests.session now maps to the same tracked client identity as requests.Session, including module aliases, from-imports, and callable aliases; unrelated session factories remain untracked.
| if isinstance(_assign, (ast.For, ast.AsyncFor)) and isinstance( | ||
| _assign.target, ast.Name | ||
| ): | ||
| if isinstance(_assign.iter, (ast.List, ast.Tuple, ast.Set)): |
There was a problem hiding this comment.
Resolve literal comprehension bindings before file checks
When a sensitive path is supplied through an ordinary comprehension, such as [open(path).read() for path in ['/etc/shadow']], the binding prepass ignores the ast.comprehension node because it only recognizes For and AsyncFor statements. The later open(path) therefore sees an unresolved name and passes the sensitive-file gate even though the iterable deterministically binds the protected path; collect bounded literal comprehension bindings using the same logic as literal for loops.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 516c2c0. Literal comprehension targets are resolved inside their own scope for list, set, dict, and generator comprehensions, including destructuring and filters. Outer bindings are restored and covered by a non-leak regression.
| pathlib_module_aliases_prepass: set[str] = {"pathlib"} | ||
| path_class_aliases_prepass: set[str] = set(_PATHLIB_PATH_CLASSES_PREPASS) | ||
|
|
||
| _LEXICAL_SCOPE_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef) |
There was a problem hiding this comment.
Keep class namespaces out of method lexical scope
Class bodies are not enclosing lexical scopes for methods, but including ast.ClassDef here makes class-local rebinding hide module aliases while method bodies are analyzed. For example, import requests as r; class C: r = LocalClient(); def fetch(self): return r.get('http://169.254.169.254/latest') resolves bare r to the global Requests module at runtime, whereas the visitor inherits the class body's cleared alias state and skips the host check. Analyze methods against their actual global/enclosing-function bindings rather than the class namespace overlay.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 516c2c0. Class bodies retain their local analysis overlay, while method and class-defined lambda bodies are checked against the real global or enclosing-function bindings. Defaults remain evaluated in class scope, and class, self, and method-local clients stay allowed.
|
@codex review |
|
Validation update for exact head 516c2c0:
Backend-only change; UI evidence is not applicable. No merge was performed. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 516c2c0cbf
ℹ️ 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".
| "fromfile", | ||
| "loadtxt", | ||
| "genfromtxt", |
There was a problem hiding this comment.
On hosts without an effective filesystem sandbox, import numpy as np; np.memmap('/home/user/.aws/credentials', dtype='uint8', mode='r') exposes the protected file, but memmap is absent from this NumPy reader set and the call does not match any other file-read branch. Include memmap in the tracked reader APIs so its filename receives the same sensitive-path check as fromfile and loadtxt.
Useful? React with 👍 / 👎.
| and isinstance(node.func, ast.Attribute) | ||
| and isinstance(node.func.value, ast.Name) | ||
| and node.func.value.id in self.os_module_aliases | ||
| and node.func.attr == "chdir" |
There was a problem hiding this comment.
Track directly imported chdir callables
Fresh evidence after the prior os.chdir fix is the ordinary from-import form: from os import chdir; chdir('/etc'); open('shadow').read() still passes because this branch only recognizes an attribute on a tracked os module alias. Without effective filesystem isolation, the relative read resolves to /etc/shadow; track from os import chdir as ... aliases and apply the same working-directory update to their calls.
Useful? React with 👍 / 👎.
| if isinstance(func, ast.Name): | ||
| if func.id in ("eval", "exec"): | ||
| return func.id | ||
| return eval_exec_aliases.get(func.id) |
There was a problem hiding this comment.
Respect lexical shadowing of eval and exec
When a function parameter or local callable is named eval or exec, such as def parse(eval, payload): return eval(payload), this unconditional name match treats the local callable as the builtin and rejects any non-literal argument as code injection. The scope machinery already identifies shadowed local bindings, so bare names should be classified as builtins only while they remain unshadowed.
Useful? React with 👍 / 👎.
| if file_copy_fq == "shutil.make_archive": | ||
| if len(node.args) > 2: | ||
| source_nodes.append(node.args[2]) | ||
| if len(node.args) > 3: | ||
| source_nodes.append(node.args[3]) | ||
| source_nodes.extend( | ||
| kw.value for kw in node.keywords or [] if kw.arg in ("root_dir", "base_dir") | ||
| ) |
There was a problem hiding this comment.
Resolve make_archive base_dir against root_dir
Fresh evidence beyond the positional base_dir fix is that these two arguments are checked independently even though shutil.make_archive resolves a relative base_dir beneath root_dir. On a host without effective filesystem isolation, shutil.make_archive('/tmp/keys', 'zip', root_dir='/home/user', base_dir='.ssh') therefore passes—the two literals appear harmless separately—but archives /home/user/.ssh; combine statically known root_dir and relative base_dir before applying the sensitive-directory policy.
Useful? React with 👍 / 👎.
|
Reviving this one. It matters more after the OS sandbox work, not less. I opened #10526, which confines the filesystem for Python and Terminal tool calls on Linux and macOS but deliberately keeps the network. So a script that can still reach a secret can still send it, and the AST gate this PR hardens is the only thing in the way. That is exactly the case the description here already calls out: "on hosts where an OS-level sandbox cannot engage (default cloud Linux without unprivileged userns, Windows), the in-process AST gate is the only defense". That host class turned out to be larger than I assumed when I wrote this in May. Ubuntu 23.10 and newer ship I tested the merge. This branch and #10526 conflict in exactly one line: They touch disjoint functions in |
Summary
Three additive detection-widening patches to the Studio software sandbox in
studio/backend/core/inference/tools.py. All are zero-regression on legitimate tool use: bashcat,ls,find,grepon normal source trees still work, only direct references to clear-cut credential or process-state targets are denied.The motivation is that on hosts where an OS-level sandbox cannot engage (default cloud Linux without unprivileged userns, Windows), the in-process AST gate is the only defense. A cross-OS test sweep on real Linux, macOS, and Windows runners showed several currently-allowed exfil patterns on
main. The patches close the highest-impact ones.Patch A: resolve concatenated and f-string literals
_extract_string_from_nodenow foldsast.BinOp(Add)and constantast.JoinedStr, depth-capped at 6. Wired into the existingopen()sensitive-file gate soopen('/etc/' + 'shadow')andopen(f'/etc/{"shadow"}')are recognised the same as the plain literal.Patch B: home-anchored credential and process-state path detection
New
_find_sensitive_paths()helper, called from_bash_execand_check_args_for_blocked. Detection uses anchored regex requiring an explicit home prefix (~/,$HOME/,${HOME}/,/home/<u>/,/root/,/Users/<u>/) for the home-relative patterns, plus absolute paths for/etc/shadow,/etc/sudoers,/etc/ssh/ssh_host_*,/proc/<pid|self>/{environ,mem,maps,auxv},/proc/kcore,/proc/kallsyms,/var/spool/cron/.The allow-list deliberately keeps these unblocked because they have legitimate tool-call uses:
~/.gitconfig,~/.bashrc,~/.zshrc,~/.profile~/.ssh/config,~/.ssh/known_hosts/etc/hosts,/etc/hostname,/etc/resolv.conf~/.npm/,~/.cache/,~/.bash_history./.npmrc,./.gitconfig, etc.Patch D: eval and exec literal payload recursion
In both
SignalEscapeVisitorandNetworkAndIoVisitor.visit_Call, whenevalorexecis called with a literal payload that parses cleanly, the visitor recurses into the payload's AST, depth-capped at 3. Combined with Patch A this meansexec("import os; os.system('sudo whoami')")resolves and is gated by the existing shell-escape detector. Non-literal payloads are flagged as dynamic shell-escape candidates.Coverage
Cross-OS GitHub Actions matrix (ubuntu-latest, macos-14, windows-latest) on a staging fork: 124 of 124 hardening tests pass on all three OSes, and the upstream
test_sandbox_tools.pysuite (131 tests) continues to pass on Linux and macOS. The fewTestBashBlocklistPositioncases that already fail on Windows onmain(POSIX-only shell semantics) are unchanged by this PR.Test plan
python -m pytest studio/backend/tests/test_sandbox_tools.py -v(no regressions)python -m pytest studio/backend/tests/test_sandbox_hardening.py -v(124 of 124 pass)