Skip to content

Studio: block sandbox bypass via command-position substitutions in terminal tool - #10860

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
veriepicc:fix/sandbox-substitution-bypass
Sep 14, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
veriepicc:fix/sandbox-substitution-bypass

Conversation

@veriepicc

Copy link
Copy Markdown
Contributor

Fixes #10835

Neither contains the blocked word, so the blocklist missed both. With tool permission set to Run automatically the ask gate approves by design, so it executed.

Backend-only change in _find_blocked_commands (studio/backend/core/inference/tools.py). Command-position substitutions and backticks now get their bodies screened: a blocked literal anywhere in the body is reported, and an executable enumeration (ls/find/compgen of bin dirs, echo/printf glob expansion) is treated as unknowable and blocked. Same screening covers brace groups, branch and loop bodies, find -exec payloads, sudo/env-style wrappers, and laundered variables. Argument-position substitutions like echo $(date) and single-binary lookups like $(which python) stay allowed.

The diff is purely additive, 270 insertions and 0 deletions, confined to the blocklist plus tests. Nothing else in the execution path changed.

Repro (both from the issue):

$(ls /usr/bin/ | grep "^reb")
$(ls /usr/bin/ | grep "^rm$") -rf ~/Downloads/can_delete

Testing: added 20 blocked cases (both issue repros verbatim) and 14 allowed cases in test_sandbox_tools.py. Full file plus test_windows_bash_shell.py: 349 passed, 4 skipped. ruff check and the repo formatter pass.
test_session
test_result

…rminal tool

Fixes unslothai#10835

A command substitution at command position synthesizes the executed word, so the blocked name never appears literally. $(ls /usr/bin/ | grep "^reb") runs reboot and $(ls /usr/bin/ | grep "^rm$") -rf ... runs rm, and neither contains the blocked word, so the blocklist missed both. With tool permission set to Run automatically the ask gate approves by design, so it executed.

Backend-only change in _find_blocked_commands (studio/backend/core/inference/tools.py). Command-position $(...) and backticks now get their bodies screened: a blocked literal anywhere in the body is reported, and an executable enumeration (ls/find/compgen of bin dirs, echo/printf glob expansion) is treated as unknowable and blocked. Same screening covers brace groups, branch and loop bodies, find -exec payloads, sudo/env-style wrappers, and laundered variables (c=$(...); $c, printf -v c, c=reboot; $c). Argument-position substitutions like echo $(date) and single-binary lookups like $(which python) stay allowed.

The diff is purely additive, 270 insertions and 0 deletions, confined to the blocklist plus tests. Nothing else in the execution path changed.

Testing: added 18 blocked cases (both issue repros verbatim) and 14 allowed cases in test_sandbox_tools.py. Full file plus test_windows_bash_shell.py: 349 passed, 4 skipped. ruff check and the repo formatter pass.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the gap in _find_blocked_commands in studio/backend/core/inference/tools.py, where a command-position substitution synthesizes the executed word so the blocked name never appears literally, and the auto-run path has no second gate. Will get this reviewed.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the literal-name scan in studio/backend/core/inference/tools.py misses a command-position substitution, so both repros get through the blocklist, and the added screening covers them plus the laundered-variable shapes. Will get this reviewed.

Six issues found while running the new screen against a corpus of everyday
terminal commands and of bypasses verified to really execute, on the posix
lexer and on both Windows lexer paths.

The screen is a hard block, not a prompt, so a false positive is a dead
command. Four of these produced one:

- A wrapper was allowed up to four arbitrary words before its operand, so
  anything within reach of a timeout/nohup/xargs/env read as command position:
  `timeout 60 python train.py --data $(ls -d data/*)` was refused. A wrapper
  forwards to ONE operand, so only its own flags, assignments and numeric
  arguments may sit in front of it now.
- A wrapper option taking a separate value has to swallow that value too, or
  `xargs -P $n` reads the `$n` as the command. The regex cannot pin this down
  on its own - it just backtracks to the shorter reading - so it is checked
  against the existing flag table in code.
- The assignment screen was missing the arithmetic guard its sibling regexes
  carry, so `sec=$((60*5)); timeout $sec make test` was refused over a value
  that can only ever be a number.
- Neither the separators nor the bodies were quote-aware. Bash expands nothing
  inside single quotes and an expansion inside double quotes is a word the
  outer command receives, so `sed 's|x|$(ls)|' f` and `echo "check if $(ls -1
  *.py | wc -l) files"` both ran nothing and were both refused. The body scan
  also matched `.` - the synonym for `source` - against any dot in a filename,
  reporting `$(cat .env)` as "Blocked command(s) for safety: .".

The remaining two let real commands through, or through the CPU:

- Assignment separators were narrower than execution separators, so a launder
  behind a keyword, a subshell or another assignment was never collected:
  `if true; then c=$(ls /usr/bin|grep rm); fi; $c`, `(c=$(...); $c)` and
  `x=1 c=$(...); $c` all delete. So does `"$c"`, the recommended spelling,
  which the screen did not cover.
- Each site costs a span walk over the rest of the line and this function has
  no length cap, unlike the ask-gate screen. `";$(" * 10000` went from 0.1s
  before the screen existed to over 30s after it, on the request thread. Past
  64 sites the screen now refuses instead of reading, which fails closed.

Verified against the merge base on a 125-command corpus: 36 bypasses newly
blocked (up from 29), 0 everyday commands newly refused (down from 10), same
verdicts under the posix and both Windows lexer paths. The 12 failures in the
wider backend suite are identical before and after.
Opening comment-reduction pass. Comment lines on the added code drop from 95
to 54 in tools.py and 30 to 17 in the tests, with no code change (AST-gated).

Stopped short of a deeper cut: what survives is one line per boundary naming
the command that regressed when the boundary sat elsewhere, which is the fact
a future reader needs in order not to move it back.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 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-09-14T03:32:11.827848Z ec3170f Manual request
🔒 Security Review ✅ Completed 2026-09-14T02:00:22.676547Z 5610550 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.

@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: 56105502e4

ℹ️ 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 thread studio/backend/core/inference/tools.py Outdated
)
_SUBST_WRAPPER_ARG = (
r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+"
r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*|\d+)"

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 Accept timeout's full duration syntax in the wrapper scan

When timeout uses a valid suffixed or fractional duration, such as timeout 1s $(ls /usr/bin | grep '^rm$') -rf victim, _SUBST_WRAPPER_ARG does not recognize the duration and therefore never screens the command-position substitution. timeout --help documents DURATION as a floating-point number with an optional s, m, h, or d suffix, while this pattern admits only bare integers; the synthesized rm consequently reaches _bash_exec without being blocklisted.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in c436d30. timeout --help documents DURATION as a floating point number with an optional s/m/h/d suffix, and the argument class took bare integers only. Verified the bypass by running it against a stand-in rm on PATH: it executed. The class now accepts the suffixed and fractional spellings, with regression tests for timeout 1s and timeout 0.5.

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +5055 to +5057
_SUBST_WRAPPER_RUN = (
r"(?:(?:env|command|builtin|exec|time|nohup|nice|setsid|stdbuf|timeout|ionice|chroot"
r"|setpriv|sudo|doas|su|xargs)\s+(?:" + _SUBST_WRAPPER_ARG + r"\s+){0,4}){0,3}"

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 wrapper scanning exceeds its bounds

A valid wrapper invocation with more than four option operands, such as env -u A -u B -u C -u D -u E $(ls /usr/bin | grep '^rm$') -rf victim, exceeds the {0,4} repetition and makes the whole substitution-site regex fail instead of refusing the command. env --help explicitly permits [OPTION]... before COMMAND, so this crafted command executes the synthesized blocked binary; the bounded scan needs an overflow path that fails closed, analogous to _exec_child_index.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in c436d30. env --help documents [OPTION]..., so any cap is a count that can be exceeded to make the site regex fail open rather than closed; the five-option form executed against a stand-in rm. Rather than add an overflow path I removed both caps: the repetitions cannot overlap (a wrapper word never matches the argument class) and each must consume a mandatory space, so there is nothing to backtrack. Measured linear to 180 KB, including the near-miss shape that never reaches a $(.

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +5060 to +5062
_SUBST_AT_CMD_SITE_RE = re.compile(
_SUBST_CMD_SEP + r"\s*"
r"(?:[A-Za-z_]\w*=[^\s;&|()]*\s+)*" + _SUBST_WRAPPER_RUN + r"(?:\"\$\((?!\()|\$\((?!\()|`)",

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 Preserve command position after leading redirections

Bash permits redirections before a command word, so >/tmp/log $(ls /usr/bin | grep '^rm$') -rf victim executes the substitution's output as the command. _SUBST_AT_CMD_SITE_RE only skips assignments and wrappers after its separator and cannot cross the leading redirection, leaving this synthesized blocked command unscreened even though the existing token walker already treats redirections as preserving command position.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in c436d30. Bash saves the leading redirections and assignments before the command name, and the token walker already treated a redirection as leaving command position intact, so the site scan was the odd one out. >out.log $(ls /usr/bin | grep '^rm$') executed against a stand-in rm. A redirection prefix is now stepped over on both sides of the assignment prefix.

Comment thread studio/backend/core/inference/tools.py Outdated
)
# Command-position separators for the screens below. `:` is absent on purpose: its arguments are
# expanded but never executed.
_SUBST_CMD_SEP = r"(?:^|[;&|\n({]|&&|\|\||\b(?:then|do|else|elif|if|while|until)\b\s*|!\s*)"

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 Treat case labels as substitution command sites

In a Bash case arm, the closing ) is followed directly by executable commands, as in case x in x) $(ls /usr/bin | grep '^rm$') -rf victim;; esac. Because _SUBST_CMD_SEP omits ), the new body scanner does not recognize this substitution as being at command position, allowing the enumerated blocked command to execute.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in c436d30. case word in [ [(] pattern ) list ;; ] ... esac puts the arm's commands directly after the ), and the form executed against a stand-in rm. Not fixed by putting ) in the separator class, which would refuse an ordinary echo $(date) $(ls /tmp): case arms are a separate site kind, matched only inside a case ... in ... esac region and only for a ) that does not close a substitution. Both controls are now tests.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 56105502e4

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

All four were reported by review and all four really delete: each was run
against a stand-in rm on PATH and executed it.

- timeout's DURATION is "a floating point number with an optional suffix: 's',
  'm', 'h' or 'd'" (timeout --help), but the wrapper argument class took bare
  integers only, so `timeout 1s $(ls /usr/bin | grep '^rm$')` was never screened.
- The wrapper option run was capped at 4 per wrapper and 3 wrappers. `env
  --help` documents `[OPTION]...`, so a fifth option made the whole site regex
  fail rather than refuse: `env -u A -u B -u C -u D -u E $(...)` ran. Both
  repetitions are unbounded now, which is safe because the parts cannot overlap
  (a wrapper word never matches the argument class) and each repetition must
  consume a mandatory space, so there is nothing to backtrack. Measured linear
  to 180 KB, including the near-miss shape that never reaches a `$(`.
- Redirections may precede the command word, so `>out.log $(...)` runs the
  substitution's output. The token walker already knew this; the site scan did
  not.
- A case arm's `)` is followed directly by the commands to run, so `case x in
  x) $(...) -rf victim;; esac` executes. Added as its own site kind rather than
  by putting `)` in the separator class, which would refuse an ordinary `echo
  $(date) $(ls /tmp)`: an arm's `)` is one that does not close a substitution,
  inside a case ... in ... esac region.

Corpus unchanged at 0 regressions and 36 bypasses blocked, on the posix lexer
and both Windows lexer paths, plus 10 new tests (5 blocked, 5 allowed controls).
@danielhanchen

Copy link
Copy Markdown
Member

@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: c436d3096b

ℹ️ 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 thread studio/backend/core/inference/tools.py Outdated
# fractional spellings too or the site behind them goes unscreened.
_SUBST_WRAPPER_ARG = (
r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+"
r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*|(?:\d+(?:\.\d*)?|\.\d+)[smhd]?)"

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 Accept every valid floating-point timeout duration

On GNU coreutils, timeout 1e1 $(ls /usr/bin | grep '^rm$') -rf victim and the suffixed 1.5e1s form are valid—the local timeout --help describes DURATION as “a floating point number with an optional suffix,” and both forms executed a stand-in rm—but this operand pattern rejects scientific notation, so _find_blocked_commands returns an empty set and the synthesized command bypasses the sandbox blocklist. The fresh evidence beyond the earlier fixed report is that scientific-notation floating-point durations remain accepted by timeout but unrecognized here.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 38c8c5a. Checked locally: timeout 1e1 true and timeout 1.5e1s true both exit 0, and both forms executed a stand-in rm. Float there means strtod, so the operand class now takes the scientific spellings; both are tests.

Comment thread studio/backend/core/inference/tools.py Outdated
)
# Command-position separators for the screens below. `:` is absent on purpose: its arguments are
# expanded but never executed.
_SUBST_CMD_SEP = r"(?:^|[;&|\n({]|&&|\|\||\b(?:then|do|else|elif|if|while|until)\b\s*|!\s*)"

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 Treat coproc's command operand as a command site

In Bash, coproc $(ls /usr/bin | grep '^rm$') -rf victim executes the substitution output asynchronously, but coproc is absent from the command-site keywords and wrappers, so _find_blocked_commands returns an empty set. Bash's local help coproc documents the syntax as coproc [NAME] command [redirections]; therefore a synthesized blocked command in that operand reaches _bash_exec without being rejected.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 38c8c5a. help coproc gives coproc [NAME] command [redirections] and the form executed a stand-in rm. Added as its own branch of the separator class with the optional NAME matched only there, so it cannot widen any other separator; coproc echo hi stays allowed as a control.

Comment thread studio/backend/core/inference/tools.py Outdated
blocked.add(_BLOCKED_SYNTHESIZED_COMMAND)
if laundered_refs:
var_exec_pattern = (
_SUBST_CMD_SEP

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 Scan laundered variables in case arms

When the synthesized name is first stored in a variable, c=$(ls /usr/bin|grep '^rm$'); case x in x) $c -rf victim;; esac executes the resulting rm, yet this variable-execution regex only recognizes _SUBST_CMD_SEP and has no case-arm handling, so _find_blocked_commands returns an empty set. The fresh evidence after the direct case-site fix is that _case_arm_sites is applied only to substitutions, leaving the newly added laundering path bypassable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 38c8c5a. Correct catch on the shape of the earlier fix: the arm handling was wired into the substitution scan only, so the laundered form still deleted. The arm walker now takes the pattern to anchor and the variable scan passes its own.

Comment thread studio/backend/core/inference/tools.py Outdated
+ r")\})"
# The closing quote ends the word too, or `"$c"` - the recommended spelling -
# walks through the screen the bare one is caught by.
r"\"?)(?=\s|$|[;&|)\]}])"

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 Reject laundered variables embedded in a command word

Bash concatenates adjacent expansion and literal fragments into one command word, so x=$(printf r); ${x}m -rf victim invokes rm; however, this lookahead requires the variable expansion to end the word, causing _find_blocked_commands to return an empty set for that command. A laundered expansion used as a command-word prefix therefore bypasses the hard blocklist even though the assignment was collected as unscreenable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 38c8c5a. Bash concatenates adjacent fragments into one word, so x=$(printf r); ${x}m runs rm; the lookahead required the expansion to end the word. Trailing word characters are now part of the same word, and the precise literal is only reported when the expansion IS the whole word: glued to more text it is a fragment of an unknown name, not that name. v=$(date); echo ${v}Z stays allowed.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
All four reported by review, all four verified here against a stand-in rm on
PATH before changing anything.

- timeout's DURATION is a float, and float there means strtod, so `timeout 1e1`
  and `timeout 1.5e1s` are valid and both ran. The operand class now takes the
  scientific spellings.
- `coproc [NAME] command` (bash `help coproc`) runs COMMAND asynchronously, so
  its operand is a command position. Added with its optional NAME matched only
  in the coproc branch, where it cannot widen any other separator.
- A case arm runs a laundered variable as readily as a substitution, but the
  arm handling was wired only into the substitution scan, so
  `c=$(ls /usr/bin|grep '^rm$'); case x in x) $c -rf victim;; esac` still
  deleted. The arm walker now takes the pattern to anchor, and the variable
  scan passes its own.
- Bash concatenates adjacent fragments into one word, so `x=$(printf r);
  ${x}m` runs rm. The scan required the expansion to END the word. Trailing
  word characters are now part of the same word, and a precise literal is only
  reported when the expansion is the whole word: glued to more text it is a
  fragment of an unknown name, not that name.

Corpus unchanged at 0 regressions and 36 bypasses blocked across the posix and
both Windows lexer paths; timing still linear to 260 KB. 7 new tests.
@danielhanchen

Copy link
Copy Markdown
Member

@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: 38c8c5afb2

ℹ️ 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 thread studio/backend/core/inference/tools.py Outdated
)
# Redirections may precede the command word (`>out.log $(...)` runs the substitution's output),
# and the token walker already treats them as leaving command position intact.
_SUBST_REDIR_PREFIX = r"(?:\d*(?:>>|<<<|<<|>&|<&|>|<)[^\s;&|()]*\s*)*"

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 Consume separated redirection filenames

When the redirection target is separated from its operator, as in > out.log $(ls /usr/bin | grep '^rm$') -rf victim, Bash still treats the substitution output as the command, but this prefix consumes only an attached target and stops at out.log; the substitution is therefore never screened. The fresh evidence beyond the earlier leading-redirection fix is that Bash accepts whitespace between the operator and filename, whereas the added test covers only >out.log, allowing the synthesized blocked binary to reach execution.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in ec3170f; it executed a stand-in rm. The redirection prefix now allows whitespace between the operator and its target, with the target and the space after it BOTH mandatory: that is what keeps >$(ls) cmd out, since a substitution that is the redirection target names a file and is not run. Added as a test alongside the blocked form.

Comment on lines +5075 to +5078
_SUBST_WRAPPER_ARG = (
r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+"
r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*"
r"|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[smhd]?)"

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 Consume env long-option operands

For env --chdir /tmp $(ls /usr/bin | grep '^rm$') -rf victim, the generic flag branch consumes --chdir, but /tmp is then treated as the forwarded command and the substitution site is missed. In the inspected GNU environment, env --help documents -C, --chdir=DIR as taking a directory and the separated --chdir /tmp spelling is accepted, so this valid wrapper invocation can execute the synthesized blocked command unless all value-taking env options are represented.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in ec3170f; it executed a stand-in rm. Worth recording where the fix went: adding -C/--chdir to _WRAPPER_VALUE_FLAGS_BY_CMD broke two real detections in test_permission_mode, because that table also drives the high-risk classifier and -C / is exactly what makes a following relative etc/passwd sensitive. It is now scoped to the substitution site scan. -S/--split-string is deliberately left out of both: its operand is split into the argv that runs, and consuming it as a value made env -S 'rm -rf /tmp/x' come back empty.

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +1560 to +1563
if state == '"':
# Double quotes DO substitute, but into a word the outer command receives - unless
# the quote opens at the site itself (`"$(...)"`), which is a command word.
return match.group(0).endswith('"$(')

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 Recognize double-quoted backticks as command sites

At the beginning of a command word, Bash executes a double-quoted backtick expansion just like the explicitly supported "$(...)" form; for example, "ls /usr/bin | grep '^rm$'" -rf victim invokes rm. This branch accepts only a match ending in "$( while _SUBST_OPENER also lacks a quoted-backtick alternative, so the enumeration body is skipped and the blocked binary can execute.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in ec3170f; it executed a stand-in rm. The opener now carries a quoted-backtick alternative and the command-position test accepts a match ending in it, matching the "$(...)" handling. echo "\date`"` stays allowed as a control.

Comment on lines +1608 to +1612
body = _command_subst_body(command, opener)
lowered_body = body.lower()
blocked.update(_blocked_body_words(lowered_body))
if _SUBST_ENUMERATES_COMMANDS_RE.search(lowered_body):
blocked.add(_BLOCKED_SYNTHESIZED_COMMAND)

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 Reject substitutions glued to literal fragments

A recognized substitution can still form only part of the executable word: "$(printf r)"m -rf victim is concatenated by Bash into rm, while this loop sees only the benign body printf r and reports neither a blocked word nor an enumerator. The new evidence beyond the fixed laundered-variable-prefix case is that a direct substitution follows the same concatenation rule, and the leading quote also prevents the separate high-risk command-site regex from failing closed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in ec3170f. Both the quoted form you gave and the bare $(printf r)m executed a stand-in rm, so the fix covers both: a substitution with more word text after it now fails closed, since the body being benign says nothing about the word that runs. It also closes $(echo reb)oot, which my corpus had carried as an open vector since the first round.

Four more reported by review, all four verified against a stand-in rm before
changing anything, plus a fifth found while testing them.

- Bash allows whitespace between a redirection operator and its target, so
  `> out.log $(...)` is the same command the attached spelling was fixed for.
  The target and the space after it are mandatory in the prefix, which is what
  keeps `>$(ls) cmd` out: a substitution that IS the target names a file.
- `env -C/--chdir DIR` takes a separate value, so the DIR read as the command.
- A double-quoted backtick expands exactly like `"$(...)"` and opens a command
  word the same way.
- Bash concatenates adjacent fragments into one word, so `"$(printf r)"m` and
  the bare `$(printf r)m` both run rm while the body reads benign. A
  substitution with more word text after it now fails closed. That also closes
  `$(echo reb)oot`, which the corpus had carried as open since the first round.

The env fix is deliberately NOT in _WRAPPER_VALUE_FLAGS_BY_CMD. Putting it
there broke two real detections, caught by test_permission_mode: that table
also drives the high-risk classifier, where `-C /` is exactly what makes a
following relative `etc/passwd` sensitive. And `-S`/`--split-string` is left
out entirely, because its operand is split into the argv that RUNS - consuming
it as a value lost the command, and `env -S 'rm -rf /tmp/x'` went unblocked.

Corpus now 0 regressions and 37 bypasses blocked across the posix and both
Windows lexer paths; timing linear to 260 KB; 10 new tests.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: ec3170f45a

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

Checked the command-position sites against main, where the literal-name scan still lets both repros through, and the review round since has closed the redirection-prefix, case-arm, coproc, timeout-operand and glued-word variants. Will get this reviewed.

@danielhanchen

Copy link
Copy Markdown
Member

Benchmarked this before merging, since tool-call screening runs on every command the model issues.

Measured on a 2637-command corpus, interleaved base/head pairs to cancel drift on a shared host (the box was at load ~29, so sequential runs are not trustworthy here):

_find_blocked_commands median
merge base 72.4, 73.7, 72.5, 73.2, 73.8 us
this PR 90.5, 90.9, 98.8, 90.9, 90.5 us

So about +17 us per command, or +24%. In absolute terms that is nothing against the milliseconds a tool call takes, and it is per command rather than per token, so nothing about inference throughput changes. I am not asking for it back: the substitution scan is doing real work and the cost is proportionate.

Worth pointing out separately, because it more than pays for the above and is not your code. Profiling the head, the single hottest thing in the scan is pre-existing:

566856  0.194  0.463  re/__init__.py:305(escape)
583380  0.139  0.602  tools.py:1539(<genexpr>)

_find_blocked_commands rebuilds the blocked-word alternation on every call:

words_alt = "|".join(re.escape(w) for w in sorted(_BLOCKED_COMMANDS))
pattern = rf"...({words_alt})..."
blocked.update(re.findall(pattern, lowered))

_BLOCKED_COMMANDS is a module-level frozenset assigned once at import and never mutated, so that pattern is a compile-time constant. Hoisting it to a module-level re.compile puts the head back at parity with base:

median
base 74.3, 77.7, 79.3, 75.5 us
head 96.5, 94.2, 95.6, 91.7 us
head + hoist 78.8, 75.2, 75.5 us (first run 87.6 is cold)

tests/test_sandbox_tools.py and tests/test_permission_mode.py stay green with it (1999 passed, 1 skipped), and the blocked/allowed verdicts are unchanged on the substitution cases this PR adds.

Happy to land that hoist as its own change against main rather than widening this PR, since it is independent of what you are fixing. Say which you prefer.

@danielhanchen
danielhanchen merged commit a09f376 into unslothai:main Sep 14, 2026
1 check passed
danielhanchen added a commit that referenced this pull request Sep 14, 2026
#10927)

* Studio: build the blocked-command alternation once instead of per call

_find_blocked_commands rebuilt its blocked-word regex on every command it screened.
_BLOCKED_COMMANDS is a module-level frozenset assigned at import and never mutated,
so that alternation is a compile-time constant and the work was pure waste: an
re.escape per blocked name per command, then a fresh re.compile behind re.findall's
cache lookup.

It showed up as the top entry when profiling the scan over a 2637 command corpus,
567k calls to re.escape and 0.60s cumulative out of 3.9s. Hoisting it to a
module-level compile takes the median from about 101 us to about 86 us per command,
measured on interleaved pairs against main (the hoist wins all five pairs; absolute
figures run high because the host is loaded, so only the pairing is meaningful).

No behaviour change, and not taken on trust: verdicts were dumped for 1829 payloads
on both sides, covering the corpus plus the command-position substitution shapes
from #10860, path-qualified and .exe spellings, and ordinary commands. Zero
differences. tests/test_sandbox_tools.py, tests/test_permission_mode.py,
tests/test_bypass_permissions.py and tests/test_windows_bash_shell.py stay green
(2199 passed, 5 skipped).

This is per command screened, not per token, so it changes nothing about inference
throughput. It is worth doing because the scan runs on every command a model issues.

* Tighten the comment on the hoisted alternation

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Safety check does not work with devised commands.

2 participants