shell tool crashes with a raw ValueError instead of a descriptive ExecutionError when the command contains an embedded NUL byte #181

Closed
opened 2026-11-20 09:46:55 +00:00 by CoreRasurae · 0 comments
Member

Metadata

Commit Message: fix(agents): reject shell tool commands containing an embedded NUL byte before spawning a subprocess
Branch: bugfix/m1-shell-nul-byte-command

Background and context

ToolAgent._execute_shell_command (src/cleveractors/agents/tool.py) is the shared implementation behind the shell tool. Before spawning anything, it only runs _enforce_safe_mode_blocklist, a case-insensitive substring check against a fixed list of dangerous words (rm, del, format, shutdown, reboot, kill). It performs no check that the command string (or the args list appended to it) is well-formed input for the underlying OS process-spawn call. It then builds cmd_str and calls asyncio.create_subprocess_shell(cmd_str, ...). CPython's subprocess machinery raises a raw ValueError ("embedded null byte") for any command string containing a NUL byte, before the system shell is ever invoked. _execute_shell_command's try block around that call only has an except asyncio.TimeoutError clause — there is no except for anything else — so the ValueError is not caught by _execute_shell_command, _shell_tool, or _execute_tool.

This is the same defect class reported in #175 for file_write (a corrupted/malformed tool argument sails through the tool's own validation and only fails deep inside a lower-level call, with a raw, un-descriptive error) — discovered while auditing file_read, shell, and python_exec for the same class of defect, at the maintainer's request, following up on #175/#176/PR #178. (A sibling finding for file_read, same root pattern but a different code path, is filed separately — see Supporting information.)

Current behavior

Confirmed directly against this branch by invoking the tool programmatically:

await tool_agent.invoke("shell", {"command": "echo abc\x00def"})

raises:

ValueError: embedded null byte

This propagates uncaught out of _execute_shell_command, _shell_tool, and _execute_tool. When the tool agent is driven through ToolAgent.invoke() — the graph-node dispatch entry point — there is no surrounding catch-all, so the raw ValueError reaches the caller directly instead of the agent's ExecutionError contract. When driven instead through process_message(), the outer generic except Exception as e there does catch and re-wrap it as ExecutionError(f"Tool execution failed: {str(e)}"), but the message is still just Python's raw low-level text, with no indication that the command itself was malformed rather than, e.g., a timeout or a non-zero exit.

Note for contrast: other forms of malformed/garbled shell input (unterminated quotes, stray markup, etc.) are already handled correctly today — the system shell itself rejects them, and the resulting non-zero exit code and stderr are captured and reported as a clean ExecutionError(f"Command failed with code {process.returncode}: {error_msg}"). Only the embedded-NUL-byte case bypasses that path entirely, because the crash happens before the shell is ever reached, at the Python/OS exec-argument layer.

Expected behavior

_execute_shell_command (shared by _shell_tool and the bundled skill-script execution path) rejects a command string containing an embedded NUL byte — and, for the shell tool specifically, any args entry that would be concatenated into it — with a descriptive ExecutionError, raised before asyncio.create_subprocess_shell is called. The behavior must be identical regardless of which public entry point (invoke() or process_message()) dispatches the call.

Acceptance criteria

  • A shell call whose command argument (or an entry in its args list) contains an embedded NUL byte is rejected with an ExecutionError before asyncio.create_subprocess_shell is reached.
  • The rejection happens identically whether shell is dispatched via ToolAgent.invoke() or ToolAgent.process_message() — no raw ValueError reaches either caller.
  • The raised ExecutionError message names the specific problem found (an embedded NUL byte), not a propagated low-level ValueError string.
  • Legitimate shell commands — including ones with pipes, redirections, &&/|| chaining, quoting, and the existing safe-mode blocklist behavior — continue to work unchanged; no regression on valid inputs.
  • The _run_skill_script_command path (which uses create_subprocess_exec, not create_subprocess_shell, for bundled skill scripts) is explicitly out of scope for this issue unless shown to share the same crash — confirm whether it does, and note the result in this issue's PR description.

Supporting information

  • Affected method: ToolAgent._execute_shell_command in src/cleveractors/agents/tool.py. Crash site: the unguarded asyncio.create_subprocess_shell(cmd_str, ...) call, inside a try block whose only except clause is asyncio.TimeoutError.
  • Related but distinct: #175 (file_write's malformed-path defect) and the sibling issue filed for the identical NUL-byte defect in file_read's os.path.realpath() call — same bug class, different tool, different crash site, filed separately per the project's one-concern-per-issue rule.

Subtasks

  • Add a check to _execute_shell_command that rejects a command (and, for the shell tool, any args entry) containing an embedded NUL byte, raising a descriptive ExecutionError, before asyncio.create_subprocess_shell is called.
  • Confirm whether _run_skill_script_command's create_subprocess_exec call shares the same crash for an embedded-NUL argv entry; if so, apply the equivalent guard there in the same commit, otherwise record the negative finding in the PR description.
  • Tests (Behave): add scenarios in features/ covering a shell command containing an embedded NUL byte, both as the command value and as an args entry, confirming the failure is an ExecutionError (not a raw ValueError) from both the invoke() and process_message() entry points, and confirming valid shell commands (pipes, redirects, chaining) remain unaffected.
  • Verify coverage >=97% via nox -s coverage_report.
  • Run nox (all default sessions), fix any errors.

Definition of Done

This issue is complete when:

  • All subtasks above are completed and checked off.
  • A Git commit is created where the first line matches the Commit Message in Metadata exactly.
  • The commit is pushed to the branch matching the Branch in Metadata exactly.
  • The commit is submitted as a PR to master, reviewed, and merged.
  • A companion Type/Testing TDD issue exists, the TDD scenario (tagged @tdd_expected_fail) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue.

Note for triage

This fits Epic #77 ("LLM Agent Runtime Stabilization") as a tool-dispatch input-validation hardening item, alongside its sibling #175 and the companion file_read issue found in the same audit — recommend linking it there, but leaving the final call, milestone assignment, and MoSCoW to maintainer/project-owner triage.

## Metadata Commit Message: `fix(agents): reject shell tool commands containing an embedded NUL byte before spawning a subprocess` Branch: bugfix/m1-shell-nul-byte-command ## Background and context `ToolAgent._execute_shell_command` (`src/cleveractors/agents/tool.py`) is the shared implementation behind the `shell` tool. Before spawning anything, it only runs `_enforce_safe_mode_blocklist`, a case-insensitive substring check against a fixed list of dangerous words (`rm`, `del`, `format`, `shutdown`, `reboot`, `kill`). It performs no check that the `command` string (or the `args` list appended to it) is well-formed input for the underlying OS process-spawn call. It then builds `cmd_str` and calls `asyncio.create_subprocess_shell(cmd_str, ...)`. CPython's subprocess machinery raises a raw `ValueError` ("embedded null byte") for any command string containing a NUL byte, before the system shell is ever invoked. `_execute_shell_command`'s `try` block around that call only has an `except asyncio.TimeoutError` clause — there is no `except` for anything else — so the `ValueError` is not caught by `_execute_shell_command`, `_shell_tool`, or `_execute_tool`. This is the same defect class reported in #175 for `file_write` (a corrupted/malformed tool argument sails through the tool's own validation and only fails deep inside a lower-level call, with a raw, un-descriptive error) — discovered while auditing `file_read`, `shell`, and `python_exec` for the same class of defect, at the maintainer's request, following up on #175/#176/PR #178. (A sibling finding for `file_read`, same root pattern but a different code path, is filed separately — see Supporting information.) ## Current behavior Confirmed directly against this branch by invoking the tool programmatically: ```python await tool_agent.invoke("shell", {"command": "echo abc\x00def"}) ``` raises: ``` ValueError: embedded null byte ``` This propagates uncaught out of `_execute_shell_command`, `_shell_tool`, and `_execute_tool`. When the tool agent is driven through `ToolAgent.invoke()` — the graph-node dispatch entry point — there is no surrounding catch-all, so the raw `ValueError` reaches the caller directly instead of the agent's `ExecutionError` contract. When driven instead through `process_message()`, the outer generic `except Exception as e` there does catch and re-wrap it as `ExecutionError(f"Tool execution failed: {str(e)}")`, but the message is still just Python's raw low-level text, with no indication that the command itself was malformed rather than, e.g., a timeout or a non-zero exit. Note for contrast: other forms of malformed/garbled shell input (unterminated quotes, stray markup, etc.) are already handled correctly today — the system shell itself rejects them, and the resulting non-zero exit code and stderr are captured and reported as a clean `ExecutionError(f"Command failed with code {process.returncode}: {error_msg}")`. Only the embedded-NUL-byte case bypasses that path entirely, because the crash happens before the shell is ever reached, at the Python/OS exec-argument layer. ## Expected behavior `_execute_shell_command` (shared by `_shell_tool` and the bundled skill-script execution path) rejects a `command` string containing an embedded NUL byte — and, for the `shell` tool specifically, any `args` entry that would be concatenated into it — with a descriptive `ExecutionError`, raised before `asyncio.create_subprocess_shell` is called. The behavior must be identical regardless of which public entry point (`invoke()` or `process_message()`) dispatches the call. ## Acceptance criteria - A `shell` call whose `command` argument (or an entry in its `args` list) contains an embedded NUL byte is rejected with an `ExecutionError` **before** `asyncio.create_subprocess_shell` is reached. - The rejection happens identically whether `shell` is dispatched via `ToolAgent.invoke()` or `ToolAgent.process_message()` — no raw `ValueError` reaches either caller. - The raised `ExecutionError` message names the specific problem found (an embedded NUL byte), not a propagated low-level `ValueError` string. - Legitimate shell commands — including ones with pipes, redirections, `&&`/`||` chaining, quoting, and the existing safe-mode blocklist behavior — continue to work unchanged; no regression on valid inputs. - The `_run_skill_script_command` path (which uses `create_subprocess_exec`, not `create_subprocess_shell`, for bundled skill scripts) is explicitly out of scope for this issue unless shown to share the same crash — confirm whether it does, and note the result in this issue's PR description. ## Supporting information - Affected method: `ToolAgent._execute_shell_command` in `src/cleveractors/agents/tool.py`. Crash site: the unguarded `asyncio.create_subprocess_shell(cmd_str, ...)` call, inside a `try` block whose only `except` clause is `asyncio.TimeoutError`. - Related but distinct: #175 (`file_write`'s malformed-path defect) and the sibling issue filed for the identical NUL-byte defect in `file_read`'s `os.path.realpath()` call — same bug class, different tool, different crash site, filed separately per the project's one-concern-per-issue rule. ## Subtasks - [ ] Add a check to `_execute_shell_command` that rejects a `command` (and, for the `shell` tool, any `args` entry) containing an embedded NUL byte, raising a descriptive `ExecutionError`, before `asyncio.create_subprocess_shell` is called. - [ ] Confirm whether `_run_skill_script_command`'s `create_subprocess_exec` call shares the same crash for an embedded-NUL `argv` entry; if so, apply the equivalent guard there in the same commit, otherwise record the negative finding in the PR description. - [ ] Tests (Behave): add scenarios in `features/` covering a `shell` command containing an embedded NUL byte, both as the `command` value and as an `args` entry, confirming the failure is an `ExecutionError` (not a raw `ValueError`) from both the `invoke()` and `process_message()` entry points, and confirming valid shell commands (pipes, redirects, chaining) remain unaffected. - [ ] Verify coverage >=97% via `nox -s coverage_report`. - [ ] Run `nox` (all default sessions), fix any errors. ## Definition of Done This issue is complete when: - All subtasks above are completed and checked off. - A Git commit is created where the first line matches the Commit Message in Metadata exactly. - The commit is pushed to the branch matching the Branch in Metadata exactly. - The commit is submitted as a PR to master, reviewed, and merged. - A companion `Type/Testing` TDD issue exists, the TDD scenario (tagged `@tdd_expected_fail`) is merged first, and this issue's Forgejo dependency correctly shows it depends on that TDD issue. ## Note for triage This fits Epic #77 ("LLM Agent Runtime Stabilization") as a tool-dispatch input-validation hardening item, alongside its sibling #175 and the companion `file_read` issue found in the same audit — recommend linking it there, but leaving the final call, milestone assignment, and MoSCoW to maintainer/project-owner triage.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
cleveragents/cleveractors-core#181
No description provided.