Repository navigation
fix(computer): parse rm targets in local shell blocklist - #11045
Ethereal49 wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Hey - I've found 11 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/computer/booters/local.py" line_range="140" />
<code_context>
+ current_dir = None
+ continue
+
+ if token != "rm" and token.lstrip("`").lower() != "rm":
+ continue
+
</code_context>
<issue_to_address>
**Path-qualified rm bypasses validation**
When a recursive delete invokes `rm` through a path-qualified, escaped, or shell-expanded command name, the exact-token check does not recognize these command names, so `_is_safe_command` skips recursive-target validation and the local shell executes the deletion. The previous raw `rm` blocklist patterns are also gone.
Recognize `rm` after normalizing command names, including path-qualified and escaped forms, and apply recursive-target validation before execution.
</issue_to_address>
### Comment 2
<location path="astrbot/core/computer/booters/local.py" line_range="132-133" />
<code_context>
+ for token in segment:
+ if token != "rm" and "rm " in token.lower():
+ nested_cwd = str(current_dir) if current_dir is not None else "/"
+ if not _is_safe_command(token, cwd=nested_cwd):
+ return False
+
+ for index, token in enumerate(segment):
</code_context>
<issue_to_address>
**Relative cleanup uses the wrong directory**
When a command changes directory before a relative recursive cleanup, or an argument happens to equal `cd`, the scan clears `current_dir` for any `cd` token without tracking the resulting directory, and it does not track directory changes such as `pushd`; nested validation then substitutes `/`. This rejects valid relative cleanups after `cd` while allowing some nested relative targets to be checked against the wrong directory and escape the intended workspace.
Track actual directory-changing commands and pass the resulting effective directory to nested-command validation instead of clearing it or substituting `/`.
Also at `astrbot/core/computer/booters/local.py:131`, `astrbot/core/computer/booters/local.py:136-138`.
</issue_to_address>
### Comment 3
<location path="astrbot/core/computer/booters/local.py" line_range="204-206" />
<code_context>
+ ):
+ continue
+ if (
+ current_dir is not None
+ and resolved != current_dir
+ and resolved.is_relative_to(current_dir)
+ ):
+ continue
</code_context>
<issue_to_address>
**System paths pass recursive-delete guard**
When the effective working directory contains a target outside the approved temporary roots, especially when `cwd` is `/`, `resolved.is_relative_to(current_dir)` accepts any descendant of the working directory, so `/etc` passes when `cwd` is `/`; the same allowance also permits paths under the AstrBot root despite the `/tmp`-only boundary described in the issue.
Restrict recursive-delete targets to the approved temporary paths rather than allowing every descendant of `current_dir`.
</issue_to_address>
### Comment 4
<location path="astrbot/core/computer/booters/local.py" line_range="194" />
<code_context>
+ return False
+ target_path = current_dir / target_path
+ try:
+ resolved = target_path.resolve()
+ except (OSError, RuntimeError):
+ return False
</code_context>
<issue_to_address>
**Symlink changes bypass path validation**
When a command or another process changes a target's parent path to a symlink after validation, before the shell removes it, `target_path.resolve()` validates the path before execution, but the shell resolves it again later; a symlink created in between redirects the deletion outside the allowed roots.
Ensure the path remains within the allowed roots at deletion time rather than relying only on the earlier `resolve()` check.
Also at `astrbot/core/computer/booters/local.py:307`, `astrbot/core/computer/booters/local.py:435`.
</issue_to_address>
### Comment 5
<location path="astrbot/core/computer/booters/local.py" line_range="119" />
<code_context>
+ segments: list[list[str]] = []
+ segment: list[str] = []
+ for token in tokens:
+ if token and set(token) <= set(";|&()"):
+ if segment:
+ segments.append(segment)
</code_context>
<issue_to_address>
**Extglob hides deletion targets**
When a command enables Bash extglob and uses an extglob pattern as an `rm` target, the segment splitter treats extglob parentheses and `|` as shell separators before validating targets, so `bash -O extglob -c 'rm -rf @(/etc|/usr)'` is accepted and Bash expands the pattern to protected directories before deleting them.
Use shell-aware parsing that preserves extglob patterns as targets, or reject unsupported shell syntax whenever it could conceal an `rm` target.
</issue_to_address>
### Comment 6
<location path="astrbot/core/computer/booters/local.py" line_range="109" />
<code_context>
+
+ for line in command.splitlines() or [""]:
+ try:
+ lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
+ lexer.whitespace_split = True
+ lexer.commenters = ""
</code_context>
<issue_to_address>
**Windows paths lose backslashes**
When the local shell runs on Windows and a recursive target uses an unquoted drive-qualified backslash path, pOSIX-mode `shlex` removes backslashes, so the guard treats paths such as `C:\Windows` as drive-relative children of `cwd`, while PowerShell receives the original absolute path and can delete outside that scope.
Tokenize or preserve Windows paths so the guard validates the same drive-qualified path that the shell executes.
</issue_to_address>
### Comment 7
<location path="astrbot/core/computer/booters/local.py" line_range="130" />
<code_context>
+
+ for segment in segments:
+ for token in segment:
+ if token != "rm" and "rm " in token.lower():
+ nested_cwd = str(current_dir) if current_dir is not None else "/"
+ if not _is_safe_command(token, cwd=nested_cwd):
</code_context>
<issue_to_address>
**Tabbed rm commands skip nested validation**
When a nested shell command has a tab between `rm` and its recursive option, the nested-command scan looks only for the literal substring `rm `, so it does not inspect commands such as `sh -c 'rm\t-rf /'`; the inner shell treats the tab as whitespace and executes the recursive delete without target validation.
Detect `rm` followed by any shell whitespace when scanning nested commands.
</issue_to_address>
### Comment 8
<location path="astrbot/core/computer/booters/local.py" line_range="171" />
<code_context>
+ if not options_done and arg == "--":
+ options_done = True
+ elif not options_done and arg.startswith("-") and arg != "-":
+ if arg == "--recursive":
+ recursive = True
+ elif not arg.startswith("--") and "r" in arg[1:].lower():
</code_context>
<issue_to_address>
**Abbreviated recursive option bypasses validation**
When a GNU `rm` command uses an unambiguous long-option abbreviation, such as `rm --recurs /etc`, `--recurs` is treated as a non-recursive option, so `_is_safe_command` skips target validation; GNU `rm` accepts that unambiguous abbreviation of `--recursive` and can delete system paths such as `/etc`.
Recognize valid abbreviations of recursive long options or reject unrecognized long options conservatively.
</issue_to_address>
### Comment 9
<location path="astrbot/core/computer/booters/local.py" line_range="194" />
<code_context>
+ return False
+ target_path = current_dir / target_path
+ try:
+ resolved = target_path.resolve()
+ except (OSError, RuntimeError):
+ return False
</code_context>
<issue_to_address>
**Symlink paths bypass scope checks**
When a recursive `rm` target is a symlink whose referent is inside an allowed root but whose directory entry is outside it,, `Path.resolve()` follows the final symlink, so a target path outside the allowed roots that points into the working directory passes validation; `rm` then unlinks the symlink at the outside path. Conversely, an in-scope symlink pointing outside is rejected even though `rm` would unlink only the symlink.
Check the path that `rm` will unlink by resolving its parent components without following the final symlink, then apply the scope checks to that entry path.
</issue_to_address>
### Comment 10
<location path="astrbot/core/computer/booters/local.py" line_range="105" />
<code_context>
+ except (OSError, RuntimeError):
+ return False
+
+ temp_roots = (_LOCAL_PATH("/tmp").resolve(), _LOCAL_PATH("/var/tmp").resolve())
+
+ for line in command.splitlines() or [""]:
</code_context>
<issue_to_address>
**Temporary-root resolution can abort checks**
When resolving `/tmp` or `/var/tmp` raises an `OSError` or `RuntimeError`, `Path.resolve()` can raise `RuntimeError` for a symlink loop or `OSError` for filesystem failures, and this call is outside the exception handling; `_is_safe_command` then raises for every command instead of returning a safety decision.
Resolve the temporary roots inside the existing fail-closed exception handling and return `False` if resolution fails.
</issue_to_address>
### Comment 11
<location path="astrbot/core/computer/booters/local.py" line_range="167-174" />
<code_context>
+ recursive = False
+ options_done = False
+ targets: list[str] = []
+ for arg in args:
+ if not options_done and arg == "--":
+ options_done = True
+ elif not options_done and arg.startswith("-") and arg != "-":
+ if arg == "--recursive":
+ recursive = True
+ elif not arg.startswith("--") and "r" in arg[1:].lower():
+ recursive = True
</code_context>
<issue_to_address>
**Windows cleanup syntax is rejected**
When a Windows caller uses the newly supported `rm -rf <scoped-target>` cleanup form, `LocalShellComponent.exec` runs shell commands through PowerShell on Windows (`astrbot/core/computer/booters/local.py:320-330`), where `rm` is the `Remove-Item` alias and `-rf` is not a bundled `-Recurse`/`-Force` option; the guard allows the scoped command, but PowerShell rejects it instead of deleting the target.
Either translate the supported recursive-delete form for PowerShell or document and validate the platform-specific syntax callers must use.
</issue_to_address>Linked issues
#11039 [Bug] shell blocklist rejects rm -rf under /tmp because it is a raw substring match · 1 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Allow literal recursive cleanup targets under /tmp. |
✅ Met | The guard parses recursive rm targets and allows literal paths below /tmp, including within compound commands. |
| 2 | Keep blocking non-/tmp targets, unresolved targets, and the other blocked command patterns. |
🟡 Partly met | Variables, globs, .., and the existing blocked patterns remain blocked, but the guard also allows recursive deletion below the working directory and /var/tmp. |
Sourcery assessment
Needs a human reviewer. 11 findings to address first, and the new check allows recursive deletion of paths beneath the supplied working directory; if that directory is /, a command such as rm -rf /etc passes. Files deleted this way are not restored by reverting the change, and the policy can permit destructive access without signaling that the scope is unsafe.
Blocking findings: astrbot/core/computer/booters/local.py:140, astrbot/core/computer/booters/local.py:133, astrbot/core/computer/booters/local.py:206, astrbot/core/computer/booters/local.py:194, astrbot/core/computer/booters/local.py:119, and 6 more
| current_dir = None | ||
| continue | ||
|
|
||
| if token != "rm" and token.lstrip("`").lower() != "rm": |
There was a problem hiding this comment.
🔴 Critical · Path-qualified rm bypasses validation
When a recursive delete invokes rm through a path-qualified, escaped, or shell-expanded command name, the exact-token check does not recognize these command names, so _is_safe_command skips recursive-target validation and the local shell executes the deletion. The previous raw rm blocklist patterns are also gone.
Recognize rm after normalizing command names, including path-qualified and escaped forms, and apply recursive-target validation before execution.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 140:
**Path-qualified rm bypasses validation**
When a recursive delete invokes `rm` through a path-qualified, escaped, or shell-expanded command name, the exact-token check does not recognize these command names, so `_is_safe_command` skips recursive-target validation and the local shell executes the deletion. The previous raw `rm` blocklist patterns are also gone.
Recognize `rm` after normalizing command names, including path-qualified and escaped forms, and apply recursive-target validation before execution.| if not _is_safe_command(token, cwd=nested_cwd): | ||
| return False |
There was a problem hiding this comment.
🔴 Critical · Relative cleanup uses the wrong directory
When a command changes directory before a relative recursive cleanup, or an argument happens to equal cd, the scan clears current_dir for any cd token without tracking the resulting directory, and it does not track directory changes such as pushd; nested validation then substitutes /. This rejects valid relative cleanups after cd while allowing some nested relative targets to be checked against the wrong directory and escape the intended workspace.
Track actual directory-changing commands and pass the resulting effective directory to nested-command validation instead of clearing it or substituting /.
Also at astrbot/core/computer/booters/local.py:131, astrbot/core/computer/booters/local.py:136-138.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at lines 132-133:
**Relative cleanup uses the wrong directory**
When a command changes directory before a relative recursive cleanup, or an argument happens to equal `cd`, the scan clears `current_dir` for any `cd` token without tracking the resulting directory, and it does not track directory changes such as `pushd`; nested validation then substitutes `/`. This rejects valid relative cleanups after `cd` while allowing some nested relative targets to be checked against the wrong directory and escape the intended workspace.
Track actual directory-changing commands and pass the resulting effective directory to nested-command validation instead of clearing it or substituting `/`.
Also at `astrbot/core/computer/booters/local.py:131`, `astrbot/core/computer/booters/local.py:136-138`.| current_dir is not None | ||
| and resolved != current_dir | ||
| and resolved.is_relative_to(current_dir) |
There was a problem hiding this comment.
🔴 Critical · System paths pass recursive-delete guard
When the effective working directory contains a target outside the approved temporary roots, especially when cwd is /, resolved.is_relative_to(current_dir) accepts any descendant of the working directory, so /etc passes when cwd is /; the same allowance also permits paths under the AstrBot root despite the /tmp-only boundary described in the issue.
Restrict recursive-delete targets to the approved temporary paths rather than allowing every descendant of current_dir.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at lines 204-206:
**System paths pass recursive-delete guard**
When the effective working directory contains a target outside the approved temporary roots, especially when `cwd` is `/`, `resolved.is_relative_to(current_dir)` accepts any descendant of the working directory, so `/etc` passes when `cwd` is `/`; the same allowance also permits paths under the AstrBot root despite the `/tmp`-only boundary described in the issue.
Restrict recursive-delete targets to the approved temporary paths rather than allowing every descendant of `current_dir`.From #11039:
Keep blocking non-`/tmp` targets, unresolved targets, and the other blocked command patterns.| return False | ||
| target_path = current_dir / target_path | ||
| try: | ||
| resolved = target_path.resolve() |
There was a problem hiding this comment.
🔴 Critical · Symlink changes bypass path validation
When a command or another process changes a target's parent path to a symlink after validation, before the shell removes it, target_path.resolve() validates the path before execution, but the shell resolves it again later; a symlink created in between redirects the deletion outside the allowed roots.
Ensure the path remains within the allowed roots at deletion time rather than relying only on the earlier resolve() check.
Also at astrbot/core/computer/booters/local.py:307, astrbot/core/computer/booters/local.py:435.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 194:
**Symlink changes bypass path validation**
When a command or another process changes a target's parent path to a symlink after validation, before the shell removes it, `target_path.resolve()` validates the path before execution, but the shell resolves it again later; a symlink created in between redirects the deletion outside the allowed roots.
Ensure the path remains within the allowed roots at deletion time rather than relying only on the earlier `resolve()` check.
Also at `astrbot/core/computer/booters/local.py:307`, `astrbot/core/computer/booters/local.py:435`.| segments: list[list[str]] = [] | ||
| segment: list[str] = [] | ||
| for token in tokens: | ||
| if token and set(token) <= set(";|&()"): |
There was a problem hiding this comment.
🟠 High · Extglob hides deletion targets
When a command enables Bash extglob and uses an extglob pattern as an rm target, the segment splitter treats extglob parentheses and | as shell separators before validating targets, so bash -O extglob -c 'rm -rf @(/etc|/usr)' is accepted and Bash expands the pattern to protected directories before deleting them.
Use shell-aware parsing that preserves extglob patterns as targets, or reject unsupported shell syntax whenever it could conceal an rm target.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 119:
**Extglob hides deletion targets**
When a command enables Bash extglob and uses an extglob pattern as an `rm` target, the segment splitter treats extglob parentheses and `|` as shell separators before validating targets, so `bash -O extglob -c 'rm -rf @(/etc|/usr)'` is accepted and Bash expands the pattern to protected directories before deleting them.
Use shell-aware parsing that preserves extglob patterns as targets, or reject unsupported shell syntax whenever it could conceal an `rm` target.|
|
||
| for segment in segments: | ||
| for token in segment: | ||
| if token != "rm" and "rm " in token.lower(): |
There was a problem hiding this comment.
🔴 Critical · Tabbed rm commands skip nested validation
When a nested shell command has a tab between rm and its recursive option, the nested-command scan looks only for the literal substring rm , so it does not inspect commands such as sh -c 'rm\t-rf /'; the inner shell treats the tab as whitespace and executes the recursive delete without target validation.
Detect rm followed by any shell whitespace when scanning nested commands.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 130:
**Tabbed rm commands skip nested validation**
When a nested shell command has a tab between `rm` and its recursive option, the nested-command scan looks only for the literal substring `rm `, so it does not inspect commands such as `sh -c 'rm\t-rf /'`; the inner shell treats the tab as whitespace and executes the recursive delete without target validation.
Detect `rm` followed by any shell whitespace when scanning nested commands.| if not options_done and arg == "--": | ||
| options_done = True | ||
| elif not options_done and arg.startswith("-") and arg != "-": | ||
| if arg == "--recursive": |
There was a problem hiding this comment.
🟠 High · Abbreviated recursive option bypasses validation
When a GNU rm command uses an unambiguous long-option abbreviation, such as rm --recurs /etc, --recurs is treated as a non-recursive option, so _is_safe_command skips target validation; GNU rm accepts that unambiguous abbreviation of --recursive and can delete system paths such as /etc.
Recognize valid abbreviations of recursive long options or reject unrecognized long options conservatively.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 171:
**Abbreviated recursive option bypasses validation**
When a GNU `rm` command uses an unambiguous long-option abbreviation, such as `rm --recurs /etc`, `--recurs` is treated as a non-recursive option, so `_is_safe_command` skips target validation; GNU `rm` accepts that unambiguous abbreviation of `--recursive` and can delete system paths such as `/etc`.
Recognize valid abbreviations of recursive long options or reject unrecognized long options conservatively.| return False | ||
| target_path = current_dir / target_path | ||
| try: | ||
| resolved = target_path.resolve() |
There was a problem hiding this comment.
🟠 High · Symlink paths bypass scope checks
When a recursive rm target is a symlink whose referent is inside an allowed root but whose directory entry is outside it,, Path.resolve() follows the final symlink, so a target path outside the allowed roots that points into the working directory passes validation; rm then unlinks the symlink at the outside path. Conversely, an in-scope symlink pointing outside is rejected even though rm would unlink only the symlink.
Check the path that rm will unlink by resolving its parent components without following the final symlink, then apply the scope checks to that entry path.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 194:
**Symlink paths bypass scope checks**
When a recursive `rm` target is a symlink whose referent is inside an allowed root but whose directory entry is outside it,, `Path.resolve()` follows the final symlink, so a target path outside the allowed roots that points into the working directory passes validation; `rm` then unlinks the symlink at the outside path. Conversely, an in-scope symlink pointing outside is rejected even though `rm` would unlink only the symlink.
Check the path that `rm` will unlink by resolving its parent components without following the final symlink, then apply the scope checks to that entry path.| except (OSError, RuntimeError): | ||
| return False | ||
|
|
||
| temp_roots = (_LOCAL_PATH("/tmp").resolve(), _LOCAL_PATH("/var/tmp").resolve()) |
There was a problem hiding this comment.
🟡 Medium · Temporary-root resolution can abort checks
When resolving /tmp or /var/tmp raises an OSError or RuntimeError, Path.resolve() can raise RuntimeError for a symlink loop or OSError for filesystem failures, and this call is outside the exception handling; _is_safe_command then raises for every command instead of returning a safety decision.
Resolve the temporary roots inside the existing fail-closed exception handling and return False if resolution fails.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at line 105:
**Temporary-root resolution can abort checks**
When resolving `/tmp` or `/var/tmp` raises an `OSError` or `RuntimeError`, `Path.resolve()` can raise `RuntimeError` for a symlink loop or `OSError` for filesystem failures, and this call is outside the exception handling; `_is_safe_command` then raises for every command instead of returning a safety decision.
Resolve the temporary roots inside the existing fail-closed exception handling and return `False` if resolution fails.| for arg in args: | ||
| if not options_done and arg == "--": | ||
| options_done = True | ||
| elif not options_done and arg.startswith("-") and arg != "-": | ||
| if arg == "--recursive": | ||
| recursive = True | ||
| elif not arg.startswith("--") and "r" in arg[1:].lower(): | ||
| recursive = True |
There was a problem hiding this comment.
🟡 Medium · Windows cleanup syntax is rejected
When a Windows caller uses the newly supported rm -rf <scoped-target> cleanup form, LocalShellComponent.exec runs shell commands through PowerShell on Windows (astrbot/core/computer/booters/local.py:320-330), where rm is the Remove-Item alias and -rf is not a bundled -Recurse/-Force option; the guard allows the scoped command, but PowerShell rejects it instead of deleting the target.
Either translate the supported recursive-delete form for PowerShell or document and validate the platform-specific syntax callers must use.
Prompt for AI agents
In `astrbot/core/computer/booters/local.py` at lines 167-174:
**Windows cleanup syntax is rejected**
When a Windows caller uses the newly supported `rm -rf <scoped-target>` cleanup form, `LocalShellComponent.exec` runs shell commands through PowerShell on Windows (`astrbot/core/computer/booters/local.py:320-330`), where `rm` is the `Remove-Item` alias and `-rf` is not a bundled `-Recurse`/`-Force` option; the guard allows the scoped command, but PowerShell rejects it instead of deleting the target.
Either translate the supported recursive-delete form for PowerShell or document and validate the platform-specific syntax callers must use.|
Withdrawn: the |
Fixes #11039.
Modifications / 改动点
Parse recursive
rminvocations from shell token segments and validate every target instead of rejecting the rawrm -rfsubstring.Allow literal cleanup targets under
/tmpand/var/tmp, plus paths inside the command's working directory.Keep rejecting
/, system paths, home-directory targets, unqualified deletes, variables, command substitution, globs, and..components.Evaluate each command separated by
&&,;,|, and related operators. Relativermtargets aftercdare blocked because the changed directory is not tracked statically.Pass the effective working directory into the local shell guard. No other booter or dependency changes.
This is NOT a breaking change. / 这不是一个破坏性变更。
Screenshots or Test Results / 运行截图或测试结果
RED before the fix:
Every allowed case failed because
_is_safe_command("rm -rf /tmp/my_build")returnedFalse.After the fix:
The tests cover
/tmpand/var/tmpcleanup, cwd-scoped relative paths, CUA's shell-quoted cleanup command, compound commands, dangerous targets, variables, globs,.., redirects, and nestedsh -c.NOT_RUN: the full repository pytest suite. Real deletion commands were not executed; the tests exercise only the decision function.Checklist / 检查清单
AI assistance disclosure: Codex prepared this patch and ran the listed local checks.
Summary by Sourcery
Safely support scoped recursive
rmcleanup while continuing to block commands that could delete system or unresolved paths.Bug Fixes:
rmsafety checks so allowed cleanup targets are validated by path rather than rejected by raw command text.Enhancements:
/tmp,/var/tmp, and the command working directory while evaluating paths relative to the effective working directory.Tests: