Skip to content
Merged
65 changes: 50 additions & 15 deletions scripts/hooks/gateguard-fact-force.js
Original file line number Diff line number Diff line change
Expand Up @@ -1051,16 +1051,12 @@ function isDestructiveQuoteAware(raw, depth = 0) {
if (isDestructiveSqlClient(tokens)) return true;
if (isDestructiveFindExec(tokens)) return true;
const argv = unwrapLeadWrappers(tokens, true, true);
const base = commandBasename(argv[0]);
if (SHELL_WRAPPERS.has(base)) {
// `-c`, or a short-option cluster that includes it (`-lc`, `-ec`).
const ci = argv.findIndex((arg, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
if (ci !== -1 && argv[ci + 1] && isDestructiveQuoteAware(argv[ci + 1], depth + 1)) {
return true;
}
}
if (base === 'su') {
for (const commandLine of suCommandLines(argv)) {
// `sudo find . -exec rm {} \;` runs the same actions as a bare find.
if (isDestructiveFindExec(argv)) return true;
// A shell that find -exec starts runs its -c text like any other.
const execShells = findExecArgvs(argv).map(exec => unwrapLeadWrappers(exec, false, true));
for (const shellArgv of [argv, ...execShells]) {
for (const commandLine of nestedShellCommandLines(shellArgv)) {
if (isDestructiveQuoteAware(commandLine, depth + 1)) return true;
}
}
Expand All @@ -1069,6 +1065,23 @@ function isDestructiveQuoteAware(raw, depth = 0) {
return false;
}

/**
* Command text a resolved argv hands to a nested shell: the `-c` operand of
* sh/bash/zsh/dash/ksh (also inside a cluster such as `-lc` or `-ec`), or every
* command line of `su`.
*
* @param {string[]} argv
* @returns {string[]}
*/
function nestedShellCommandLines(argv) {
const base = commandBasename(argv[0]);
if (SHELL_WRAPPERS.has(base)) {
const ci = argv.findIndex((arg, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
return ci !== -1 && argv[ci + 1] ? [argv[ci + 1]] : [];
Comment on lines +1079 to +1080

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.

P2 Script arguments trigger destructive prompts

nestedShellCommandLines() scans past the shell's script name. For example, find . -exec bash /dev/null -c 'rm -rf /important/data' \; runs the empty script /dev/null; the remaining words are only script arguments. The new find-action scan instead treats that argument as shell code and raises an unnecessary destructive-command denial.

Stop looking for -c after a script name or --, and add a passive regression case.

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/hooks/gateguard-fact-force.js
Line: 1079-1080

Comment:
**Script arguments trigger destructive prompts**

`nestedShellCommandLines()` scans past the shell's script name. For example, `find . -exec bash /dev/null -c 'rm -rf /important/data' \;` runs the empty script `/dev/null`; the remaining words are only script arguments. The new find-action scan instead treats that argument as shell code and raises an unnecessary destructive-command denial.

Stop looking for `-c` after a script name or `--`, and add a passive regression case.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

}
return base === 'su' ? suCommandLines(argv) : [];
}

/**
* Strip a leading path and trailing `.exe` from a command token so
* `/usr/bin/git`, `git.exe`, and `GIT` all normalize to `git`.
Expand Down Expand Up @@ -1441,8 +1454,19 @@ const FIND_EXEC_ACTIONS = new Set(['-exec', '-execdir', '-ok', '-okdir']);
function isDestructiveFindExec(command) {
const quoteAware = Array.isArray(command);
const tokens = quoteAware ? command : tokenize(String(command || '').trim());
if (commandBasename(tokens[0]) !== 'find') return false;
return findExecArgvs(tokens).some(argv => isDestructiveFindExecArgv(argv, quoteAware));
}

/**
* The argv of every executable action of one find invocation, or [] when the
* tokens are not a find command.
*
* @param {string[]} tokens
* @returns {string[][]}
*/
function findExecArgvs(tokens) {
if (commandBasename(tokens[0]) !== 'find') return [];
const actions = [];
for (let index = 1; index < tokens.length; index += 1) {
const action = tokens[index];
if (action === '-fprintf') {
Expand All @@ -1456,9 +1480,9 @@ function isDestructiveFindExec(command) {
if (!FIND_EXEC_ACTIONS.has(action)) continue;
const exec = readFindExecArgv(tokens, index + 1, action);
index = exec.index;
if (exec.argv.length && isDestructiveFindExecArgv(exec.argv, quoteAware)) return true;
if (exec.argv.length) actions.push(exec.argv);
}
return false;
return actions;
}

// Collect the argv of one find action starting at `start`. Returns the argv
Expand All @@ -1479,10 +1503,21 @@ function readFindExecArgv(tokens, start, action) {

function isDestructiveFindExecArgv(argv, quoteAware) {
// The legacy raw fallback can split quoted prose into apparent actions.
// Preserve its old rm/Git coverage, but classify dd only from real argv.
// Preserve its old rm/Git coverage, but classify dd and wrappers only from
// real argv.
if (quoteAware && isDestructiveDd(argv, false)) return true;
if (isDestructiveFindExecCommand(argv)) return true;
if (!quoteAware) return false;
// find execs argv directly, so `-exec sudo rm {} \;` and
// `-exec timeout 5 rm {} \;` run rm just as `-exec rm {} \;` does (#2832).
// Shell builtins do not apply: find never runs `command` or `exec` itself.
const resolved = unwrapLeadWrappers(argv, false, true);
return resolved.length > 0 && isDestructiveFindExecCommand(resolved);
}

// Preserve main's existing find rm/rmdir/unlink and git-reset handling.
function isDestructiveFindExecCommand(argv) {
const baseCmd = commandBasename(argv[0]);
// Preserve main's existing rm/rmdir/unlink and git-reset handling.
if (baseCmd === 'rm' || baseCmd === 'rmdir' || baseCmd === 'unlink') return true;
if (baseCmd !== 'git') return false;
const sub = findGitSubcommand(argv);
Expand Down
50 changes: 49 additions & 1 deletion tests/hooks/gateguard-fact-force.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,51 @@ function runDdRegressionTests() {
});
}
}
// #2832: find execs its action argv directly, so a wrapper or a nested
// shell there runs rm/Git exactly like a bare `-exec rm {} \;`.
const findExecWrappedDestructive = [
'find . -exec sudo rm {} \\;',
'find . -exec doas rm {} \\;',
'find . -exec sudo -u root rm -rf {} \\;',
'find . -exec sudo git reset --hard \\;',
'find . -execdir sudo rm {} \\;',
'find . -ok doas rm {} \\;',
'find . -exec timeout 5m rm -rf {} \\;',
'find . -exec setsid rm -rf {} +',
'find . -exec env FOO=1 rm -rf {} +',
'find . -exec nice -n 5 rm -rf {} +',
'sudo find . -exec rm {} \\;',
'timeout 5 find . -exec rm -rf {} +',
"find . -exec sh -c 'rm -rf {}' \\;",
'find . -exec bash -c "rm -rf /important/data" \\;',
'find . -exec sh -ec "rm -rf {}" +',
'find . -exec sh -o errexit -c "rm -rf {}" \\;',
'find . -exec sh -c "git reset --hard" \\;',
"find . -exec sudo sh -c 'rm -rf {}' \\;",
"find . -exec timeout 5 sh -c 'rm -rf {}' \\;",
"find . -exec su -c 'rm -rf /important/data' \\;"
];
const findExecWrappedPassive = [
'find . -exec sudo chmod 644 {} \\;',
'find . -exec sudo git status \\;',
'find . -exec sudo -l rm -rf {} \\;',
'find . -exec echo sudo rm -rf {} \\;',
'find . -exec timeout 5 echo rm -rf {} \\;',
"find . -exec sh -c 'echo rm -rf {}' \\;",
'find . -exec sh -c "npm test" \\;',
"find . -name 'sudo rm -rf' -print",
'sudo find . -name "*.log" -exec ls {} \\;'
];
for (const [commands, expected] of [
[findExecWrappedDestructive, ['gateguard.bash-compatible-destructive']],
[findExecWrappedPassive, []]
]) {
for (const command of commands) {
check(`find -exec wrapper classification: ${JSON.stringify(command)}`, () => {
assert.deepStrictEqual(hook.classifyDestructiveCommand('Bash', command), expected);
});
}
}
for (const [command, denied] of [
['sudo -u root dd if=input', true],
["sh -c 'echo $(dd if=input)'", true],
Expand All @@ -738,7 +783,10 @@ function runDdRegressionTests() {
['find . -exec echo {} \\; -exec dd if=input \\;', true],
['command -pv dd', false],
["timeout 2 sh -c 'dd if=input'", true],
['cat /dev/zero | dd of=/dev/sda', true]
['cat /dev/zero | dd of=/dev/sda', true],
['find . -exec sudo rm -rf {} \\;', true],
["find . -exec sh -c 'rm -rf {}' +", true],
['find . -exec sudo chmod 644 {} \\;', false]
]) {
check(`dd hook-input contract: ${command}`, () => {
fs.rmSync(stateDir, { recursive: true, force: true });
Expand Down