Skip to content

fix(shell,skills): close the allowlist holes that let a read run code - #3593

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:fix/shell-allowlist-bypass
Sep 18, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:fix/shell-allowlist-bypass

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

A skill or a prompt-injected tool argument could run arbitrary commands on Windows through paths the shell tool reported as read-only, and could print the user's GitHub token without a confirmation prompt. Both now refuse. Legitimate reads are unaffected — they take a reviewed flag allowlist instead of whatever the underlying tool would have accepted.

The argv rewrite that removes cmd.exe from this path entirely is a larger change and lands separately. Its contract is pinned here as four strict-xfail tests, so implementing it forces the marker off rather than leaving the spec unenforced.

Test plan

  • python -m pytest tests/unit/test_shell_guardrails.py tests/unit/test_skill_binary_grants.py — 365 passed, 4 xfailed
  • Each refusal is asserted on the exact probe string, not on "the validator was called"
  • Negative direction covered: ordinary reads (gh auth status, gh issue list, dir, powershell -Command "Get-Process") still pass
  • python util/lint.py --black --isort clean

The Windows shell allowlist called commands read-only that were not.
`dir . &where cmd` ran a second command because the operator check only
saw an ampersand followed by whitespace; `powershell -e` slipped a filter
that matched only the full `-EncodedCommand` spelling; and .NET calls,
alias invocations and `>` redirection inside `-Command` all passed as
cmdlet reads. Allowlisted binaries were write primitives too:
`git log --output=` and `wmic /output:` put near-arbitrary content at a
near-arbitrary path.

Separately, a skill holding `shell:execute:gh` could run
`gh auth status --show-token`, which sits in the tier that skips
confirmation, and print the user's GitHub token into tool output a
`network:read` skill could then send anywhere.

Reads now take a fixed flag allowlist, so a flag nobody reviewed is
refused rather than passed through to the tool's own parser.

The argv rewrite that removes cmd.exe from this path entirely is a
larger change and lands separately; its contract is pinned here as
strict xfail so implementing it forces the marker off.
@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Request changes

This PR closes several genuine holes — gh auth status --show-token, unspaced & chaining, PowerShell parameter-prefix abbreviations, and git/wmic output flags — and the tests read like the probes they came from. One hole is only half closed, and two ordinary reads become collateral.

The PowerShell fix stops one token short. Put almost any other PowerShell switch in front of the command text and the whole new script-body check goes back to sleep: powershell -NoLogo calc.exe is still reported read-only, and PowerShell treats a bare string after switches as the command, so on Windows it runs. The body has to be located after all leading switches, and a switch nobody reviewed should be refused rather than skipped over.

The skill doc now promises more than the code does. It tells the model that reads take a fixed flag allowlist, but that only holds for repo, release, run, search and auth. gh issue, gh pr and gh label — the ones triage actually uses — still pass an unlisted flag straight through, with no prompt. Extend the allowlist to them or soften the sentence.

Two reads that used to work now fail with the wrong reason. Listing untracked files (git ls-files -o) is refused as "writes to a file", and any PowerShell read naming a relative path is refused as dot-sourcing. Both are one-line regex/scope fixes.

Four tests became strict expected-failures with a reason saying argv execution isn't implemented — but that path looks present in the shell tool already. Worth saying, per test, why it actually fails today; an expected-failure marker on a security contract hides a regression rather than pinning a spec.

Real-world evidence

No evidence-bundle.md was produced for this PR, and the test-plan checkboxes are unticked, so nothing here shows the suite result the description cites. I verified the finding above myself, by importing ShellToolsMixin and calling the real validator on probe strings (this runner has no pytest or GAIA dependencies installed, so I could not run the PR's test files):

ALLOWED | powershell -NoLogo calc.exe
ALLOWED | powershell -com "calc.exe"
ALLOWED | powershell -mta calc.exe
REFUSED | powershell -Command "calc.exe"     <- the case the PR fixes
REFUSED | git ls-files -o                    <- "writes to a file"
REFUSED | powershell -Command "Get-Content ./a.txt"   <- "dot-sourcing"
REFUSED | powershell -Command "Get-ChildItem . -Recurse"

and the same way against the gh policy table:

allow  | gh issue list --unreviewed-flag
allow  | gh pr view 1 --made-up
allow  | gh label list --made-up
refuse | gh repo view amd/gaia --unreviewed-flag
refuse | gh auth status -t
refuse | gh run view 1 --watch

The gh auth status -t and --watch refusals land as intended. The verdict rests on this plus static review; nothing exercised the tool through an agent on Windows, which is where the PowerShell path actually runs.

🔍 Technical details

🔴 Critical — a leading PowerShell switch defeats the new body check (src/gaia/agents/tools/shell_tools.py:744)

ps_cmd is only taken from the token after an exact -command/-c. Anything else falls to the else branch at line 751, which joins cmd_parts[1:] — so the flag token itself becomes the head of the body. Every new command-position pattern in _PS_BODY_ESCAPES is anchored with (?:^|\|), so once -nologo occupies position 0 they cannot match, and re.findall(r"[a-z]+-[a-z]+", ps_cmd) finds no cmdlet in -nologo calc.exe either, leaving the whole PowerShell filter a no-op. Confirmed by running the validator: powershell -NoLogo calc.exe, powershell -mta calc.exe, powershell -com "calc.exe" all return no error. -com/-comm matter because _is_blocked_ps_flag correctly leaves command out of PREFIX_BLOCKED_PS_PARAMS, so the prefix reasoning the PR adds for -File/-EncodedCommand never gets applied to the switch that selects the body.

No suggestion block here on purpose — a half-right patch to a security guard is worse than none. The shape that closes it: walk cmd_parts[1:] consuming leading --prefixed tokens, refuse any switch not in a reviewed switch table (with an explicit value-consuming set), and take everything from the first non-switch token as ps_cmd. That also makes -Command prefix-tolerant, matching what _is_blocked_ps_flag already assumes about PowerShell's parser.

🟡 The read-flag allowlist covers five subcommands; the doc says all reads (src/gaia/skills/binaries.py:409, hub/skills/github-triage/SKILL.md:77)

allowed_flags is only set in the not confirm_actions branch of _gh, so issue, pr and label — which carry write actions — keep the pass-through denylist. gh issue list --unreviewed-flag classifies allow, which skill_grant_covers_call exempts from confirmation. SKILL.md's "Reads take a fixed flag allowlist, so a gh flag not listed here is refused rather than passed through" is therefore wrong for the three subcommands the skill's own procedure uses, and "not listed here" points at a list of refused flags, not the allowed set. Either apply the allowlist to the read actions of mixed subcommands too, or scope the sentence to the subcommands it holds for.

🟡 git ls-files -o is refused as an output flag (src/gaia/agents/tools/shell_tools.py:698)

-o on ls-files is --others (list untracked files), a read. No allowlisted git subcommand uses short -o for output — git diff --output= is the real write spelling and the long-form branch already catches it, plus every abbreviation of it.

            # A read-only subcommand still writes a caller-chosen path when it
            # is handed an output flag, and the subcommand check never sees it.
            for part in cmd_parts[1:]:
                # `git ls-files -o` is --others (untracked), not an output flag.
                if git_subcmd == "ls-files" and part.lower().startswith("-o"):
                    continue
                if _is_file_write_flag(part):

🟡 The dot-sourcing pattern refuses relative-path reads (src/gaia/agents/tools/shell_tools.py:234)

(?:^|\s)\.(?=[\s\\/'\"]) fires on any . followed by a space or slash, so Get-Content ./a.txt and Get-ChildItem . -Recurse are both reported as dot-sourcing. The comment above the block says a path operand stays a read, and the tests only pin the absolute-path spellings, so the gap is invisible in CI. Requiring the separator that dot-sourcing actually needs keeps every existing probe refused:

    (re.compile(r"(?:^|\s)\.\s+(?=[.\\/~]|[a-z]:)"), "dot-sourcing (. script.ps1)"),

🟡 Four strict-xfails on a security contract (tests/unit/test_skill_binary_grants.py:1377)

The reason reads "argv execution for granted binaries is not implemented yet", but shell_tools.py:1061 computes lone_granted_segment and drops shell=True for exactly that case. At the same time the helper switched from the registered tool (get_tool_metadata) to a decorator spy that captures the undecorated function, so what these tests exercise changed too. If they fail for a different reason — a validation refusal, or the @tool kwarg change in #3252 — strict=True pins the wrong spec and will keep passing while the real contract rots. Worth one line per test saying what currently fails, or reverting the helper change and letting them fail loudly.

🟢 gh run list --status failure is now refused

Collateral of the new allowlist: --status is a plain read filter on gh run list. Adding it (and --visibility for gh repo list) to _GH_READ_ALLOWED_FLAGS costs nothing.

Strengths

  • Each test asserts on the exact probe string that used to be answered "allowed", so the file documents the attack, not just the outcome — TestQuotedOperatorsAreData pinning the skill's own gh api "…&per_page=50" call verbatim is a good regression anchor for the widened & rule.
  • _outside_double_quotes models cmd.exe's quote toggling correctly (split on ", keep even spans) and deliberately leaves single quotes scanned, which is the conservative direction — the widened operator regex would otherwise have broken every URL query string.
  • Routing skill_grant_covers_call through the same _operator_check_text as the refusal path removes a real class of divergence between the "refuse" and "skip the prompt" tiers.

They are module-level constants handed to a helper as default arguments,
so a mutable dict there is a shared object any caller could rewrite for
every later policy lookup. MappingProxyType makes that impossible rather
than merely unlikely.
@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

🔴 The leading-switch bypass from the first review is still open. _is_blocked_ps_flag only refuses switches that are explicitly named or that prefix one of four blocked parameter names. Any other valid PowerShell.exe switch — -NoLogo, -Mta, -Sta, -InputFormat, -ConfigurationName, -WindowSize — lands in the else branch at line 751, becomes the head of ps_cmd, and none of the _PS_BODY_ESCAPES anchored at (?:^|\|) can match because a dash-prefixed token is in position 0. re.findall(r"[a-z]+-[a-z]+", "-nologo calc.exe") finds no cmdlet, so the command falls through as allowed.

The first review described the shape needed: walk cmd_parts[1:] consuming leading --prefixed tokens and refuse any switch not in an explicit reviewed table, then take the first non-switch token onwards as the body. The current approach (block a list of known-bad flags) leaves every unlisted switch as a silent bypass.

🔍 Technical details

shell_tools.py:744-751 — the ps_cmd extraction is unchanged from the first review:

for i, part in enumerate(cmd_parts):
    if part.lower() in ("-command", "-c"):
        ps_cmd = " ".join(cmd_parts[i + 1:]).lower()
        break
if not ps_cmd:
    ps_cmd = " ".join(cmd_parts[1:]).lower()  # flag becomes head of body

Reproducing what the first review showed:

Command Result
powershell -NoLogo calc.exe ALLOWED — -nolog not in BLOCKED_PS_FLAGS, no body escape fires
powershell -Mta calc.exe ALLOWED — same path
powershell -com calc.exe ALLOWED — -com not a prefix of any PREFIX_BLOCKED_PS_PARAMS
powershell -Command calc.exe REFUSED ✓ — calc.exe appears in ps_cmd after skipping -Command

The gap: PREFIX_BLOCKED_PS_PARAMS covers encodedcommand, encodedarguments, file, executionpolicy. PowerShell.exe has roughly 15 other switches (-NoLogo, -NoExit, -Mta, -Sta, -NonInteractive, -InputFormat, -OutputFormat, -WindowStyle, -ConfigurationName, -PSConsoleFile, -Version) none of which are prefixes of those four names.

The fix the first review outlined: build an explicit allowlist of the PowerShell.exe switches that are safe to pass before the body (e.g. -NoLogo, -NoExit), refuse any --prefixed token not in that list before extracting ps_cmd, and set ps_cmd from the first non-switch token onwards.

Ovtcharov and others added 4 commits September 11, 2026 16:24
The agent's Windows tips told it to run a Get-Process command with an inline
calculated property, which the hardened shell allowlist refuses, so asking for
top memory users failed instead of answering. It now asks for the raw WS column
and leaves the division to the model.
# Conflicts:
#	src/gaia/agents/tools/shell_tools.py
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

Security hardening across four layers — the shell operator filter, PowerShell body inspection, git/wmic file-write detection, and the gh binary policy. The logic is careful and internally consistent; the test suite directly covers each new path. No correctness bugs, security bypasses, or architecture violations found.

A few observations that don't block merge:

🟢 _outside_double_quotes doesn't account for \" inside a quoted span (e.g. grep "he said \"hello\" & bye" file). An even-quote-count string with escaped quotes produces the wrong split, and the & inside may pass undetected. In practice this needs a carefully crafted command to matter, and it's safe-by-default (false positives are fine; false negatives are the concern here). Worth a follow-up note in the docstring.

🟢 The two new standalone test functions at the top of test_shell_guardrails.py reference ShellToolsMixin before the file-level import of it. This works at runtime (function bodies resolve names at call time, after the full module loads), but static analysers will flag it and the ordering surprises readers.

🔍 Technical details

_outside_double_quotes escape-quote edge case:

# shell_tools.py
def _outside_double_quotes(text: str) -> str:
    if text.count('"') % 2:
        return text
    return " ".join(text.split('"')[::2])

grep "he said \"hello\" & bye" file.txt has four " characters (even count), but split('"') treats each verbatim " as a delimiter, so the & bye segment — which is inside the outer double quotes — gets classified as outside-quote and scanned. Result: & is correctly caught here. The problematic direction is the reverse: a \" that closes an outer quote earlier than expected can exclude an operator from scanning. Extremely edge-case and any exploit requires a very specific quoting shape; documenting the known limitation in the docstring is enough.

Import ordering in test_shell_guardrails.py (lines ~563-595 in the diff):

# New tests at top of file — ShellToolsMixin used here
def test_powershell_switches_cannot_hide_executable_body(command):
    assert ShellToolsMixin()._validate_shell_command(command)[0] is not None

# ... more tests ...

# Import appears later in the file (pre-existing position)
from gaia.agents.tools.shell_tools import (
    ShellToolsMixin,
    ...
)

Works at runtime; isort would reorder this automatically. Low priority.

_captured_shell_tool refactor: cleaner than the old get_tool_metadata global lookup — captures the bound function directly during registration and avoids cross-test contamination. The spy wrapper correctly passes through to original(**kwargs)(fn) so the tool is also registered globally as before.

Agent prompt alignment (agent.py): the old @{N='Memory(MB)';E={[math]::Round($_.WS/1MB,1)}} hash-table syntax contains $ and would be refused by the new _powershell_body_escape check. The simplified command (Select-Object -First 15 Name, Id, WS with "WS is bytes" note) is consistent with the updated filter. ✓

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

This is well-targeted security hardening. Each bypass (unspaced &, PowerShell parameter abbreviations, -Command body escapes — $, ::, .Method(), executable paths — file-write flags on git/wmic, gh auth status --show-token) is fixed with a corresponding test that would have caught the original hole. The _outside_double_quotes approach correctly avoids false positives on URL query strings in double-quoted arguments.

One thing to be aware of going forward:

🟢 PowerShell body & applies to string arguments too. After shlex.split, the quotes around a string like 'https://host?a=1&b=2' are stripped, so the naked & triggers the call-operator check even though it is data. This is intentionally conservative, and the agent-prompt update (dropping @{N='...';E={...}}) shows the author accounted for it — but a one-line comment on the & entry in _PS_BODY_ESCAPES would help the next reader understand why URL-containing cmdlets are refused.

🟢 Test import ordering. The two new test_powershell_switches_* functions at the top of test_shell_guardrails.py reference ShellToolsMixin before the import block ~600 lines below. Python resolves the name at call time so the tests run correctly, but a from gaia.agents.tools.shell_tools import ShellToolsMixin at the top would make the dependency visible.

Both are nits; neither blocks the fix.

🔍 Technical details

& in PS body (shell_tools.py:96-113): _PS_BODY_ESCAPES is scanned against ps_cmd after shlex.split strips outer quotes. powershell -Command "Invoke-WebRequest 'https://host?a=1&b=2'" → shlex gives ps_cmd = "invoke-webrequest 'https://host?a=1&b=2'" (single quotes preserved by shlex but the inner & is still bare). Pattern re.compile(r"&") fires. The fix for real & invocations is correct; the single-quotes edge case just needs a comment noting it is accepted collateral.

Import ordering (test_shell_guardrails.py:70-88 vs test_shell_guardrails.py:~605): The new parametrized functions appear before the from gaia.agents.tools.shell_tools import (ShellToolsMixin, …) block. Functionally fine — Python's module-level execution runs the import before pytest calls the test bodies. Suggest hoisting a minimal from gaia.agents.tools.shell_tools import ShellToolsMixin to the top of the file alongside import pytest.

_GH_READ_ALLOWED_FLAGS completeness: The new allowlist for pure-read gh subcommands covers --log, --log-failed, --exit-status, --verbose, --comments, --source, --fork, --no-archived, --archived, --paginate plus whatever _GH_COMMON_VALUE_FLAGS and policy.bare_flags carry. The test_read_filters_remain_allowed tests pin the two flags added this PR; the rest of the pre-existing set is unchanged.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve 🟢

Security hardening to the shell guardrails that closes several real bypass paths and is backed by thorough tests. No bugs found across the correctness, security, and architecture checks.

What the PR fixes:

  • Unspaced & in cmd.exe was not treated as a command separator (dir .&whoami passed)
  • PowerShell -encodedcommand prefix-matching gap: -e, -ec, -enc were not blocked
  • PowerShell -Command body now checked for $, ::, .Method(), .exe/.ps1 paths, and redirections — previously a body with none of these was passed straight to the cmdlet allowlist, which is a no-op if the body contained no verb-noun pattern (e.g. calc.exe)
  • git log --output= / wmic /output: were not flagged as file-write operations
  • gh auth status -t / --show-token printed the GitHub credential silently
  • --watch blocked the agent waiting for a run to finish
  • URL query strings (gh api "…?a=1&b=2") were incorrectly refused

Notable design decisions (worth noting for reviewers):

  • _operator_check_text strips the PowerShell body only for exact -command/-c; prefix variants like -comm leave the body in the scanned text. This is conservative-correct: if the body contains an operator (&, >, etc.) it gets caught. If it doesn't, validate_invocation still runs the full _PS_BODY_ESCAPES check.
  • The git ls-files -o carve-out (-o means --others, not --output) is correctly scoped to that subcommand only; -oC:/path still fails.
  • The new _GH_READ_ALLOWED_FLAGS allowlist is additive with value_flags / flag_values, so previously-working flags like --json and -t/--template continue to work.

Chat agent prompt change: The Windows process-monitoring command was simplified from the @{N='Memory(MB)';E={[math]::Round($_.WS/1MB,1)}} form (which uses $_ and :: — now blocked) to plain WS bytes. This is a forced consequence of the security fix, not a regression; the old command would now be refused entirely. The new command is pinned in test_plain_read_only_cmdlets_still_run.

🔍 Technical details

The _is_blocked_ps_flag prefix logic direction is correct: param.startswith(name) checks that a blocked parameter name starts with the user's input, so -e blocks encodedcommand and encodedarguments. No false positives observed in the test matrix.

_outside_double_quotes uses text.split('"')[::2] — clean for the URL-query use case; single-quoted shell arguments still get scanned whole (intentionally conservative for cmd.exe, which has no single-quote protection).

The new per-segment pipeline cmdlet check (ps_cmd.split("|")) adds a check that every pipe segment starts with a recognised verb-noun form. This correctly catches bodies like "calc.exe" (no hyphen → head is None → refused) and complements the existing re.findall check below it.

deny_flags / denied_flag_reasons in _gh() now flow as keyword-only parameters with the shared read defaults, keeping the auth-specific denylist narrowly scoped to the auth entry only.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 18, 2026
Merged via the queue into amd:main with commit 10d62d1 Sep 18, 2026
35 checks passed
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Sep 19, 2026
Main's allowlist fixes (amd#3593) keep refusing under this branch's ask-first
model: each guard it added is tagged as an outright refusal, so none of
them turns into a yes/no prompt. The /agents switch (amd#3987) and the
conversation-clear test (amd#3650) now use the full-access names, and a
saved-default notice is shown once rather than again on every switch.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants