Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
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
310 changes: 304 additions & 6 deletions scripts/hooks/block-no-verify.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

'use strict';

const { quotedRegions, quotedRegionAt, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD } = require('../lib/shell-quotes');

const MAX_STDIN = 1024 * 1024;
let raw = '';

Expand All @@ -35,6 +37,63 @@ const GIT_COMMANDS_WITH_NO_VERIFY = [
*/
const VALID_BEFORE_GIT = ' \t\n\r;&|$`(<{!"\']/.~\\';

/**
* Programs that execute a quoted argument as a shell command line, so a
* `git` inside one of their quoted arguments is a command that must still
* be checked (`sh -c "git commit --no-verify"`, `sudo`, `xargs`, `env`...).
* For any other argv0 (`node cli.js 'git commit --no-verify'`,
* `printf '%s' '...'`, `grep -n '...' docs.md`) a quoted string is data,
* unless it is a runtime given an eval flag (see CODE_EVALUATORS).
*/
const COMMAND_WRAPPERS = new Set([
'sh',
'bash',
'zsh',
'dash',
'ksh',
'fish',
'busybox',
'eval',
'exec',
'command',
'xargs',
'sudo',
'doas',
'su',
'env',
'nice',
'ionice',
'nohup',
'timeout',
'time',
'watch',
'flock',
'ssh',
'script',
'csh',
'tcsh',
'setsid',
'stdbuf',
'taskset',
'chrt',
'unshare',
'chroot',
'runuser',
'npx',
'bunx',
'pnpx',
// Runs a command line for each input line; find and fd, which do so only
// after one of their exec flags, are in LAUNCHERS.
'parallel',
// Shell builtins and zsh precommand modifiers that run a command line, or
// keep one to run later (`trap '...' EXIT`, `alias x='...'`).
'builtin',
'noglob',
'nocorrect',
'trap',
'alias',
]);

// Git config section and variable names are case-insensitive
// (subsection names are case-sensitive but core.hooksPath has none),
// so we normalize the candidate token to lowercase before matching.
Expand Down Expand Up @@ -149,7 +208,11 @@ function tokenizeShellWords(input, start = 0, end = input.length) {
continue;
}

if (/\s/.test(char)) {
// Whitespace ends a word; so do the unquoted substitution delimiters,
// which can never be part of a word (`echo "$(git push --no-verify)"`,
// "`git push --no-verify`" used to yield the token `--no-verify)` /
// `--no-verify\``, hiding the flag).
if (/[\s`()]/.test(char)) {
pushToken(i);
continue;
}
Expand Down Expand Up @@ -289,6 +352,221 @@ function isInComment(input, idx) {
return false;
}

/**
* Strip a leading path and a trailing `.exe` from a command word.
*/
function commandBasename(word) {
return String(word || '')
.replace(/^.*[\\/]/, '')
.replace(/\.exe$/i, '')
.toLowerCase();
}

/**
* Runtimes that run a quoted argument as program source, each with the
* flags that do it: `node -e`, `python3 -c`, `perl -E`, `php -r`,
* `deno eval`. That source can spawn git itself, so it stays subject to the
* guard. The same runtime without one of its own eval flags receives a
* script path and arguments, which are data (`node cli.js 'git commit
* --no-verify'`).
*
* The flags are per runtime because the same letter means different things:
* node's `-r` preloads a module and leaves the rest of the command line as
* ordinary arguments, while php's `-r` is how php is handed code.
*/
const CODE_EVALUATORS = new Map([
['node', ['-e', '--eval', '-p', '--print']],
['nodejs', ['-e', '--eval', '-p', '--print']],
['bun', ['-e', '--eval', '-p', '--print']],
['deno', ['-e', '--eval', 'eval']],
['python', ['-c']],
['python2', ['-c']],
['python3', ['-c']],
['pythonw', ['-c']],
['perl', ['-e', '-E']],
['ruby', ['-e']],
['php', ['-r']],
['lua', ['-e']],
['luajit', ['-e']],
['rscript', ['-e']],
['osascript', ['-e']],
['groovy', ['-e']],
['julia', ['-e', '-E']],
['elixir', ['-e']],
['erl', ['-eval']],
['expect', ['-c']],
]);

/**
* Launchers that run another program given after one of their flags:
* `find . -exec CMD ARGS \;`, `fd -x CMD ARGS`. A quoted argument of the
* launched program is judged as that program's own, so `-exec grep '...'`
* searches and `-exec sh -c '...'` runs. After find's `;` or `{} +` the
* arguments are find's again.
*/
const LAUNCHERS = new Map([
['find', ['-exec', '-execdir', '-ok', '-okdir']],
['fd', ['-x', '--exec', '-X', '--exec-batch']],
['fdfind', ['-x', '--exec', '-X', '--exec-batch']],
]);

const EXEC_TERMINATORS = new Set(['\\;', "';'", '";"']);

/**
* Runtimes whose first operand is itself program source, with no eval flag:
* `awk 'BEGIN { system("git commit --no-verify") }'` runs git. Every quoted
* argument they receive stays subject to the guard, at the cost of also
* checking an awk pattern that merely mentions a bypass flag.
*/
const SOURCE_OPERAND_RUNTIMES = new Set(['awk', 'gawk', 'mawk', 'nawk']);

/**
* Whether a quoted argument is data for the program that receives it.
* `words` runs from that program's name up to the argument. An eval flag is
* matched as a whole word, or as the `=` form of itself, so a path that
* happens to end in one of them cannot qualify.
*/
function receivesAsData(words) {
// A program named by an expansion is only known when the line runs.
if (/[$`]/.test(words[0])) return false;
const base = commandBasename(words[0]);
if (base === 'git' || COMMAND_WRAPPERS.has(base) || SOURCE_OPERAND_RUNTIMES.has(base)) return false;
const launchFlags = LAUNCHERS.get(base);
if (launchFlags !== undefined) {
const at = words.findLastIndex((word) => launchFlags.includes(word));
if (at === -1) return true;
const launched = words.slice(at + 1);
if (launched.some((word, i) => EXEC_TERMINATORS.has(word) || (word === '+' && launched[i - 1] === '{}'))) {
return true;
}
// The quoted argument is the launched program's name itself.
if (launched.length === 0) return false;
return receivesAsData([launched[0].replace(/['"\\]/g, ''), ...launched.slice(1)]);
}
const flags = CODE_EVALUATORS.get(base);
if (flags === undefined) return true;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`)));
}

/**
* Whether a statement's first word sits right inside or right after a
* substitution. `$(echo '...')` runs what echo prints, `source <(echo '...')`
* reads it as a script, and in `$(command -v sh) -c '...'` the program is only
* known when the line runs.
*/
function startsAtSubstitution(input, argv0Start) {
let i = argv0Start - 1;
while (i >= 0 && /\s/.test(input.charAt(i))) i--;
const char = input.charAt(i);
if (char === '`' || char === ')') return true;
return char === '(' && /[$<>]/.test(input.charAt(i - 1));
}

/**
* Whether a program reads the text piped into it as code: a shell or command
* wrapper (`| sh`, `| xargs sh -c`), a runtime with no script operand of its
* own (`| node`, `| python3 -`), or a program named by an expansion.
*/
function readsCodeFromStdin(words) {
if (/[$`]/.test(words[0])) return true;
const base = commandBasename(words[0]);
if (COMMAND_WRAPPERS.has(base)) return true;
if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-'));
return false;
}

/**
* Whether the separator at `i` ends a statement instead of joining the next
* command to it: `;`, a newline, `&&`, `||` or a background `&`. A pipe (`|`,
* `|&`) joins, and so does the `&` of a redirection (`2>&1`, `>&2`, `&>`).
*/
function endsStatement(input, i) {
const char = input.charAt(i);
if (char === ';' || char === '\n') return true;
if (char === '|') return input.charAt(i + 1) === '|';
if (char !== '&') return false;
const before = input.charAt(i - 1);
return before !== '>' && before !== '<' && before !== '|' && input.charAt(i + 1) !== '>';
}

/**
* Whether the command line before `end` holds anything that can carry the
* output of a finished statement into a later pipe: a brace group or
* subshell (`{ echo '...'; } | sh`), a function body called later on, a
* compound command (`if ...; fi | sh`) or a substitution. Quoted text does
* not count, and neither does a brace inside a word, which is brace or
* parameter expansion (`/tmp/{a,b}`, `${HOME}`): a brace group opens with
* `{` as a word of its own.
*/
function mayGroupStatements(input, end) {
let bare = '';
let pos = 0;
for (const region of quotedRegions(input)) {
if (region.start >= end) break;
bare += `${input.slice(pos, region.start)} `;
pos = region.end + 1;
}
bare += input.slice(pos, end);
return /[()`]/.test(bare) || bare.split(/[\s;&|]+/).some((word) => SHELL_RESERVED_WORDS.has(word));
}

/**
* Whether a later part of the command line pipes into a program that reads
* what it receives as code (`echo '...' | sh`). Every later pipe counts, not
* only the rest of this pipeline, so a group such as `{ echo '...'; } | sh`
* is covered as well. When nothing before a statement's end can group it
* with later commands, its output stops there: in
* `echo '...'; printf x | sh` only `printf x` reaches `sh`.
*/
function pipesIntoCodeReader(input, from) {
let pos = from;
let grouped = false;
while (pos < input.length) {
const end = findCommandSegmentEnd(input, pos);
if (end >= input.length) return false;
// The prefix only grows, so once it can group statements it always can.
if (!grouped && endsStatement(input, end)) {
if (!mayGroupStatements(input, end)) return false;
grouped = true;
}
pos = end + 1;
if (input.charAt(end) !== '|') continue;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if (input.charAt(pos) === '|') {
pos += 1;
continue;
}
if (input.charAt(pos) === '&') pos += 1;
// A newline right after a pipe continues the pipeline.
while (/\s/.test(input.charAt(pos))) pos += 1;
const words = tokenizeShellWords(input, pos, findCommandSegmentEnd(input, pos))
.map((token) => token.value)
.filter((word) => !ASSIGNMENT_WORD.test(word));
if (words.length > 0 && readsCodeFromStdin(words)) return true;
}
return false;
}

/**
* A `git` inside a quoted string is only a command when that string is
* handed to something that executes it: a shell or process wrapper, or a
* runtime given an eval flag. Otherwise it is an argument of an unrelated
* program (a CLI under test, printf, grep, a script path, ...) and must not
* be inspected for bypass flags. A double-quoted string that contains a
* command substitution (`"$(git ...)"`, "`git ...`") runs git before any
* program receives it, so it is never data. Nor is a string whose program
* prints it into something that runs it: a pipe into a shell, or a
* substitution whose output is run or sourced.
*/
function isQuotedDataArgument(input, idx) {
const region = quotedRegionAt(input, idx);
if (region === null || region.argv0 === '') return false;
if (region.substitution) return false;
if (startsAtSubstitution(input, region.argv0Start)) return false;
if (pipesIntoCodeReader(input, region.end + 1)) return false;
const words = input.slice(region.argv0Start, region.start).split(/\s+/).filter(Boolean);
return receivesAsData([region.argv0, ...words.slice(1)]);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

/**
* Find the next 'git' token in the input starting from a position.
*/
Expand All @@ -307,7 +585,9 @@ function findGit(input, start) {
}

const before = idx > 0 ? input[idx - 1] : ' ';
if (VALID_BEFORE_GIT.includes(before)) return { idx, len };
if (VALID_BEFORE_GIT.includes(before) && !isQuotedDataArgument(input, idx)) {
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return { idx, len };
}
pos = idx + 1;
}
return null;
Expand Down Expand Up @@ -403,19 +683,31 @@ function isNoVerifyLongFlag(value) {
return value.length >= '--no-v'.length && '--no-verify'.startsWith(value);
}

/**
* A flag inside a code payload is followed by the punctuation that closes the
* call (`execSync("git push --no-verify")`), and the word tokenizer keeps that
* punctuation in the token. When the payload goes on after the call, the
* closing quote reads to the tokenizer as an opening one, and the rest of the
* payload lands in the same token (`system("git push --no-verify") }`). Keep
* the part before the first such character; a real flag contains none.
*/
function flagToken(value) {
return value.replace(/[)\]}'"`;,\s][\s\S]*$/, '');
}

/**
* Check if the input contains a --no-verify flag for a specific git command.
* Only inspects the portion of the input starting at `offset` (the position
* right after the detected subcommand keyword) so that flags belonging to
* earlier commands in a chain are not falsely matched.
*/
function hasNoVerifyFlag(input, command, offset) {
const segmentEnd = findCommandSegmentEnd(input, offset);
function hasNoVerifyFlag(input, command, offset, limit = input.length) {
const segmentEnd = Math.min(findCommandSegmentEnd(input, offset), limit);
const tokens = tokenizeShellWords(input, offset, segmentEnd);
let skipNext = false;

for (const token of tokens) {
const value = token.value;
const value = flagToken(token.value);

if (skipNext) {
skipNext = false;
Expand Down Expand Up @@ -497,7 +789,13 @@ function checkCommand(input) {
};
}

if (hasNoVerifyFlag(input, gitCommand, offset)) {
// A git command line inside a quoted string (`sh -c 'git push ...'`)
// ends with that string: scanning past the closing quote would read the
// rest of the outer statement in the wrong quote state, so `sh -c 'git
// push --no-verify'; echo done` glued `; echo done` onto the flag token.
const region = quotedRegionAt(input, detected.gitStart);
const limit = region === null ? input.length : region.end;
if (hasNoVerifyFlag(input, gitCommand, offset, limit)) {
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return {
blocked: true,
reason: `BLOCKED: --no-verify flag is not allowed with git ${gitCommand}. Git hooks must not be bypassed.`,
Expand Down
Loading
Loading