Skip to content

fix(core): inspect shell wrapper variants for command substitution and policy checks - #30451

Merged
spencer426 merged 3 commits into
google-gemini:mainfrom
duvanka-prasad:fix/shell-wrapper-substitution-bypass
Nov 25, 2026
Merged

spencer426 merged 3 commits into
google-gemini:mainfrom
duvanka-prasad:fix/shell-wrapper-substitution-bypass

Conversation

@duvanka-prasad

Copy link
Copy Markdown
Contributor

Summary

Hardens shell wrapper inspection in detectCommandSubstitution, stripShellWrapper, and PolicyEngine so 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

  • Structured wrapper payload extraction (packages/core/src/utils/shell-utils.ts):
    • Added extractWrappedShellCommands() using tree-sitter-bash AST decomposition (including redirected_statement mid-command redirections) with a linear-time fallback segmenter when the WASM parser is unavailable or on Windows/PowerShell.
    • Added a POSIX/ANSI-C ($'...') wrapper tokenizer with redirection stripping and declarative prefix-utility peeling (env including -S/--split-string, nice, timeout, nohup, setsid, sudo, stdbuf, ionice, chrt, taskset, time, command, exec, builtin, watch, xargs, etc.).
    • Extracts inner payloads from POSIX shells (sh, bash, zsh, dash, ksh, ash, mksh, csh, tcsh) with arbitrary flags before or after -c, eval, cmd/cmd.exe (/c, /k, /r and pre-switches), and powershell/pwsh (-c/-co..-command, -e/-ec/-enc..-encodedcommand UTF-16LE base64, and parameter prefixes).
  • Recursive substitution detection & safer wrapper stripping (packages/core/src/utils/shell-utils.ts):
    • Updated detectCommandSubstitution() to recursively inspect all extracted wrapper payloads up to MAX_SHELL_WRAPPER_DEPTH = 5 and MAX_WRAPPER_DETECTION_STATES = 64 (failing closed when exceeded).
    • Hardened stripSingleShellWrapper(), unwrapCmdCommandArg(), and unwrapPowerShellCommandArg() so single/double-quoted wrapper arguments with trailing operators, arguments, comments, redirections, post--c flags, 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.
  • Recursive policy enforcement (packages/core/src/policy/policy-engine.ts):
    • Updated 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), preserving DENY enforcement and ALLOW -> ASK_USER downgrades without upgrading unapproved outer wrappers or regressing known-safe wrapped commands such as bash -lc "ls -la".
  • Tests (packages/core/src/utils/shell-utils.test.ts, packages/core/src/policy/shell-substitution.test.ts, packages/core/src/tools/shell.test.ts):
    • Added regression tests covering prefix utilities, shell flags, ANSI-C quoting, trailing arguments/operators/redirections, Windows PowerShell/cmd.exe switches (including -enc), recursion caps, benign wrapped command preservation, policy enforcement (interactive & non-interactive), and ShellToolInvocation.execute() defense-in-depth blocking.

Related Issues

N/A

How to Validate

  1. Run unit, policy, and sandbox test suites:
    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
  2. Run full @google/gemini-cli-core test suite, typecheck, and lint:
    npm run typecheck
    cd packages/core && npx vitest run
  3. Verify wrapper handling in bundled CLI with a prefix-allow policy for wrapper commands:
    • Wrapped commands containing command substitution (e.g., 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.
    • Benign wrapped commands without substitution or denied inner commands (e.g., env sh -c 'echo ok') continue to execute normally when allowed by policy.

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

…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.
@duvanka-prasad
duvanka-prasad requested review from a team as code owners November 24, 2026 18:46
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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

  • Structured Shell Wrapper Inspection: Introduced extractWrappedShellCommands to recursively decompose shell wrapper payloads using tree-sitter-bash AST or a linear-time fallback, supporting POSIX shells, Windows cmd.exe, and PowerShell variants.
  • Recursive Policy Enforcement: Updated PolicyEngine to recursively validate extracted wrapper payloads with a depth limit, ensuring consistent DENY/ASK_USER enforcement across nested shell invocations.
  • Hardened Substitution Detection: Refactored detectCommandSubstitution and stripSingleShellWrapper to safely handle complex shell syntax, including ANSI-C quoting, trailing redirections, and prefix utilities, while failing closed on recursion limits.
  • Comprehensive Regression Testing: Added extensive test suites covering Windows/POSIX wrapper bypasses, recursive policy enforcement, and edge cases like mid-command redirections and encoded PowerShell commands.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@github-actions github-actions Bot added the size/xl An extra large PR label Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

📊 PR Size: size/XL

  • Lines changed: 2547
  • Additions: +2393
  • Deletions: -154
  • Files changed: 5

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@gemini-cli gemini-cli Bot added the status/need-issue Pull requests that need to have an associated issue. label Nov 24, 2026
…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`.
@duvanka-prasad

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
Comment thread packages/core/src/utils/shell-utils.ts Resolved
…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.
@duvanka-prasad

Copy link
Copy Markdown
Contributor Author

/gemini Review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@spencer426 spencer426 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@spencer426
spencer426 enabled auto-merge November 25, 2026 16:28
@spencer426
spencer426 added this pull request to the merge queue Nov 25, 2026
Merged via the queue into google-gemini:main with commit 3e349a2 Nov 25, 2026
33 checks passed
spencer426 pushed a commit that referenced this pull request Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/xl An extra large PR status/need-issue Pull requests that need to have an associated issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants