Skip to content
Merged
105 changes: 99 additions & 6 deletions scripts/hooks/gateguard-fact-force.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,11 @@ const SHELL_WRAPPERS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
*/
function isDestructiveQuoteAware(raw, depth = 0) {
if (depth > 4) return false;
for (const tokens of quoteAwareSegments(raw)) {
for (const segment of quoteAwareSegments(raw)) {
if (segment.length === 0) continue;
// A quoted command word survives this path as a plain token, so the
// wrapper prefix has to be normalized here too (`sudo "rm" -rf /`).
const tokens = stripCommandWrappers(segment);
if (tokens.length === 0) continue;
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
Expand Down Expand Up @@ -375,6 +379,86 @@ function commandBasename(token) {
.toLowerCase();
}

/**
* Command words that run ANOTHER command: the destructive check has to look
* past them, or the most dangerous spellings are the ones that slip through.
* Every token-based detector keys on `tokens[0]`, so `sudo rm -rf /` reads as
* an invocation of `sudo` and is allowed while the bare `rm -rf /` is denied.
*
* The value is the set of that wrapper's OWN options which consume the
* following token, so the value is not mistaken for the wrapped command word.
* Arity is per wrapper because the same letter differs between them: `sudo -p`
* takes a prompt string, while `command -p` is a boolean that must leave `rm`
* as the next token. Long `--flag=value` forms need no entry (single token),
* and so do attached short forms (`stdbuf -oL`) — the flag token is skipped
* either way.
*
* @type {Map<string, Set<string>>}
*/
const COMMAND_WRAPPERS = new Map([
[
'sudo',
new Set([
'-a', '-C', '-c', '-D', '-g', '-h', '-p', '-R', '-r', '-T', '-t', '-U', '-u',
'--auth-type', '--close-from', '--login-class', '--chdir', '--group',
'--host', '--prompt', '--chroot', '--role', '--command-timeout', '--type',
'--other-user', '--user',
]),
],
['doas', new Set(['-a', '-C', '-u'])],
['env', new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string'])],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
['command', new Set()],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
['nohup', new Set()],
['setsid', new Set()],
['stdbuf', new Set(['-i', '-o', '-e', '--input', '--output', '--error'])],
['nice', new Set(['-n', '--adjustment'])],
[
'ionice',
new Set(['-c', '-n', '-p', '-P', '-u', '--class', '--classdata', '--pid', '--pgid', '--uid']),
],
]);

/**
* Return `tokens` with any leading wrapper commands, their options, and
* `VAR=value` assignment prefixes removed, so the caller sees the command that
* actually runs.
*
* Options are only skipped once a wrapper has been seen, so this can never walk
* into an unwrapped command's own arguments, and an option's value is only
* consumed when the wrapper it belongs to declares that arity. Returns the
* input array when there is nothing to strip.
*
* @param {string[]} tokens
* @returns {string[]}
*/
function stripCommandWrappers(tokens) {
if (!Array.isArray(tokens) || tokens.length === 0) return tokens;
let index = 0;
let valueFlags = null;
while (index < tokens.length) {
const token = tokens[index];
const wrapperFlags = COMMAND_WRAPPERS.get(commandBasename(token));
if (wrapperFlags) {
valueFlags = wrapperFlags;
index += 1;
continue;
}
// `FOO=bar rm -rf /` and `env FOO=bar rm -rf /` both put assignments before
// the command word.
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) {
index += 1;
continue;
}
if (valueFlags && token.startsWith('-')) {
if (valueFlags.has(token)) index += 1;
index += 1;
continue;
}
break;
}
return index === 0 ? tokens : tokens.slice(index);
}

/**
* Detect `rm` invocations that recursively force-delete files. Handles
* combined (`-rf`, `-fr`, `-Rf`) and split (`-r -f`) flag forms.
Expand Down Expand Up @@ -613,12 +697,12 @@ function isDestructiveFindExec(command) {
}

// Tokenize the whole command line
const tokens = tokenize(trimmed);
const tokens = stripCommandWrappers(tokenize(trimmed));
if (!tokens || tokens.length === 0) {
return false;
}

// Must start with `find`
// Must start with `find` — after any wrapper prefix (`sudo find . -exec rm`).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (commandBasename(tokens[0]) !== 'find') {
return false;
}
Expand All @@ -643,7 +727,14 @@ function isDestructiveFindExec(command) {
return false;
}

const baseCmd = commandBasename(execTokens[0]);
// `find . -exec sudo rm {} \;` runs the same deletion as `-exec rm`, so the
// executed command needs the same wrapper normalization as a top-level one.
const execCommand = stripCommandWrappers(execTokens);
if (execCommand.length === 0) {
return false;
}

const baseCmd = commandBasename(execCommand[0]);

// Directly destructive commands inside -exec
if (baseCmd === 'rmdir' || baseCmd === 'unlink') {
Comment thread
ntdat812 marked this conversation as resolved.
Resolved
Expand All @@ -657,7 +748,7 @@ function isDestructiveFindExec(command) {

// `git reset --hard` inside -exec
if (baseCmd === 'git') {
const sub = findGitSubcommand(execTokens);
const sub = findGitSubcommand(execCommand);
if (sub && sub.command === 'reset' && sub.rest.includes('--hard')) {
return true;
}
Expand Down Expand Up @@ -702,7 +793,9 @@ function isDestructiveBash(command) {
const stripped = stripQuotedStrings(segment);
if (DESTRUCTIVE_SQL_DD.test(stripped)) return true;
if (extra && extra.test(stripped)) return true;
const tokens = tokenize(segment);
// Look past sudo/doas/env/... so a privileged spelling is not the one that
// gets through (the gate matters MORE for those, not less).
const tokens = stripCommandWrappers(tokenize(segment));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (isDestructiveRm(tokens)) return true;
if (isDestructiveGit(tokens)) return true;
}
Expand Down
103 changes: 103 additions & 0 deletions tests/hooks/gateguard-fact-force.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,109 @@ function runTests() {
passed++;
else failed++;

// --- Test 4d: wrapper-prefixed destructive commands ---
/**
* Every token-based detector keys on `tokens[0]`, so `sudo rm -rf /` read as
* an invocation of `sudo` and was ALLOWED while the bare `rm -rf /` was
* denied — the gate missed exactly the privileged spellings it matters most
* for. Same for doas/env/command/nohup, `VAR=value` prefixes, sudo's own
* flags, and a wrapper appearing after a compound separator.
*/
for (const command of [
'sudo rm -rf /important/data',
'sudo -u root rm -rf /important/data',
'sudo --user=root rm -rf /important/data',
'doas rm -rf /important/data',
'env rm -rf /important/data',
'FOO=bar rm -rf /important/data',
'command rm -rf /important/data',
'nohup rm -rf /important/data',
'sudo git reset --hard',
'sudo git clean -fd',
'sudo git push --force',
'sudo find . -exec rm {} ;',
'echo hello && sudo rm -rf /important/data',
// A wrapper INSIDE `-exec` runs the same deletion as a bare one.
'find . -exec sudo rm {} ;',
'find . -exec doas rm {} ;',
'find . -exec sudo git reset --hard {} ;',
// Option arity is per wrapper: `command -p` is boolean and must leave `rm`
// in place, while `nice -n`, `stdbuf -o`, and `ionice -c` consume a value.
'command -p rm -rf /important/data',
'nice -n 10 rm -rf /important/data',
'stdbuf -o L rm -rf /important/data',
'stdbuf -oL rm -rf /important/data',
'ionice -c 3 rm -rf /important/data',
// Quoting the command word routes the check through the quote-aware pass,
// which needs the same wrapper normalization.
'sudo "rm" -rf /important/data',
"sudo 'rm' -rf /important/data",
'env "rm" -rf /important/data',
'doas "rm" -rf /important/data',
'sudo bash -c "rm -rf /important/data"'
]) {
clearState();
if (
test(`denies a wrapper-prefixed destructive command: ${command}`, () => {
// Prime the session so the separate first-command routine gate cannot
// be mistaken for a destructive denial.
runBashHook({ tool_name: 'Bash', tool_input: { command: 'printf ready' } });
const result = runBashHook({ tool_name: 'Bash', tool_input: { command } });
assert.strictEqual(result.code, 0, `hook should exit 0 for ${command}`);
const output = parseOutput(result.stdout);
assert.ok(output, `hook should produce JSON output for ${command}`);
assert.ok(output.hookSpecificOutput, `${command} should carry a permission decision`);
assert.strictEqual(
output.hookSpecificOutput.permissionDecision,
'deny',
`${command} must be gated as destructive`
);
assert.ok(output.hookSpecificOutput.permissionDecisionReason.includes('Destructive'));
})
)
passed++;
else failed++;
}

// --- Test 4e: looking past wrappers must not gate ordinary privileged work ---
for (const command of [
'sudo apt-get update',
'sudo systemctl restart nginx',
'sudo ls -la /etc',
'sudo -u root ls -la /etc',
'env NODE_ENV=production npm run build',
'command ls',
'command -p ls',
'command -v rm',
'nice -n 10 npm run build',
'ionice -c 3 npm test',
'stdbuf -o L npm test',
'find . -exec sudo chmod 644 {} ;'
]) {
clearState();
if (
test(`does not gate an ordinary wrapped command: ${command}`, () => {
runBashHook({ tool_name: 'Bash', tool_input: { command: 'printf ready' } });
const result = runBashHook({ tool_name: 'Bash', tool_input: { command } });
assert.strictEqual(result.code, 0, `hook should exit 0 for ${command}`);
const output = parseOutput(result.stdout);
assert.ok(output, `hook should produce JSON output for ${command}`);
const decision = output.hookSpecificOutput;
if (decision) {
const reason = decision.permissionDecisionReason || '';
assert.ok(
decision.permissionDecision !== 'deny' || !reason.includes('Destructive'),
`${command} must not be gated as destructive`
);
} else {
assert.strictEqual(output.tool_name, 'Bash', 'pass-through should preserve input');
}
})
)
passed++;
else failed++;
}

// --- Test 5: denies first routine Bash, allows second ---
clearState();
if (
Expand Down