Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 213 additions & 4 deletions scripts/hooks/gateguard-fact-force.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
Comment on lines +729 to +731

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Clear-Content, Clear-Disk, and Format-Volume are gated by governance capture but not by the gate.

scripts/hooks/governance-capture.js Lines 52-53 add Clear-(?:Content|Disk) and Format-Volume to APPROVAL_COMMANDS. isDestructivePowerShell has no equivalent. PS_DELETE_VERBS at Lines 729-731 lists only Remove-Item and its aliases, and the regexes at Lines 740-743 cover only .NET delete and cmd recursive delete.

Result: Format-Volume -DriveLetter D emits an approval_requested event but passes the destructive gate once the session routine gate is satisfied. The audit record and the enforcement decision disagree — the same class of gap reported earlier for the rm alias, in the opposite direction.

Add a data-destruction verb set that is gated independently of -Recurse / -Force, since these cmdlets destroy content without either parameter.

🔒 Proposed fix: gate content-destroying cmdlets
 const PS_DELETE_VERBS = new Set([
   'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase',
 ]);
+
+// Cmdlets that destroy data without a delete verb and without -Recurse/-Force.
+// Gated on presence alone, matching the governance-capture approval patterns.
+const PS_DATA_DESTROYERS = new Set([
+  'clear-content', 'clear-disk', 'format-volume',
+]);
   for (const tokens of quoteAwareSegments(raw)) {
     if (tokens.length === 0) continue;
 
     const verb = commandBasename(tokens[0]);
     const rest = tokens.slice(1);
+
+    if (PS_DATA_DESTROYERS.has(verb)) return true;
 
     if (PS_NESTED_SHELLS.has(verb)) {

Also applies to: 784-798

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/hooks/gateguard-fact-force.js` around lines 729 - 731, Extend the
PowerShell destructive-command detection around PS_DELETE_VERBS and
isDestructivePowerShell to include Clear-Content, Clear-Disk, and Format-Volume
in a separate data-destruction verb set. Gate these verbs independently of
-Recurse and -Force, while preserving existing Remove-Item, .NET delete, and cmd
recursive-delete handling.


// 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.
Comment on lines +760 to +766

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

The doc comment contradicts the implemented behavior.

Lines 765-766 state that Remove-Item -Force notes.txt stays ungated. Line 829 gates any -Force prefix, and Lines 827-828 explain why. The test at tests/hooks/gateguard-fact-force.test.js Line 2577 asserts denial for Remove-Item -Force C:/tmp/some-directory.

Correct the doc so a future reader does not treat the -Force gate as a bug.

📝 Proposed doc fix
- * 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.
+ * The hazard class is *recursive, forced, or wildcarded* deletion, not any
+ * delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even
+ * without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree
+ * and a static string cannot distinguish a file target from a directory target.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* 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.
/**
* Detect destructive PowerShell commands.
*
* The hazard class is *recursive, forced, or wildcarded* deletion, not any
* delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even
* without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree
* and a static string cannot distinguish a file target from a directory target.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/hooks/gateguard-fact-force.js` around lines 760 - 766, Update the
documentation comment for the destructive PowerShell command detector near
isDestructiveRm to accurately describe the implemented behavior: any Remove-Item
-Force prefix is gated, including single-file and directory targets. Remove the
claim that Remove-Item -Force notes.txt remains ungated, while preserving the
explanation that this behavior intentionally differs from the rm -f comparison.

*
* @param {string} command
* @returns {boolean}
*/
function isDestructivePowerShell(command, depth = 0) {
if (depth > 4) return false;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// 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 <directory>` removes the tree.
if (isPsParamPrefixOf(token, 'recurse') || isPsParamPrefixOf(token, 'force')) {
return true;
Comment on lines +803 to +830

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.

P1 security PowerShell subexpressions bypass the destructive-command gate

The PowerShell pre-tool hook denies Remove-Item -Recurse -Force C:/tmp/demo, but passes $(Remove-Item -Recurse -Force C:/tmp/demo) through on a fresh session. PowerShell evaluates the statement inside $(), so a destructive deletion can execute without the fact-forcing denial. Recursively inspect quote- and nesting-aware $() bodies with the same destructive-command classifier, and add a regression test for this form.

Rule Used: Treat CLI inputs, URLs, file paths, and subprocess... (source)

Artifacts

Node hook reproduction source comparing direct and PowerShell subexpression deletes

  • This executed Node-only harness sends direct and `$()` PowerShell command strings to the configured hook with fresh state directories and sessions, showing the precise comparison setup.

Initial hook comparison: direct delete denied and subexpression delete passed through

  • This captured first execution shows the direct destructive command denied while the `$()` form is returned unchanged by the Node hook, confirming the bypass.

Repeated hook comparison: direct delete denied and subexpression delete passed through

  • This independently repeated execution with fresh state directories and sessions reproduces the same direct-deny versus subexpression-pass-through result, confirming it is deterministic.

Focused GateGuard regression suite passes without the missing PowerShell subexpression case

  • This captured focused regression run completed with 166 passing tests and zero failures, showing existing coverage does not catch the reproduced PowerShell `$()` bypass.

View artifacts

T-Rex Ran code and verified through T-Rex

}
}
}

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) {
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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)) {
Expand Down
22 changes: 18 additions & 4 deletions scripts/hooks/governance-capture.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/(?:^|[\s;|(])Clear-(?:Content|Disk)\b/i,
/(?:^|[\s;|(])Format-Volume\b/i,
];

// File patterns that indicate policy-sensitive paths
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down
Loading