From 31788681f4c47e9dca38da2f99adb44027d98697 Mon Sep 17 00:00:00 2001 From: Nathan Oliver Date: Sat, 8 Aug 2026 08:21:49 +0800 Subject: [PATCH 1/3] fix(hooks): close the PowerShell destructive-command gate bypass CLAUDE_CODE_USE_POWERSHELL_TOOL=1 makes PowerShell a second arbitrary-command shell, but every destructive-command gate was scoped to Bash alone. Identical destructive intent through the two tools produced opposite outcomes: the Bash recursive-delete form was denied, while the PowerShell equivalent passed through with exit 0 and no gate at all. The gate failed at two independent levels, so widening either alone was insufficient: - gateguard-fact-force.js: TOOL_MAP had no `powershell` key, and `if (toolName === 'Bash')` was the only branch reaching isDestructiveBash(). Unrecognised tool names fell through to the bare allow at the end of run(). - governance-capture.js: SECURITY_RELEVANT_TOOLS held only 'Bash', and a second Bash-only branch guarded APPROVAL_COMMANDS, so a bypassing command was also invisible to the audit trail. PowerShell delete verbs share no syntax with POSIX rm, so a dedicated isDestructivePowerShell() is required rather than reuse: the PowerShell recursive-delete form reaches isDestructiveRm() as tokens whose -Force fails its case-sensitive /f/ test. PowerShell also accepts any unambiguous parameter prefix, so -Recurse, -Rec and -r must all match. Detection reuses the file's existing quote-aware segmenter (quoteAwareSegments) rather than a naive split, which is what closes the quoted-separator evasion class described in GHSA-4v57-ph3x-gf55; the same choice resolves the `&` call operator and quoted command words for free. Covered in addition: pipelines that carry -Recurse on an upstream enumerator, backtick obfuscation, nested powershell/pwsh/cmd reinvocation including base64 -EncodedCommand, .NET [System.IO.Directory]::Delete, and splatted (opaque) parameters. -Force is gated even without -Recurse. This deliberately departs from the rm -f analogy: PowerShell's Remove-Item -Force on a directory removes the tree, and a static string cannot distinguish a file target from a directory target. isDestructiveBash() still runs for PowerShell input so the shell-agnostic phrases (force push, hard reset, DROP TABLE, dd) stay covered. The PowerShell detector runs only for the PowerShell tool, so Bash gating behaviour is unchanged - verified by differential testing of both versions across 15 representative Bash commands, 0 differences. The routine first-command gate intentionally shares ROUTINE_BASH_SESSION_KEY across both tools, so an operator sees one fact-forcing prompt per session rather than two; its message is now tool-neutral. Tests: 164 passed / 0 failed in gateguard-fact-force (20 new PowerShell cases, 144 pre-existing unaffected), 30/0 governance-capture, 13/0 posttooluse-dispatcher. --- scripts/hooks/gateguard-fact-force.js | 217 +++++++++++++++++++++- scripts/hooks/governance-capture.js | 22 ++- tests/hooks/gateguard-fact-force.test.js | 227 +++++++++++++++++++++++ 3 files changed, 458 insertions(+), 8 deletions(-) diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.js index 3f7f9ed809c..8fdf6298d5b 100644 --- a/scripts/hooks/gateguard-fact-force.js +++ b/scripts/hooks/gateguard-fact-force.js @@ -714,6 +714,209 @@ function isDestructiveBash(command) { return false; } +// --- PowerShell destructive detection --- +// +// When CLAUDE_CODE_USE_POWERSHELL_TOOL=1 the PowerShell tool can run arbitrary +// commands, but its delete verbs share no syntax with POSIX `rm`, so the +// tokenizer above cannot see them: `rm -Recurse -Force x` reaches +// `isDestructiveRm` as tokens whose `-Force` fails its case-sensitive /f/ test. +// These helpers close that gap. They run ONLY for the PowerShell tool, so Bash +// gating behaviour is unchanged. + +// Remove-Item plus its built-in aliases, and Remove-ItemProperty (a distinct +// cmdlet that deletes registry values rather than files, gated on the same terms). +const PS_DELETE_VERBS = new Set([ + 'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase', +]); + +// Shells reachable from PowerShell that can carry a destructive command in an +// argument, the PowerShell analogue of the `sh -c` / `bash -c` wrapper class +// that isDestructiveQuoteAware already unwraps for Bash. +const PS_NESTED_SHELLS = new Set(['powershell', 'pwsh', 'cmd']); + +// PowerShell has unrestricted .NET access, so the delete verbs are not the only +// route: [System.IO.Directory]::Delete($p, $true) removes a tree. +const PS_DOTNET_DELETE = /\[\s*(?:system\.)?io\.(?:directory|file)\s*\]\s*::\s*delete\s*\(/i; + +// cmd.exe recursive removal reached via `cmd /c`: rd /s /q, rmdir /s, del /s. +const CMD_RECURSIVE_DELETE = /(?:^|[\s;|&(])(?:rd|rmdir|del|erase)\s+[^;|&]*[/-]s\b/i; + +/** + * PowerShell accepts any unambiguous prefix of a parameter name (`-Recurse` + * may be written `-Recurs`, `-Rec`, or `-r`), so parameters must be matched by + * prefix rather than exact spelling. A trailing `:value` suffix + * (`-Confirm:$false`) is stripped before comparison. + * + * @param {string} token - a single argument token, e.g. `-Rec` + * @param {string} fullName - the lowercase full parameter name, e.g. `recurse` + * @returns {boolean} + */ +function isPsParamPrefixOf(token, fullName) { + const name = token.replace(/^-+/, '').split(':')[0].toLowerCase(); + return name.length > 0 && fullName.startsWith(name); +} + +/** + * Detect destructive PowerShell commands. + * + * Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not + * `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any + * delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as + * its `rm -f notes.txt` equivalent does. + * + * @param {string} command + * @returns {boolean} + */ +function isDestructivePowerShell(command, depth = 0) { + if (depth > 4) return false; + + // PowerShell's backtick escapes a single character. `n / `r are newlines + // (statement separators); before any other character the backtick is a no-op + // that obfuscation abuses, e.g. Rem`ove-Item. Normalize both away first. + const raw = String(command || '') + .replace(/`n/gi, '\n') + .replace(/`r/gi, '\n') + .replace(/`/g, ''); + + if (PS_DOTNET_DELETE.test(raw)) return true; + if (CMD_RECURSIVE_DELETE.test(raw)) return true; + + // Statement-level pass. `Get-ChildItem -Recurse | Remove-Item` splits its + // evidence across a pipeline: -Recurse sits on the enumerating command, not + // on the delete verb. This is the PowerShell analogue of `find -exec rm`, + // which isDestructiveFindExec already covers for Bash. + for (const statement of splitPsStatements(raw)) { + const words = statement.map(word => word.toLowerCase()); + const hasDeleteVerb = words.some(word => PS_DELETE_VERBS.has(commandBasename(word))); + if (!hasDeleteVerb) continue; + if (words.some(word => word.startsWith('-') && isPsParamPrefixOf(word, 'recurse'))) { + return true; + } + } + + // Segment-level pass. quoteAwareSegments strips quotes and splits on + // ; | & and newlines, so it also resolves `& 'Remove-Item' ...` (the call + // operator) and quoted command words without extra handling here. + for (const tokens of quoteAwareSegments(raw)) { + if (tokens.length === 0) continue; + + const verb = commandBasename(tokens[0]); + const rest = tokens.slice(1); + + if (PS_NESTED_SHELLS.has(verb)) { + if (isDestructiveNestedPsShell(rest, depth)) return true; + continue; + } + + if (!PS_DELETE_VERBS.has(verb)) continue; + + for (const token of rest) { + // Splatted parameters (`Remove-Item @params`) are opaque to static + // inspection, so a splatted delete is gated rather than assumed safe. + if (token.startsWith('@')) return true; + if (!token.startsWith('-')) continue; + // -Force is gated as well as -Recurse: unlike `rm -f`, PowerShell's + // `Remove-Item -Force ` removes the tree. + if (isPsParamPrefixOf(token, 'recurse') || isPsParamPrefixOf(token, 'force')) { + return true; + } + } + } + + return false; +} + +/** + * Unwrap a nested shell invocation (`powershell -Command ...`, `pwsh -c ...`, + * `cmd /c ...`, and the base64 `-EncodedCommand` form) and re-scan its payload. + * + * @param {string[]} rest - tokens after the shell name + * @param {number} depth - recursion guard, shared with isDestructivePowerShell + * @returns {boolean} + */ +function isDestructiveNestedPsShell(rest, depth) { + for (let i = 0; i < rest.length; i += 1) { + const token = rest[i]; + const next = rest[i + 1]; + if (!next) continue; + + if (token.startsWith('-') && isPsParamPrefixOf(token, 'encodedcommand')) { + try { + // PowerShell encodes -EncodedCommand payloads as UTF-16LE base64. + const decoded = Buffer.from(next, 'base64').toString('utf16le'); + if (decoded && isDestructivePowerShell(decoded, depth + 1)) return true; + } catch (_) { + /* not valid base64; fall through */ + } + continue; + } + + // `-Command`, `-c`, and cmd.exe's `/c` / `/k`. + const isCommandFlag = + (token.startsWith('-') && isPsParamPrefixOf(token, 'command')) || + token === '/c' || + token === '/C' || + token === '/k' || + token === '/K'; + if (isCommandFlag && isDestructivePowerShell(rest.slice(i + 1).join(' '), depth + 1)) { + return true; + } + } + return false; +} + +/** + * Quote-aware split into statements on `;` and newlines only, keeping pipelines + * intact so recursion flags on an upstream command stay visible to the delete + * verb downstream. Each statement is returned as a list of words. + * + * @param {string} input + * @returns {string[][]} + */ +function splitPsStatements(input) { + const statements = []; + let words = []; + let current = ''; + let quote = null; + + const flushWord = () => { + if (current) words.push(current); + current = ''; + }; + const flushStatement = () => { + flushWord(); + if (words.length) statements.push(words); + words = []; + }; + + for (const ch of String(input || '')) { + if (quote) { + if (ch === quote) quote = null; + else current += ch; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (ch === ';' || ch === '\n' || ch === '\r') { + flushStatement(); + continue; + } + if (ch === '|') { + flushWord(); + continue; + } + if (/\s/.test(ch)) { + flushWord(); + continue; + } + current += ch; + } + flushStatement(); + return statements; +} + // --- State management (per-session, atomic writes, bounded) --- function normalizeEnvValue(value) { @@ -1117,7 +1320,7 @@ function routineBashMsg() { return [ '[Fact-Forcing Gate]', '', - 'Before the first Bash command this session, present these facts:', + 'Before the first shell command this session, present these facts:', '', '1. The current user request in one sentence', '2. What this specific command verifies or produces', @@ -1185,7 +1388,7 @@ function run(rawInput) { const rawToolName = data.tool_name || ''; const toolInput = data.tool_input || {}; // Normalize: case-insensitive matching via lookup map - const TOOL_MAP = { edit: 'Edit', write: 'Write', multiedit: 'MultiEdit', bash: 'Bash' }; + const TOOL_MAP = { edit: 'Edit', write: 'Write', multiedit: 'MultiEdit', bash: 'Bash', powershell: 'PowerShell' }; const toolName = TOOL_MAP[rawToolName.toLowerCase()] || rawToolName; const inSubagent = isSubagentInvocation(data); @@ -1236,13 +1439,19 @@ function run(rawInput) { return rawInput; // allow } - if (toolName === 'Bash') { + // PowerShell shares this branch: `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` makes it a + // second arbitrary-command shell, and a gate that names only `Bash` is a hole + // rather than a policy. Both tools carry the command in `tool_input.command`. + if (toolName === 'Bash' || toolName === 'PowerShell') { const command = toolInput.command || ''; if (isReadOnlyGitIntrospection(command)) { return rawInput; } - if (isDestructiveBash(command)) { + // `isDestructiveBash` still runs for PowerShell: `git push --force`, + // `git reset --hard`, `DROP TABLE` and `dd if=` are shell-agnostic phrases. + // The PowerShell-only detector is additive and never relaxes Bash gating. + if (isDestructiveBash(command) || (toolName === 'PowerShell' && isDestructivePowerShell(command))) { // Gate destructive commands on first attempt; allow retry after facts presented const key = '__destructive__' + crypto.createHash('sha256').update(command).digest('hex').slice(0, 16); if (!isChecked(key)) { diff --git a/scripts/hooks/governance-capture.js b/scripts/hooks/governance-capture.js index b38187c2771..1a5cf99f622 100644 --- a/scripts/hooks/governance-capture.js +++ b/scripts/hooks/governance-capture.js @@ -34,15 +34,23 @@ const SECRET_PATTERNS = [ // Tool names that represent security-relevant operations const SECURITY_RELEVANT_TOOLS = new Set([ 'Bash', // Could execute arbitrary commands + 'PowerShell', // Same, once CLAUDE_CODE_USE_POWERSHELL_TOOL=1 makes it a live shell ]); -// Commands that require governance approval +// Commands that require governance approval. +// The git/SQL/dd entries are shell-agnostic and match under either shell; the +// PowerShell entries cover delete verbs that share no syntax with POSIX `rm`. const APPROVAL_COMMANDS = [ /git\s+push\s+.*--force/, /git\s+reset\s+--hard/, /rm\s+-rf?\s/, /DROP\s+(?:TABLE|DATABASE)/i, /DELETE\s+FROM\s+\w+\s*(?:;|$)/i, + // PowerShell Remove-Item and its aliases with -Recurse. PowerShell accepts any + // unambiguous parameter prefix, so -Recurse, -Rec and -r must all match. + /(?:^|[\s;|(])(?:Remove-Item|Remove-ItemProperty|ri|rmdir|rd|del|erase)\b[^;|]*\s-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b/i, + /(?:^|[\s;|(])Clear-(?:Content|Disk)\b/i, + /(?:^|[\s;|(])Format-Volume\b/i, ]; // File patterns that indicate policy-sensitive paths @@ -174,8 +182,8 @@ function analyzeForGovernanceEvents(input, context = {}) { }); } - // 2. Approval-required commands (Bash only) - if (toolName === 'Bash') { + // 2. Approval-required commands (any shell tool) + if (SECURITY_RELEVANT_TOOLS.has(toolName)) { const command = toolInput.command || ''; const approvalFindings = detectApprovalRequired(command); const commandSummary = summarizeCommand(command); @@ -220,7 +228,13 @@ function analyzeForGovernanceEvents(input, context = {}) { // 4. Security-relevant tool usage tracking if (SECURITY_RELEVANT_TOOLS.has(toolName) && hookPhase === 'post') { const command = toolInput.command || ''; - const hasElevated = /sudo\s/.test(command) || /chmod\s/.test(command) || /chown\s/.test(command); + const hasElevated = + /sudo\s/.test(command) || + /chmod\s/.test(command) || + /chown\s/.test(command) || + // PowerShell equivalents: UAC elevation and ACL/ownership changes. + /-Verb\s+RunAs/i.test(command) || + /\b(?:Set-Acl|icacls|takeown)\b/i.test(command); const commandSummary = summarizeCommand(command); if (hasElevated) { diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.js index 8912eb99447..e9be32e6fd6 100644 --- a/tests/hooks/gateguard-fact-force.test.js +++ b/tests/hooks/gateguard-fact-force.test.js @@ -2456,6 +2456,233 @@ function runTests() { passed++; else failed++; + // --- PowerShell: the tool bypassed every destructive gate before this --- + // + // CLAUDE_CODE_USE_POWERSHELL_TOOL=1 makes PowerShell a second arbitrary-command + // shell. Its delete verbs share no syntax with POSIX `rm`, so the Bash + // tokenizer could not see them and unknown tool names hit the bare + // allow-fallthrough at the end of run(). + + function runPsHook(command, env = {}) { + clearState(); + return runBashHook({ tool_name: 'PowerShell', tool_input: { command } }, env); + } + + function expectPsDeny(command, label) { + const result = runPsHook(command); + assert.strictEqual(result.code, 0, `${label}: exit code should be 0`); + const output = parseOutput(result.stdout); + assert.ok(output, `${label}: should produce JSON output`); + assert.ok(output.hookSpecificOutput, `${label}: should not pass through ungated`); + assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny', `${label}: should deny`); + assert.ok( + output.hookSpecificOutput.permissionDecisionReason.includes('Destructive'), + `${label}: reason should mention "Destructive"` + ); + } + + function expectPsAllow(command, label) { + clearState(); + writeState({ checked: ['__bash_session__'], last_active: Date.now() }); + const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command } }); + assert.strictEqual(result.code, 0, `${label}: exit code should be 0`); + const output = parseOutput(result.stdout); + if (output && output.hookSpecificOutput) { + assert.notStrictEqual(output.hookSpecificOutput.permissionDecision, 'deny', `${label}: should not deny`); + } + } + + // The exact command pair that proved the bug: identical destructive intent, + // two tools. Both must now deny. + if ( + test('denies PowerShell Remove-Item -Recurse -Force (the original bypass)', () => { + expectPsDeny('Remove-Item -Recurse -Force C:/tmp/demo', 'Remove-Item -Recurse -Force'); + }) + ) + passed++; + else failed++; + + if ( + test('denies PowerShell rm alias with PowerShell-style flags', () => { + expectPsDeny('rm -Recurse -Force C:/tmp/demo', 'rm -Recurse -Force'); + }) + ) + passed++; + else failed++; + + // PowerShell accepts any unambiguous parameter prefix. + if ( + test('denies abbreviated -Rec and -r parameter prefixes', () => { + expectPsDeny('Remove-Item -Rec -Force C:/tmp/demo', '-Rec'); + expectPsDeny('Remove-Item -r C:/tmp/demo', '-r'); + }) + ) + passed++; + else failed++; + + if ( + test('denies Remove-Item aliases del/rd/rmdir/ri with -Recurse', () => { + expectPsDeny('del -Recurse C:/tmp/demo', 'del'); + expectPsDeny('rd -Recurse C:/tmp/demo', 'rd'); + expectPsDeny('rmdir -Recurse C:/tmp/demo', 'rmdir'); + expectPsDeny('ri -Recurse C:/tmp/demo', 'ri'); + }) + ) + passed++; + else failed++; + + if ( + test('denies forced wildcard delete without -Recurse', () => { + expectPsDeny('Remove-Item -Force C:/build/*', '-Force with wildcard'); + }) + ) + passed++; + else failed++; + + if ( + test('denies destructive PowerShell in a later statement of a chain', () => { + expectPsDeny('Get-ChildItem C:/tmp; Remove-Item -Recurse -Force C:/tmp/demo', 'chained ;'); + }) + ) + passed++; + else failed++; + + // Shell-agnostic phrases must still be caught when they arrive via PowerShell. + if ( + test('denies git push --force and git reset --hard via PowerShell', () => { + expectPsDeny('git push --force origin main', 'PowerShell git push --force'); + expectPsDeny('git reset --hard HEAD~1', 'PowerShell git reset --hard'); + }) + ) + passed++; + else failed++; + + // -Force is gated even without -Recurse: unlike `rm -f`, PowerShell's + // `Remove-Item -Force ` removes the whole tree, and a static + // string cannot tell a file target from a directory target. + if ( + test('denies -Force without -Recurse (directory targets recurse in PowerShell)', () => { + expectPsDeny('Remove-Item -Force C:/tmp/some-directory', '-Force alone'); + }) + ) + passed++; + else failed++; + + // A plain delete with no -Recurse/-Force stays ungated. + if ( + test('allows a plain non-recursive PowerShell delete', () => { + expectPsAllow('Remove-Item C:/tmp/notes.txt', 'plain Remove-Item'); + }) + ) + passed++; + else failed++; + + // --- Regression: bypasses found in security/code review of the first draft --- + + if ( + test('denies quoted-separator evasion of the segment splitter', () => { + expectPsDeny('Remove-Item -Force "C:/evil;dir/*"', 'quoted ; in path'); + }) + ) + passed++; + else failed++; + + if ( + test('denies the pipe-to-delete idiom carrying -Recurse upstream', () => { + expectPsDeny('Get-ChildItem C:/tmp -Recurse | Remove-Item -Force', 'GCI -Recurse | RI'); + expectPsDeny('Get-ChildItem C:/tmp -Recurse | Remove-Item', 'GCI -Recurse | RI (no force)'); + }) + ) + passed++; + else failed++; + + if ( + test('denies the call operator with a quoted verb', () => { + expectPsDeny("& 'Remove-Item' -Recurse -Force C:/tmp/demo", '& call operator'); + }) + ) + passed++; + else failed++; + + if ( + test('denies backtick-obfuscated verbs and parameters', () => { + expectPsDeny('Rem`ove-Item -Recurse -Force C:/tmp/demo', 'backtick in verb'); + expectPsDeny('Remove-Item -Rec`urse C:/tmp/demo', 'backtick in parameter'); + }) + ) + passed++; + else failed++; + + if ( + test('denies nested shell reinvocation', () => { + expectPsDeny('powershell -Command "Remove-Item -Recurse -Force C:/tmp/demo"', 'powershell -Command'); + expectPsDeny('pwsh -c "Remove-Item -Recurse C:/tmp/demo"', 'pwsh -c'); + }) + ) + passed++; + else failed++; + + if ( + test('denies base64 -EncodedCommand payloads', () => { + const encoded = Buffer.from('Remove-Item -Recurse -Force C:/tmp/demo', 'utf16le').toString('base64'); + expectPsDeny(`powershell -EncodedCommand ${encoded}`, '-EncodedCommand'); + }) + ) + passed++; + else failed++; + + if ( + test('denies cmd.exe recursive removal via cmd /c', () => { + expectPsDeny('cmd /c rd /s /q C:/tmp/demo', 'cmd /c rd /s /q'); + }) + ) + passed++; + else failed++; + + if ( + test('denies .NET directory deletion', () => { + expectPsDeny("[System.IO.Directory]::Delete('C:/tmp/demo', $true)", '.NET Directory::Delete'); + }) + ) + passed++; + else failed++; + + if ( + test('denies splatted delete parameters as opaque', () => { + expectPsDeny('Remove-Item @params', 'splatted parameters'); + }) + ) + passed++; + else failed++; + + if ( + test('allows read-only PowerShell commands', () => { + expectPsAllow('Get-ChildItem C:/tmp', 'Get-ChildItem'); + }) + ) + passed++; + else failed++; + + // Regression guard: the routine gate is shared, so PowerShell must not get a + // second first-command gate after Bash has already satisfied it. + if ( + test('shares the routine session gate with Bash', () => { + clearState(); + writeState({ checked: ['__bash_session__'], last_active: Date.now() }); + const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); + const output = parseOutput(result.stdout); + if (output && output.hookSpecificOutput) { + assert.notStrictEqual( + output.hookSpecificOutput.permissionDecision, + 'deny', + 'PowerShell should not re-trigger the routine gate Bash already satisfied' + ); + } + }) + ) + passed++; + else failed++; + // Cleanup only the temp directory created by this test file. try { if (fs.existsSync(stateDir)) { From 308f39074c83dd7571be88532a7c93e2f029b1e1 Mon Sep 17 00:00:00 2001 From: Nathan Oliver Date: Sat, 8 Aug 2026 09:30:15 +0800 Subject: [PATCH 2/3] test(hooks): cover the PowerShell governance rules The PowerShell entries in APPROVAL_COMMANDS and the extended elevated-privilege check had no suite coverage; they were verified only by direct invocation. Adds 5 cases: recursive-delete detection including abbreviated parameter prefixes, Clear-Content/Format-Volume, a benign control, approval_requested parity with Bash, and elevated-privilege security_finding for RunAs/Set-Acl/takeown. All 6 assertions verified red-green against the pre-fix module (pre=none, post=flag); the benign control is 0 in both. Suite: 35 passed, 0 failed. --- tests/hooks/governance-capture.test.js | 43 ++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/hooks/governance-capture.test.js b/tests/hooks/governance-capture.test.js index df118594afa..a0b02b0ae75 100644 --- a/tests/hooks/governance-capture.test.js +++ b/tests/hooks/governance-capture.test.js @@ -353,6 +353,49 @@ async function runTests() { assert.ok(eventTypes.includes('approval_requested')); })) passed += 1; else failed += 1; + // --- PowerShell: a second arbitrary-command shell, previously unwatched --- + // + // Before PowerShell joined SECURITY_RELEVANT_TOOLS, a command that bypassed + // the gateguard deny was also invisible to the audit trail. These cover the + // PowerShell entries in APPROVAL_COMMANDS and the elevated-privilege check. + + if (await test('detectApprovalRequired flags PowerShell recursive deletes', async () => { + assert.ok(detectApprovalRequired('Remove-Item -Recurse -Force C:/tmp/demo').length > 0); + // PowerShell accepts any unambiguous parameter prefix. + assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0); + assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0); + })) passed += 1; else failed += 1; + + if (await test('detectApprovalRequired flags Clear-Content and Format-Volume', async () => { + assert.ok(detectApprovalRequired('Clear-Content C:/tmp/log.txt').length > 0); + assert.ok(detectApprovalRequired('Format-Volume -DriveLetter D').length > 0); + })) passed += 1; else failed += 1; + + if (await test('detectApprovalRequired ignores benign PowerShell', async () => { + assert.strictEqual(detectApprovalRequired('Get-ChildItem C:/tmp').length, 0); + assert.strictEqual(detectApprovalRequired('Get-Date').length, 0); + })) passed += 1; else failed += 1; + + if (await test('PowerShell tool raises approval_requested like Bash', async () => { + const events = analyzeForGovernanceEvents({ + tool_name: 'PowerShell', + tool_input: { command: 'Remove-Item -Recurse -Force C:/tmp/demo' }, + }); + assert.ok(events.map(e => e.eventType).includes('approval_requested')); + })) passed += 1; else failed += 1; + + if (await test('PowerShell elevated-privilege commands raise a security_finding', async () => { + for (const command of ['Start-Process -Verb RunAs cmd', 'Set-Acl -Path C:/x -AclObject $a', 'takeown /f C:/x']) { + const events = analyzeForGovernanceEvents( + { tool_name: 'PowerShell', tool_input: { command } }, + { hookPhase: 'post' } + ); + const finding = events.find(e => e.eventType === 'security_finding'); + assert.ok(finding, `${command} should raise a security_finding`); + assert.strictEqual(finding.payload.reason, 'elevated_privilege_command'); + } + })) passed += 1; else failed += 1; + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); process.exit(failed > 0 ? 1 : 0); } From c4b6cb6016f0908ca47d934f9c78c9b37570ee1b Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Wed, 12 Aug 2026 00:11:45 -0400 Subject: [PATCH 3/3] fix(hooks): complete PowerShell gate routing --- hooks/hooks.json | 14 +++++- scripts/hooks/gateguard-fact-force.js | 16 ++++-- scripts/hooks/governance-capture.js | 2 +- scripts/hooks/posttooluse-dispatcher.js | 2 +- tests/hooks/gateguard-fact-force.test.js | 32 +++++++++++- tests/hooks/governance-capture.test.js | 1 + tests/hooks/hooks.test.js | 57 ++++++++++++++++++++++ tests/hooks/posttooluse-dispatcher.test.js | 9 +++- 8 files changed, 124 insertions(+), 9 deletions(-) diff --git a/hooks/hooks.json b/hooks/hooks.json index 2eb1ef3ea95..7925802a788 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -13,6 +13,18 @@ "description": "Consolidated Bash preflight dispatcher for quality, tmux, push, and GateGuard checks", "id": "pre:bash:dispatcher" }, + { + "matcher": "PowerShell", + "hooks": [ + { + "type": "command", + "command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i 4) return false; + // Deeply wrapped commands are no longer statically analyzable. Treat scan + // budget exhaustion as a gate candidate instead of silently allowing it. + if (depth > 4) return true; // PowerShell's backtick escapes a single character. `n / `r are newlines // (statement separators); before any other character the backtick is a no-op @@ -814,7 +817,13 @@ function isDestructivePowerShell(command, depth = 0) { // Splatted parameters (`Remove-Item @params`) are opaque to static // inspection, so a splatted delete is gated rather than assumed safe. if (token.startsWith('@')) return true; - if (!token.startsWith('-')) continue; + if (!token.startsWith('-')) { + // PowerShell expands wildcard targets before deletion. Even without + // -Recurse or -Force, one command can therefore remove an unbounded + // number of entries. + if (token.includes('*') || token.includes('?')) return true; + continue; + } // -Force is gated as well as -Recurse: unlike `rm -f`, PowerShell's // `Remove-Item -Force ` removes the tree. if (isPsParamPrefixOf(token, 'recurse') || isPsParamPrefixOf(token, 'force')) { @@ -1475,7 +1484,8 @@ function run(rawInput) { if (!markChecked(ROUTINE_BASH_SESSION_KEY)) { return allowWithStateWarning(); } - return denyResult(routineBashMsg(), { hookIds: [BASH_HOOK_ID] }); + const shellHookId = toolName === 'PowerShell' ? POWERSHELL_HOOK_ID : BASH_HOOK_ID; + return denyResult(routineBashMsg(), { hookIds: [shellHookId] }); } return rawInput; // allow diff --git a/scripts/hooks/governance-capture.js b/scripts/hooks/governance-capture.js index 1a5cf99f622..f5e14e36255 100644 --- a/scripts/hooks/governance-capture.js +++ b/scripts/hooks/governance-capture.js @@ -48,7 +48,7 @@ const APPROVAL_COMMANDS = [ /DELETE\s+FROM\s+\w+\s*(?:;|$)/i, // PowerShell Remove-Item and its aliases with -Recurse. PowerShell accepts any // unambiguous parameter prefix, so -Recurse, -Rec and -r must all match. - /(?:^|[\s;|(])(?:Remove-Item|Remove-ItemProperty|ri|rmdir|rd|del|erase)\b[^;|]*\s-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b/i, + /(?:^|[\s;|(])(?:Remove-Item|Remove-ItemProperty|ri|rm|rmdir|rd|del|erase)\b[^;|]*\s-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b/i, /(?:^|[\s;|(])Clear-(?:Content|Disk)\b/i, /(?:^|[\s;|(])Format-Volume\b/i, ]; diff --git a/scripts/hooks/posttooluse-dispatcher.js b/scripts/hooks/posttooluse-dispatcher.js index 027ea569f43..6f6f6dd2f65 100644 --- a/scripts/hooks/posttooluse-dispatcher.js +++ b/scripts/hooks/posttooluse-dispatcher.js @@ -26,7 +26,7 @@ const SYNC_HOOKS = [ { id: 'post:edit:design-quality-check', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/design-quality-check.js', run: runDesignQualityCheck }, { id: 'post:edit:accumulator', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-accumulator.js', run: runPostEditAccumulator }, { id: 'post:edit:console-warn', matcher: 'Edit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-console-warn.js', run: runConsoleWarn }, - { id: 'post:governance-capture', matcher: 'Bash|Write|Edit|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/governance-capture.js', run: runGovernanceCapture }, + { id: 'post:governance-capture', matcher: 'Bash|PowerShell|Write|Edit|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/governance-capture.js', run: runGovernanceCapture }, { id: 'post:session-activity-tracker', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/session-activity-tracker.js', run: runSessionActivityTracker }, { id: 'post:ecc-metrics-bridge', matcher: '*', profiles: 'minimal,standard,strict', script: 'scripts/hooks/ecc-metrics-bridge.js', run: runMetricsBridge }, { id: 'post:ecc-context-monitor', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/ecc-context-monitor.js', run: runContextMonitor } diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.js index e9be32e6fd6..d5a4176a8d5 100644 --- a/tests/hooks/gateguard-fact-force.test.js +++ b/tests/hooks/gateguard-fact-force.test.js @@ -2487,8 +2487,11 @@ function runTests() { const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command } }); assert.strictEqual(result.code, 0, `${label}: exit code should be 0`); const output = parseOutput(result.stdout); - if (output && output.hookSpecificOutput) { + assert.ok(output, `${label}: should produce JSON output`); + if (output.hookSpecificOutput) { assert.notStrictEqual(output.hookSpecificOutput.permissionDecision, 'deny', `${label}: should not deny`); + } else { + assert.strictEqual(output.tool_name, 'PowerShell', `${label}: pass-through should preserve the tool name`); } } @@ -2539,6 +2542,15 @@ function runTests() { passed++; else failed++; + if ( + test('denies wildcard-only PowerShell deletes', () => { + expectPsDeny('Remove-Item C:/build/*', 'wildcard target'); + expectPsDeny('Remove-Item C:/build/file?.tmp', 'single-character wildcard target'); + }) + ) + passed++; + else failed++; + if ( test('denies destructive PowerShell in a later statement of a chain', () => { expectPsDeny('Get-ChildItem C:/tmp; Remove-Item -Recurse -Force C:/tmp/demo', 'chained ;'); @@ -2631,6 +2643,19 @@ function runTests() { passed++; else failed++; + if ( + test('fails closed when encoded PowerShell nesting exceeds the scan budget', () => { + let command = 'Remove-Item -Recurse -Force C:/tmp/demo'; + for (let depth = 0; depth < 6; depth += 1) { + const encoded = Buffer.from(command, 'utf16le').toString('base64'); + command = `powershell -EncodedCommand ${encoded}`; + } + expectPsDeny(command, 'deep -EncodedCommand nesting'); + }) + ) + passed++; + else failed++; + if ( test('denies cmd.exe recursive removal via cmd /c', () => { expectPsDeny('cmd /c rd /s /q C:/tmp/demo', 'cmd /c rd /s /q'); @@ -2671,12 +2696,15 @@ function runTests() { writeState({ checked: ['__bash_session__'], last_active: Date.now() }); const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } }); const output = parseOutput(result.stdout); - if (output && output.hookSpecificOutput) { + assert.ok(output, 'PowerShell should produce pass-through JSON'); + if (output.hookSpecificOutput) { assert.notStrictEqual( output.hookSpecificOutput.permissionDecision, 'deny', 'PowerShell should not re-trigger the routine gate Bash already satisfied' ); + } else { + assert.strictEqual(output.tool_name, 'PowerShell'); } }) ) diff --git a/tests/hooks/governance-capture.test.js b/tests/hooks/governance-capture.test.js index a0b02b0ae75..060c39e79b3 100644 --- a/tests/hooks/governance-capture.test.js +++ b/tests/hooks/governance-capture.test.js @@ -364,6 +364,7 @@ async function runTests() { // PowerShell accepts any unambiguous parameter prefix. assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0); assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0); + assert.ok(detectApprovalRequired('rm -Recurse C:/tmp/demo').length > 0); })) passed += 1; else failed += 1; if (await test('detectApprovalRequired flags Clear-Content and Format-Volume', async () => { diff --git a/tests/hooks/hooks.test.js b/tests/hooks/hooks.test.js index 49d6f1e23c3..46550c25280 100644 --- a/tests/hooks/hooks.test.js +++ b/tests/hooks/hooks.test.js @@ -2541,10 +2541,26 @@ async function runTests() { const hooks = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); const preBash = hooks.hooks.PreToolUse.filter(entry => entry.matcher === 'Bash'); + const prePowerShell = hooks.hooks.PreToolUse.filter(entry => entry.matcher === 'PowerShell'); + const preGovernance = hooks.hooks.PreToolUse.find(entry => entry.id === 'pre:governance-capture'); const postEntries = hooks.hooks.PostToolUse; assert.strictEqual(preBash.length, 1, 'Should have exactly one PreToolUse Bash dispatcher'); assert.strictEqual(preBash[0].id, 'pre:bash:dispatcher'); + assert.strictEqual(prePowerShell.length, 1, 'Should have exactly one dedicated PreToolUse PowerShell GateGuard route'); + assert.strictEqual(prePowerShell[0].id, 'pre:powershell:gateguard-fact-force'); + assert.ok( + prePowerShell[0].hooks[0].command.includes('pre:powershell:gateguard-fact-force'), + 'PowerShell route should preserve its independently configurable hook ID' + ); + assert.ok( + prePowerShell[0].hooks[0].command.includes('scripts/hooks/gateguard-fact-force.js'), + 'PowerShell route should invoke GateGuard directly instead of unrelated Bash hooks' + ); + assert.ok( + preGovernance.matcher.split('|').includes('PowerShell'), + 'PreToolUse governance capture should receive PowerShell commands' + ); assert.deepStrictEqual( postEntries.map(entry => entry.id), ['post:dispatcher:sync', 'post:dispatcher:async'], @@ -2564,6 +2580,47 @@ async function runTests() { passed++; else failed++; + if ( + test('configured PowerShell route reaches GateGuard without Bash-only hooks', () => { + const repoRoot = path.join(__dirname, '..', '..'); + const hooksPath = path.join(repoRoot, 'hooks', 'hooks.json'); + const hooks = JSON.parse(fs.readFileSync(hooksPath, 'utf8')); + const route = hooks.hooks.PreToolUse.find(entry => entry.id === 'pre:powershell:gateguard-fact-force'); + const stateDir = createTestDir(); + + try { + const result = spawnSync(route.hooks[0].command, { + shell: true, + cwd: repoRoot, + input: JSON.stringify({ + hook_event_name: 'PreToolUse', + tool_name: 'PowerShell', + tool_input: { command: 'Remove-Item C:/build/*' }, + session_id: 'configured-powershell-route' + }), + encoding: 'utf8', + env: { + ...process.env, + CLAUDE_PLUGIN_ROOT: repoRoot, + ECC_PLUGIN_ROOT: repoRoot, + ECC_PROFILE: 'standard', + GATEGUARD_STATE_DIR: stateDir + }, + timeout: 10000 + }); + + assert.strictEqual(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny'); + assert.match(output.hookSpecificOutput.permissionDecisionReason, /Destructive command detected/); + } finally { + cleanupTestDir(stateDir); + } + }) + ) + passed++; + else failed++; + if ( test('SessionEnd marker hook is async and cleanup-safe', () => { const hooksPath = path.join(__dirname, '..', '..', 'hooks', 'hooks.json'); diff --git a/tests/hooks/posttooluse-dispatcher.test.js b/tests/hooks/posttooluse-dispatcher.test.js index 0900117d41e..18ef6e2ac28 100644 --- a/tests/hooks/posttooluse-dispatcher.test.js +++ b/tests/hooks/posttooluse-dispatcher.test.js @@ -30,7 +30,9 @@ function runDispatcher(mode, toolName, env = {}) { const raw = JSON.stringify({ hook_event_name: 'PostToolUse', tool_name: toolName, - tool_input: toolName === 'Bash' ? { command: 'true' } : { file_path: path.join(os.tmpdir(), 'ecc-posttooluse-test.txt') }, + tool_input: ['Bash', 'PowerShell'].includes(toolName) + ? { command: 'true' } + : { file_path: path.join(os.tmpdir(), 'ecc-posttooluse-test.txt') }, tool_response: {} }); @@ -126,6 +128,11 @@ function runTests() { sync: ['post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'], async: ['post:bash:dispatcher', 'post:observe:continuous-learning'] }, + { + tool: 'PowerShell', + sync: ['post:governance-capture', 'post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'], + async: ['post:observe:continuous-learning'] + }, { tool: 'Read', sync: ['post:session-activity-tracker', 'post:ecc-metrics-bridge', 'post:ecc-context-monitor'],