From ef7073ab7200205dcf60d8499f85eb2a9e461b68 Mon Sep 17 00:00:00 2001 From: Yovany Date: Fri, 27 Nov 2026 20:56:06 -0800 Subject: [PATCH] fix(hooks): pre-bash fails closed under cmd.exe and blocks Windows drive wipes (#5166) pre-bash took the command from `prompt`, which falls back to process.env.PROMPT. cmd.exe always sets PROMPT=$P$G, so under a cmd environment an empty or command-less payload validated "$p$g" and exited 0, defeating the #4743 fail-closed gate. The classic helper and the inline fallback now read the command only from the hook payload. The classic helpers, the inline fallback and the ruflo-mods guard also block wiping or formatting a whole Windows drive: format , rd/rmdir /s , and Remove-Item (or an alias) with -Recurse on a drive root (C:\, C:/, C:, "C:\", C:\*). Paths below the root and Format-Table pass. The DANGEROUS_COMMANDS list is unchanged, so ADR-404 list parity holds. helpers.manifest.json needs re-signing with the release key. Fixes #5166 Co-Authored-By: Claude Opus 5.5 --- .claude/helpers/hook-handler.cjs | 27 ++++- CHANGELOG.md | 1 + .../hooks/guard/dangerous-command.ts | 20 ++++ .../cli/.claude/helpers/hook-handler.cjs | 27 ++++- .../issue-5166-pre-bash-windows.test.ts | 104 ++++++++++++++++++ .../cli/src/init/helpers-generator.ts | 29 ++++- 6 files changed, 205 insertions(+), 3 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/issue-5166-pre-bash-windows.test.ts diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs index 638a98583a..d02c5518d4 100755 --- a/.claude/helpers/hook-handler.cjs +++ b/.claude/helpers/hook-handler.cjs @@ -1006,7 +1006,9 @@ const handlers = { // Only a non-empty string counts as the command (#2017, #4743): input that // arrived late, did not parse, or carried no command blocks instead of passing. if (stdinUnparsable) blockPreBash('pre-bash could not parse the hook input'); - const raw = [hookInput.command, toolInput.command, prompt].find((c) => typeof c === 'string' && c.trim()); + // Only the stdin payload names the command (#5166): `prompt` falls back to process.env.PROMPT, which + // cmd.exe always sets ($P$G), so an empty payload validated that text instead of blocking. + const raw = [hookInput.command, toolInput.command, hookInput.prompt].find((c) => typeof c === 'string' && c.trim()); if (!raw) blockPreBash('pre-bash received no command to validate'); const cmd = raw.toLowerCase(); const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']; @@ -1307,6 +1309,24 @@ const handlers = { } return false } + // Wiping or formatting a whole Windows drive (#5166): cmd's format and rd/rmdir /s, and PowerShell's + // Remove-Item (or an alias) with -Recurse, aimed at a drive root: c:\, c:/, c:, "c:\" or c:\*. A path below + // the root (c:\temp) is not matched, nor is Format-Table. The command arrives lowercased. + function windowsDriveWipe(command) { + const start = /(?:^|[\s;&|(])/.source + const drive = /["']?[a-z]:[\\/]?\*?["']?(?=\s|$|[;&|)])/.source + const flags = /(?:\s+\/[a-z])*/.source + if (new RegExp(start + /format(?:\.com)?\s+[a-z]:/.source).test(command)) return 'format ' + if (new RegExp(start + /(?:rd|rmdir)/.source + flags + /\s+\/s/.source + flags + /\s+/.source + drive).test(command) || + new RegExp(start + /(?:rd|rmdir)\s+/.source + drive + flags + /\s+\/s\b/.source).test(command)) return 'rd /s ' + const remove = new RegExp(start + /(?:remove-item|ri|rm|del|erase|rmdir|rd)\b([^;&|\n]*)/.source, 'g') + const recurse = /(?:^|\s)-r(?:e|ec|ecu|ecur|ecurs|ecurse)?\b/ + const target = new RegExp(/(?:^|\s)/.source + drive) + for (let m = remove.exec(command); m; m = remove.exec(command)) { + if (recurse.test(m[1]) && target.test(m[1])) return 'Remove-Item -Recurse ' + } + return '' + } for (const d of dangerous) { if (d === 'rm -rf /' ? hasRootDelete(cmd) : d === ':(){:|:&};:' ? hasForkBomb(cmd) : cmd.includes(d)) { console.error(`[BLOCKED] Dangerous command detected: ${d}`); @@ -1314,6 +1334,11 @@ const handlers = { process.exit(2); } } + const driveWipe = windowsDriveWipe(cmd); + if (driveWipe) { + console.error(`[BLOCKED] Dangerous command detected: ${driveWipe}`); + process.exit(2); + } console.log('[OK] Command validated'); }, diff --git a/CHANGELOG.md b/CHANGELOG.md index 521823baa8..c725fc249d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Security +- `pre-bash` fails closed on Windows again (#5166). The classic `hook-handler.cjs` and its inline fallback took the command from `prompt`, which falls back to `process.env.PROMPT`; cmd.exe always sets it (`$P$G`), so under a cmd environment an empty or command-less payload validated that text and passed the #4743 gate. The command now comes only from the hook payload. The classic helpers, the fallback and the ruflo-mods guard also block wiping or formatting a whole Windows drive: `format `, `rd`/`rmdir /s `, and `Remove-Item` (or an alias) with `-Recurse` on a drive root such as `C:\`, `C:/` or `C:\*`. Paths below the root and `Format-Table` are unaffected. - `@claude-flow/plugin-agent-federation`: `signatureMode` defaults to `require-jcs`. A legacy-v1 signature covers only `id` and `type`, so `payload`, `targetNodeId` and `sessionId` went unsigned (#4748). **Breaking:** a peer that does not advertise `ruflo-signature-jcs-v1` (an older release, or one joined by endpoint without a verified manifest) can no longer exchange heartbeat or status messages. Set `signatureMode: 'prefer-jcs'` to allow legacy-v1 for those two types again. ## [3.71.0] - 2026-11-01 diff --git a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts index a57ef69121..736444dc2f 100644 --- a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts +++ b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts @@ -306,6 +306,25 @@ function hasForkBomb(command: string): boolean { return false } +// Wiping or formatting a whole Windows drive (#5166): cmd's format and rd/rmdir /s, and PowerShell's +// Remove-Item (or an alias) with -Recurse, aimed at a drive root: c:\, c:/, c:, "c:\" or c:\*. A path below +// the root (c:\temp) is not matched, nor is Format-Table. The command arrives lowercased. +export function windowsDriveWipe(command: string): string { + const start = /(?:^|[\s;&|(])/.source + const drive = /["']?[a-z]:[\\/]?\*?["']?(?=\s|$|[;&|)])/.source + const flags = /(?:\s+\/[a-z])*/.source + if (new RegExp(start + /format(?:\.com)?\s+[a-z]:/.source).test(command)) return 'format ' + if (new RegExp(start + /(?:rd|rmdir)/.source + flags + /\s+\/s/.source + flags + /\s+/.source + drive).test(command) || + new RegExp(start + /(?:rd|rmdir)\s+/.source + drive + flags + /\s+\/s\b/.source).test(command)) return 'rd /s ' + const remove = new RegExp(start + /(?:remove-item|ri|rm|del|erase|rmdir|rd)\b([^;&|\n]*)/.source, 'g') + const recurse = /(?:^|\s)-r(?:e|ec|ecu|ecur|ecurs|ecurse)?\b/ + const target = new RegExp(/(?:^|\s)/.source + drive) + for (let m = remove.exec(command); m; m = remove.exec(command)) { + if (recurse.test(m[1]) && target.test(m[1])) return 'Remove-Item -Recurse ' + } + return '' +} + /** * A deny for a Bash call whose command is on the list, else undefined. * @@ -319,6 +338,7 @@ export function dangerousCommandVerdict(tool: string, input: unknown): Verdict | // never skipped. const command = String(raw ?? '').toLowerCase() const hit = DANGEROUS_COMMANDS.find(d => d === 'rm -rf /' ? hasRootDelete(command) : d === ':(){:|:&};:' ? hasForkBomb(command) : command.includes(d)) + ?? (windowsDriveWipe(command) || undefined) return hit === undefined ? undefined : { decision: 'deny', reason: `ruflo: dangerous command blocked (${hit})` } diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs index 638a98583a..d02c5518d4 100755 --- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs +++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs @@ -1006,7 +1006,9 @@ const handlers = { // Only a non-empty string counts as the command (#2017, #4743): input that // arrived late, did not parse, or carried no command blocks instead of passing. if (stdinUnparsable) blockPreBash('pre-bash could not parse the hook input'); - const raw = [hookInput.command, toolInput.command, prompt].find((c) => typeof c === 'string' && c.trim()); + // Only the stdin payload names the command (#5166): `prompt` falls back to process.env.PROMPT, which + // cmd.exe always sets ($P$G), so an empty payload validated that text instead of blocking. + const raw = [hookInput.command, toolInput.command, hookInput.prompt].find((c) => typeof c === 'string' && c.trim()); if (!raw) blockPreBash('pre-bash received no command to validate'); const cmd = raw.toLowerCase(); const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']; @@ -1307,6 +1309,24 @@ const handlers = { } return false } + // Wiping or formatting a whole Windows drive (#5166): cmd's format and rd/rmdir /s, and PowerShell's + // Remove-Item (or an alias) with -Recurse, aimed at a drive root: c:\, c:/, c:, "c:\" or c:\*. A path below + // the root (c:\temp) is not matched, nor is Format-Table. The command arrives lowercased. + function windowsDriveWipe(command) { + const start = /(?:^|[\s;&|(])/.source + const drive = /["']?[a-z]:[\\/]?\*?["']?(?=\s|$|[;&|)])/.source + const flags = /(?:\s+\/[a-z])*/.source + if (new RegExp(start + /format(?:\.com)?\s+[a-z]:/.source).test(command)) return 'format ' + if (new RegExp(start + /(?:rd|rmdir)/.source + flags + /\s+\/s/.source + flags + /\s+/.source + drive).test(command) || + new RegExp(start + /(?:rd|rmdir)\s+/.source + drive + flags + /\s+\/s\b/.source).test(command)) return 'rd /s ' + const remove = new RegExp(start + /(?:remove-item|ri|rm|del|erase|rmdir|rd)\b([^;&|\n]*)/.source, 'g') + const recurse = /(?:^|\s)-r(?:e|ec|ecu|ecur|ecurs|ecurse)?\b/ + const target = new RegExp(/(?:^|\s)/.source + drive) + for (let m = remove.exec(command); m; m = remove.exec(command)) { + if (recurse.test(m[1]) && target.test(m[1])) return 'Remove-Item -Recurse ' + } + return '' + } for (const d of dangerous) { if (d === 'rm -rf /' ? hasRootDelete(cmd) : d === ':(){:|:&};:' ? hasForkBomb(cmd) : cmd.includes(d)) { console.error(`[BLOCKED] Dangerous command detected: ${d}`); @@ -1314,6 +1334,11 @@ const handlers = { process.exit(2); } } + const driveWipe = windowsDriveWipe(cmd); + if (driveWipe) { + console.error(`[BLOCKED] Dangerous command detected: ${driveWipe}`); + process.exit(2); + } console.log('[OK] Command validated'); }, diff --git a/v3/@claude-flow/cli/__tests__/issue-5166-pre-bash-windows.test.ts b/v3/@claude-flow/cli/__tests__/issue-5166-pre-bash-windows.test.ts new file mode 100644 index 0000000000..3a94c9c639 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/issue-5166-pre-bash-windows.test.ts @@ -0,0 +1,104 @@ +/** Regression coverage for issue #5166. + * + * 1. pre-bash read the command from `prompt`, which falls back to + * process.env.PROMPT. cmd.exe always sets PROMPT=$P$G, so with a cmd + * environment an empty or command-less payload validated "$p$g" and exited + * 0, defeating the #4743 fail-closed gate. (issue-4743's own test blanks + * PROMPT, which is why it never showed.) + * 2. Wiping or formatting a whole Windows drive was not detected. + * + * Only hook helpers run; every command string below is inert stdin JSON data. */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { generateHookHandler } from '../src/init/helpers-generator'; +import { dangerousCommandVerdict } from '../../../../plugins/ruflo-mods/hooks/guard/dangerous-command'; + +const SHIPPED = [ + path.resolve(__dirname, '../.claude/helpers/hook-handler.cjs'), + path.resolve(__dirname, '../../../../.claude/helpers/hook-handler.cjs'), +]; +let project: string; +let fallback: string; + +beforeAll(() => { + project = mkdtempSync(path.join(tmpdir(), 'ruflo-5166-')); + fallback = path.join(project, 'hook-handler.cjs'); + writeFileSync(fallback, generateHookHandler()); +}); +afterAll(() => rmSync(project, { recursive: true, force: true })); + +function preBash(helper: string, input: string, extraEnv: Record = {}) { + return spawnSync(process.execPath, [helper, 'pre-bash'], { + input, cwd: project, encoding: 'utf8', timeout: 10_000, + env: { PATH: process.env.PATH, HOME: project, CI: '1', CLAUDE_PROJECT_DIR: project, RUFLO_MODS_OWNS: '', ...extraEnv }, + }); +} +const bash = (command: string) => JSON.stringify({ tool_name: 'Bash', tool_input: { command } }); + +describe('pre-bash ignores the PROMPT / TOOL_INPUT_command environment — issue #5166', () => { + const cmdEnv = { PROMPT: '$P$G' }; + it.each(SHIPPED.map((h) => [path.relative(path.resolve(__dirname, '../../../..'), h), h]))( + '%s still fails closed under a cmd.exe environment', (_name, helper) => { + for (const input of ['', '{}', JSON.stringify({ tool_input: {} }), JSON.stringify({ tool_input: { command: ' ' } })]) { + const r = preBash(helper, input, cmdEnv); + expect(r.status, `${JSON.stringify(input)}: ${r.stderr}`).toBe(2); + expect(r.stderr).toContain('[BLOCKED]'); + expect(r.stdout).not.toContain('[OK]'); + } + expect(preBash(helper, '{}', { TOOL_INPUT_command: 'ls' }).status).toBe(2); + expect(preBash(helper, bash('ls -la'), cmdEnv).status).toBe(0); + }); + + it('the inline fallback does not validate PROMPT instead of the payload', () => { + const r = preBash(fallback, '{}', { PROMPT: 'format c:' }); + expect(r.stderr).not.toContain('[BLOCKED]'); + expect(r.status).toBe(0); + }); +}); + +describe('Windows drive wipe — mod, shipped helpers and fallback agree (#5166)', () => { + const cases: Array<[string, boolean]> = [ + // drive roots: blocked + ['Remove-Item -Recurse -Force C:\\', true], + ['Remove-Item C:\\ -Recurse', true], + ['Remove-Item -Path "D:\\" -Recurse -Force', true], + ["Remove-Item -LiteralPath 'e:/' -Recurse", true], + ['ri -r -fo C:\\*', true], + ['rm -r c:/', true], + ['Get-Date; Remove-Item -Recurse C:/', true], + ['(Remove-Item -Rec C:)', true], + ['rd /s /q c:\\', true], + ['rd c:\\ /s /q', true], + ['rmdir /s /q C:\\', true], + ['RMDIR /Q /S D:', true], + ['format d:', true], + ['format.com C: /q', true], + ['echo x && format e: /fs:ntfs', true], + // below the root, or not a wipe: allowed + ['Remove-Item -Recurse -Force .\\build', false], + ['Remove-Item -Recurse C:\\temp\\cache', false], + ['Remove-Item -Recurse "C:\\Users\\me\\AppData\\Local\\Temp\\x"', false], + ['Remove-Item C:\\file.txt', false], + ['Remove-Item -Force D:\\', false], + ['rd /s /q C:\\projects\\old', false], + ['rd C:\\empty', false], + ['rmdir /s /q node_modules', false], + ['Get-Process | Format-Table -AutoSize', false], + ['Get-ChildItem C:\\ | Format-List', false], + ['git log --format=%H -3', false], + ['dir C:\\', false], + ['Remove-Item -Recurse $env:TEMP\\ruflo', false], + ]; + it.each(cases)('%j: denied=%s', (command, denied) => { + expect(dangerousCommandVerdict('Bash', { command })?.decision === 'deny').toBe(denied); + for (const helper of [...SHIPPED, fallback]) { + const r = preBash(helper, bash(command)); + expect(r.error, helper).toBeUndefined(); + expect(r.status, `${helper}: ${r.stderr}`).toBe(denied ? 2 : 0); + expect(denied ? r.stderr : r.stdout).toContain(denied ? '[BLOCKED]' : '[OK] Command validated'); + } + }); +}); diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts index 15489758c5..de35e6fd99 100644 --- a/v3/@claude-flow/cli/src/init/helpers-generator.ts +++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts @@ -783,6 +783,26 @@ function hasForkBomb(command) { return false }`; +// Windows drive-wipe guard (#5166), mirrored in the mod and both shipped classic helpers. +const WINDOWS_DRIVE_WIPE_SOURCE = String.raw`// Wiping or formatting a whole Windows drive (#5166): cmd's format and rd/rmdir /s, and PowerShell's +// Remove-Item (or an alias) with -Recurse, aimed at a drive root: c:\, c:/, c:, "c:\" or c:\*. A path below +// the root (c:\temp) is not matched, nor is Format-Table. The command arrives lowercased. +function windowsDriveWipe(command) { + const start = /(?:^|[\s;&|(])/.source + const drive = /["']?[a-z]:[\\/]?\*?["']?(?=\s|$|[;&|)])/.source + const flags = /(?:\s+\/[a-z])*/.source + if (new RegExp(start + /format(?:\.com)?\s+[a-z]:/.source).test(command)) return 'format ' + if (new RegExp(start + /(?:rd|rmdir)/.source + flags + /\s+\/s/.source + flags + /\s+/.source + drive).test(command) || + new RegExp(start + /(?:rd|rmdir)\s+/.source + drive + flags + /\s+\/s\b/.source).test(command)) return 'rd /s ' + const remove = new RegExp(start + /(?:remove-item|ri|rm|del|erase|rmdir|rd)\b([^;&|\n]*)/.source, 'g') + const recurse = /(?:^|\s)-r(?:e|ec|ecu|ecur|ecurs|ecurse)?\b/ + const target = new RegExp(/(?:^|\s)/.source + drive) + for (let m = remove.exec(command); m; m = remove.exec(command)) { + if (recurse.test(m[1]) && target.test(m[1])) return 'Remove-Item -Recurse ' + } + return '' +}`; + /** * Generate hook-handler.cjs (cross-platform hook dispatcher) * This is the inline fallback when file copy from the package fails. @@ -1004,9 +1024,11 @@ export function generateHookHandler(): string { ' },', '', " 'pre-bash': () => {", - " var cmd = String(hookInput.command || toolInputObj.command || prompt || '').toLowerCase();", + " // Only the stdin payload names the command (#5166): prompt falls back to process.env.PROMPT (cmd.exe: $P$G).", + " var cmd = String(hookInput.command || toolInputObj.command || hookInput.prompt || '').toLowerCase();", " var dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\\\', ':(){:|:&};:'];", ROOT_DELETE_CHECK_SOURCE.split('\n').map((line) => ' ' + line).join('\n'), + WINDOWS_DRIVE_WIPE_SOURCE.split('\n').map((line) => ' ' + line).join('\n'), ' for (var i = 0; i < dangerous.length; i++) {', " if (dangerous[i] === 'rm -rf /' ? hasRootDelete(cmd) : dangerous[i] === ':(){:|:&};:' ? hasForkBomb(cmd) : cmd.includes(dangerous[i])) {", " console.error('[BLOCKED] Dangerous command detected: ' + dangerous[i]);", @@ -1014,6 +1036,11 @@ export function generateHookHandler(): string { ' process.exit(2);', ' }', ' }', + ' var driveWipe = windowsDriveWipe(cmd);', + ' if (driveWipe) {', + " console.error('[BLOCKED] Dangerous command detected: ' + driveWipe);", + ' process.exit(2);', + ' }', " console.log('[OK] Command validated');", ' },', '',