Repository navigation
fix(core): inspect shell wrapper variants for command substitution and policy checks - #30451
Conversation
…d policy checks Hardens shell wrapper unwrapping, command substitution detection, and policy validation so inner shell payloads wrapped by prefix utilities, intermediate shell flags, trailing arguments/operators/redirections, or Windows shell switches cannot evade inspection: - Add `extractWrappedShellCommands()` in `shell-utils.ts` using tree-sitter-bash AST decomposition (including `redirected_statement` mid-command redirections) with a linear-time fallback segmenter, POSIX quote/ANSI-C tokenizer, prefix-utility peeler (`env`, `nice`, `timeout`, `nohup`, `setsid`, `sudo`, `watch`, `xargs`, etc.), and POSIX / `eval` / `cmd.exe` / PowerShell (`-c`, `-com`, `-enc`) payload extractors. - Recursively inspect extracted wrapper payloads in `detectCommandSubstitution()` with bounded recursion depth and state caps (failing closed when exceeded). - Harden `stripSingleShellWrapper()` to avoid partially stripping `sh -c` when trailing tokens/operators/redirections, post-`-c` flags, or mixed quoting would corrupt the command or hide substitution, while preserving sandbox manager unwrapping for benign argv-joined commands. - Recursively validate extracted wrapper payloads in `PolicyEngine.checkShellCommand()` (per subcommand and top-level) so denied inner commands and command substitutions behind wrappers are consistently enforced without upgrading unapproved outer wrappers. - Add unit, policy, and `ShellToolInvocation` regression tests.
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly hardens the shell wrapper inspection logic to prevent security bypasses where malicious commands are hidden behind prefix utilities, shell flags, or Windows-specific shell wrappers. By implementing a recursive extraction and validation mechanism, the system now consistently detects command substitution and enforces security policies even when commands are deeply nested or obfuscated across various shell environments. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. Footnotes
|
|
📊 PR Size: size/XL
|
There was a problem hiding this comment.
Code Review
This pull request hardens the policy engine and shell utilities against security bypasses by introducing recursive inspection of wrapped shell commands and command substitutions across prefix utilities, shell flags, and Windows/PowerShell wrappers. The review feedback highlights two critical improvements: enforcing the recursion depth limit at the entry point of checkShellCommand to prevent stack exhaustion, and ensuring that wrapped payloads allowed by catch-all rules do not incorrectly upgrade the overall command decision to ALLOW.
…catch-all allow upgrades Addresses Gemini Code Assist review comments on PR google-gemini#30451: - Enforce `MAX_POLICY_WRAPPER_DEPTH` at the entry of `checkShellCommand()` (after explicit `DENY` short-circuiting) and preserve `wrapperDepth` when checking compound subcommands via `checkInternal()` so neither `stripShellWrapper()` nor compound splitting can bypass the cap. - Set `allSubCommandsExplicitlyAllowed = false` in `checkExtractedPayloads()` when a wrapped payload is not allowed by an explicit `argsPattern` rule. - Add regression tests for both cases in `shell-substitution.test.ts`.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements wrapper bypass hardening for the policy engine and shell utilities. It introduces extractWrappedShellCommands to recursively parse and extract inner shell command payloads wrapped by prefix utilities (such as env, nice, timeout, nohup, setsid, sudo) and shell invocations (such as sh, bash, zsh, eval, cmd.exe, powershell, pwsh). The PolicyEngine and detectCommandSubstitution logic are updated to recursively inspect these extracted payloads up to a maximum depth of 5, failing closed if the depth limit is exceeded. Extensive unit tests are added to validate these security improvements against various bypass techniques. No review comments were provided, so there is no additional feedback to address.
Note: Security Review did not run due to the size of the PR.
…ross shell wrapper parsing Addresses all review comments from @spencer426: - Peel leading shell env assignments with quoted values or `+=` using raw prefix matching (`FOO="bar"`, `FOO=''`, `FOO+=bar`) and accept quoted `NAME=VALUE` args on `env`, `sudo`, and `doas`. - Count all `o`/`O` option arguments in POSIX shell short-flag clusters (`bash -oc pipefail`, `bash -oo pipefail noglob -c`) and add `fish` (`-c`/`--command`/`-C`/`--init-command`) plus `.exe` normalization (`bash.exe`, `sh.exe`). - Restrict unquoted Windows path backslash preservation so POSIX backslash escapes after `\\` (`sh -e -c true\ a\\b\;\$\(whoami\)`) still unescape shell metacharacters. - Handle Bash locale-translated double quotes (`$"..."`) in both the wrapper tokenizer and `stripSingleShellWrapper`, and preserve exact character adjacency in `collectAstCommandSegments` instead of joining AST children with spaces. - Fix prefix-utility peeling: remove optional-arg GNU `env` signal flags from `ENV_FLAGS_WITH_VALUE`, parse short-flag clusters on `env`, `watch`, and `PREFIX_UTILITY_SPECS` (`timeout -fs KILL 5`, `sudo -Eu root`, `watch -xn 1`), add `xargs`, and decode GNU `env -S` escapes (`\_`, `\'`, `\"`, `\$`, `\\`, `\c`, `#`). - Fix Windows/PowerShell wrappers: join multi-token tails on `cmd.exe` and `pwsh`/`powershell`, handle Unicode smart quotes in both the tokenizer and `unwrapPowerShellCommandArg`, normalize `/` switches, handle implicit default `-Command` on `powershell`/`powershell.exe`, strip embedded whitespace in `-EncodedCommand` base64, and fail closed (`uninspectable: true`) when encoded payloads exceed 65,536 chars. - Handle POSIX clobber redirection `>|` in segment splitting and redirection stripping. - Remove unreachable duplicate `wrapperDepth` check inside `checkExtractedPayloads` in `PolicyEngine`. - Add unit and `PolicyEngine` regression tests covering all cases.
|
/gemini Review |
There was a problem hiding this comment.
Code Review
This pull request hardens the policy engine and shell utilities against wrapper bypasses and command injection. It introduces extractWrappedShellCommands to recursively inspect and extract inner shell command payloads wrapped by prefix utilities (such as env, nice, timeout, nohup, setsid, sudo, xargs) and shell invocations (such as sh, bash, cmd.exe, powershell, pwsh). Additionally, it implements recursion depth limits to fail closed when nesting is too deep, and adds comprehensive unit tests validating these security improvements. I have no feedback to provide as there are no review comments.
Summary
Hardens shell wrapper inspection in
detectCommandSubstitution,stripShellWrapper, andPolicyEngineso command substitutions and denied commands inside wrapped shell invocations are consistently detected and enforced across prefix utilities, shell flags, trailing tokens/operators/redirections, and Windows shell wrapper variants.Details
packages/core/src/utils/shell-utils.ts):extractWrappedShellCommands()using tree-sitter-bash AST decomposition (includingredirected_statementmid-command redirections) with a linear-time fallback segmenter when the WASM parser is unavailable or on Windows/PowerShell.$'...') wrapper tokenizer with redirection stripping and declarative prefix-utility peeling (envincluding-S/--split-string,nice,timeout,nohup,setsid,sudo,stdbuf,ionice,chrt,taskset,time,command,exec,builtin,watch,xargs, etc.).sh,bash,zsh,dash,ksh,ash,mksh,csh,tcsh) with arbitrary flags before or after-c,eval,cmd/cmd.exe(/c,/k,/rand pre-switches), andpowershell/pwsh(-c/-co..-command,-e/-ec/-enc..-encodedcommandUTF-16LE base64, and parameter prefixes).packages/core/src/utils/shell-utils.ts):detectCommandSubstitution()to recursively inspect all extracted wrapper payloads up toMAX_SHELL_WRAPPER_DEPTH = 5andMAX_WRAPPER_DETECTION_STATES = 64(failing closed when exceeded).stripSingleShellWrapper(),unwrapCmdCommandArg(), andunwrapPowerShellCommandArg()so single/double-quoted wrapper arguments with trailing operators, arguments, comments, redirections, post--cflags, ANSI-C quoting, or hidden substitutions are preserved rather than partially stripped, while maintaining existing sandbox-manager stripping behavior for benign argv-joined commands and PowerShell\"unescaping.packages/core/src/policy/policy-engine.ts):PolicyEngine.checkShellCommand()to recursively validate extracted wrapper payloads (per subcommand and on the full command for wrappers split across AST redirections) with bounded recursion depth (wrapperDepth), preservingDENYenforcement andALLOW -> ASK_USERdowngrades without upgrading unapproved outer wrappers or regressing known-safe wrapped commands such asbash -lc "ls -la".packages/core/src/utils/shell-utils.test.ts,packages/core/src/policy/shell-substitution.test.ts,packages/core/src/tools/shell.test.ts):cmd.exeswitches (including-enc), recursion caps, benign wrapped command preservation, policy enforcement (interactive & non-interactive), andShellToolInvocation.execute()defense-in-depth blocking.Related Issues
N/A
How to Validate
cd packages/core npx vitest run \ src/utils/shell-utils.test.ts \ src/tools/shell.test.ts \ src/policy/shell-substitution.test.ts \ src/policy/shell-safety.test.ts \ src/policy/shell-safety-regression.test.ts \ src/policy/shell-argument-expansion.test.ts \ src/policy/policy-engine.test.ts \ src/policy/policy-updater.test.ts \ src/services/sandboxManager.integration.test.ts@google/gemini-cli-coretest suite, typecheck, and lint:env sh -c 'echo $(id)',sh -e -c 'echo $(id)',sh -c 'echo $(id)' '') prompt (ASK_USER) in interactive mode and are denied (policy_violation) in non-interactive--approval-mode default.env sh -c 'echo ok') continue to execute normally when allowed by policy.Pre-Merge Checklist