diff --git a/scripts/hooks/block-no-verify.js b/scripts/hooks/block-no-verify.js index 16e0044d7fd..4fb7c548a01 100644 --- a/scripts/hooks/block-no-verify.js +++ b/scripts/hooks/block-no-verify.js @@ -15,6 +15,16 @@ 'use strict'; +const { quotedRegionAt, commandStatements, ASSIGNMENT_WORD } = require('../lib/shell-quotes'); +const { + startsAtSubstitution, + statementBounds, + endsStatement, + mayGroupStatements, +} = require('../lib/shell-statements'); +const { receivesAsData, sedArguments, readsCodeFromStdin } = require('../lib/code-receivers'); +const { sedScriptTexts, sedExecution } = require('../lib/sed-script'); + const MAX_STDIN = 1024 * 1024; let raw = ''; @@ -149,7 +159,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; } @@ -289,6 +303,78 @@ function isInComment(input, idx) { return false; } +/** + * The commands the sed scripts in `input` run, from every statement that runs + * sed. A script that only mentions a bypass flag, in a pattern or a text it + * does not run, adds nothing, and neither does an input file name. + */ +function sedExecutedCommands(input) { + return commandStatements(input).flatMap(({ argv0Start }) => { + const { end, opaque } = statementBounds(input, argv0Start); + const words = tokenizeShellWords(input, argv0Start, end).map((token) => token.value); + const args = sedArguments(words); + if (args === null) return []; + return sedScriptTexts(args, opaque).flatMap((script) => sedExecution(script).commands); + }); +} + +/** + * 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; + 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)]); +} + /** * Find the next 'git' token in the input starting from a position. */ @@ -307,7 +393,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)) { + return { idx, len }; + } pos = idx + 1; } return null; @@ -403,19 +491,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; @@ -482,6 +582,14 @@ function hasHooksPathOverride(input, detected) { * Check a command string for git hook bypass attempts. */ function checkCommand(input) { + // sed runs these through a shell, and inside its script they are glued to + // the delimiters (`s/x/git push --no-verify/e`), so they are checked as the + // command lines they are. + for (const command of sedExecutedCommands(input)) { + const result = checkCommand(command); + if (result.blocked) return result; + } + let start = 0; while (start < input.length) { @@ -497,7 +605,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)) { return { blocked: true, reason: `BLOCKED: --no-verify flag is not allowed with git ${gitCommand}. Git hooks must not be bypassed.`, diff --git a/scripts/lib/code-receivers.js b/scripts/lib/code-receivers.js new file mode 100644 index 00000000000..56eddf07634 --- /dev/null +++ b/scripts/lib/code-receivers.js @@ -0,0 +1,194 @@ +'use strict'; + +/** + * Which programs run the text they receive as code: a quoted argument + * (`sh -c '...'`, `node -e '...'`, `awk '...'`), or what is piped into them + * (`| sh`, `| python3 -`, `| sed e`). + */ + +const { SED_PROGRAMS, sedScriptTexts, sedExecution } = require('./sed-script'); + +/** + * 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', +]); + +/** + * 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; + return !words.some((word) => flags.some((flag) => word === flag || word.startsWith(`${flag}=`))); +} + +/** + * The arguments sed receives in a statement, or null when the statement does + * not run sed: `sed ARGS`, or sed behind a wrapper (`sudo sed ARGS`). + */ +function sedArguments(words) { + const base = commandBasename(words[0]); + if (SED_PROGRAMS.has(base)) return words.slice(1); + if (!COMMAND_WRAPPERS.has(base)) return null; + const at = words.findIndex((word) => SED_PROGRAMS.has(commandBasename(word))); + return at === -1 ? null : words.slice(at + 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 -`), sed with a script that runs its input + * (`| sed e`), 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 (SED_PROGRAMS.has(base)) { + const opaque = words.some((word) => /[$`]/.test(word)); + return sedScriptTexts(words.slice(1), opaque).some((script) => sedExecution(script).runsInput); + } + if (CODE_EVALUATORS.has(base)) return words.slice(1).every((word) => word.startsWith('-')); + return false; +} + +module.exports = { COMMAND_WRAPPERS, commandBasename, receivesAsData, sedArguments, readsCodeFromStdin }; diff --git a/scripts/lib/sed-script.js b/scripts/lib/sed-script.js new file mode 100644 index 00000000000..490ed24538d --- /dev/null +++ b/scripts/lib/sed-script.js @@ -0,0 +1,238 @@ +'use strict'; + +/** + * GNU sed, as far as a command guard needs it: which of sed's arguments are + * its scripts, and what a script runs through a shell. The `e` command and + * the `e` flag of `s` run a command line; nothing else in a script does. + */ + +const SED_PROGRAMS = new Set(['sed', 'gsed']); + +/** + * The scripts in sed's arguments, read as GNU sed's option parser reads them: + * each `-e`/`--expression` value, or else the first operand. The other + * operands are input files, and a script named with `-f` is not on the line. + * When the shell may still change the words (`$OPTS`, a substitution), every + * operand may be the script. + */ +function sedScripts(args, everyOperand = false) { + const scripts = []; + const operands = []; + let scriptOption = false; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === '--') { + operands.push(...args.slice(i + 1)); + break; + } + if (arg.startsWith('--')) { + // A long option may be shortened to any prefix that names only it. + const [name, value] = arg.slice(2).split(/=(.*)/s); + if ('expression'.startsWith(name)) { + scripts.push(value ?? args[++i] ?? ''); + scriptOption = true; + } else if (name.length >= 2 && 'file'.startsWith(name)) { + scriptOption = true; + if (value === undefined) i++; + } else if ('line-length'.startsWith(name) && value === undefined) { + i++; + } + continue; + } + if (arg.startsWith('-') && arg !== '-') { + for (let j = 1; j < arg.length; j++) { + const option = arg[j]; + // -i takes the rest of the word as its backup suffix: `-ie` is -i with suffix e. + if (option === 'i') break; + if (option !== 'e' && option !== 'f' && option !== 'l') continue; + const value = j + 1 < arg.length ? arg.slice(j + 1) : args[++i]; + if (option === 'e') scripts.push(value ?? ''); + if (option !== 'l') scriptOption = true; + break; + } + continue; + } + operands.push(arg); + } + if (everyOperand) return [...scripts, ...operands]; + if (!scriptOption && operands.length > 0) scripts.push(operands[0]); + return scripts; +} + +/** + * The texts to read as sed scripts, each on its own. sed joins its scripts + * with newlines into one; when the shell may still change the words, every + * operand is read as a script of its own. + */ +function sedScriptTexts(args, opaque) { + return opaque ? sedScripts(args, true) : [sedScripts(args).join('\n')]; +} + +/** Past the spaces and tabs at `i`. */ +function skipBlanks(script, i) { + while (script[i] === ' ' || script[i] === '\t') i++; + return i; +} + +/** + * One part of a sed `s` or `y` command or of a regex address, from `start` up + * to the next unescaped `delimiter`. An escaped delimiter stands for itself. + * sed rejects a part that an unescaped newline cuts short. + */ +function sedPart(script, start, delimiter) { + let text = ''; + for (let i = start; i < script.length; i++) { + const char = script[i]; + if (char === '\\' && i + 1 < script.length) { + text += script[i + 1] === delimiter ? delimiter : char + script[i + 1]; + i++; + continue; + } + if (char === delimiter) return { text, end: i }; + if (char === '\n') return null; + text += char; + } + return null; +} + +/** + * Past the sed address at `i`, if there is one: a line number (`3`, `0~4`), + * `$`, a regex (`/re/I`, `\%re%`) or, as the second address, `+N` or `~N`. + */ +function sedAddressEnd(script, i, second) { + const char = script[i]; + if (char === '/' || char === '\\') { + const delimiter = char === '\\' ? script[i + 1] : char; + const regex = sedPart(script, char === '\\' ? i + 2 : i + 1, delimiter); + if (regex === null) return script.length; + i = skipBlanks(script, regex.end + 1); + while (script[i] === 'I' || script[i] === 'M') i = skipBlanks(script, i + 1); + return i; + } + if (char === '$') return i + 1; + if (!/[0-9]/.test(char || '') && !(second && (char === '+' || char === '~'))) return i; + if (!/[0-9]/.test(char)) i = skipBlanks(script, i + 1); + while (/[0-9]/.test(script[i] || '')) i++; + const step = skipBlanks(script, i); + if (second || script[step] !== '~') return i; + i = skipBlanks(script, step + 1); + while (/[0-9]/.test(script[i] || '')) i++; + return i; +} + +/** + * The end of the text of an `a`, `i`, `c` or `e` command: the first newline + * that no backslash escapes. A backslash before a newline carries the text on. + */ +function sedTextEnd(script, i) { + for (; i < script.length; i++) { + if (script[i] === '\\') i++; + else if (script[i] === '\n') return i; + } + return script.length; +} + +/** + * sed's text as the shell running it reads it: escaped characters stand for + * themselves, and a backslash before a newline joins the two lines. + */ +function sedUnescape(text) { + return text.replace(/\\\n/g, '').replace(/\\([\s\S])/g, (match, char) => (char === 'n' ? '\n' : char)); +} + +// Commands whose argument runs to the end of the line: a comment and a file name. +const SED_LINE_COMMANDS = new Set(['#', 'r', 'R', 'w', 'W']); + +// Commands that take text, which the next newline without a backslash ends. +const SED_TEXT_COMMANDS = new Set(['a', 'i', 'c', 'e']); + +// Commands that take a label or a version, which a blank or `;` ends. +const SED_LABEL_COMMANDS = new Set([':', 'b', 't', 'T', 'v']); + +/** The end of the line that `i` is on. */ +function lineEnd(script, i) { + const end = script.indexOf('\n', i); + return end === -1 ? script.length : end; +} + +/** Past a command's addresses and any `!`, to its command letter. */ +function sedCommandStart(script, i) { + i = skipBlanks(script, sedAddressEnd(script, i, false)); + if (script[i] === ',') i = skipBlanks(script, sedAddressEnd(script, skipBlanks(script, i + 1), true)); + while (script[i] === '!') i = skipBlanks(script, i + 1); + return i; +} + +/** + * The text of an `a`, `i`, `c` or `e` command, from `i` after its letter: past + * blanks and one backslash. An `e` command's text is recorded in `found`: the + * command it runs, or, with no text, the pattern space. Returns where it ends. + */ +function readSedText(script, i, command, found) { + i = skipBlanks(script, i); + if (script[i] === '\\') i += script[i + 1] === '\n' ? 2 : 1; + const end = sedTextEnd(script, i); + if (command === 'e') { + const text = sedUnescape(script.slice(i, end)).trim(); + if (text === '') found.runsInput = true; + else found.commands.push(text); + } + return end; +} + +/** + * An `s` or `y` command from its delimiter at `i`. An `s` command with the `e` + * flag runs its replacement, and the text sed reads with it, which `found` + * records. Returns where the command ends, or -1 when a part is not closed: + * sed then rejects the whole script and runs none of it. + */ +function readSedSubstitution(script, i, command, found) { + const delimiter = script[i]; + const pattern = delimiter === undefined ? null : sedPart(script, i + 1, delimiter); + const replacement = pattern && sedPart(script, pattern.end + 1, delimiter); + if (!replacement) return -1; + i = replacement.end + 1; + if (command === 'y') return i; + const flags = /^[gpiImMe0-9]*/.exec(script.slice(i))[0]; + i += flags.length; + if (script[i] === 'w') i = lineEnd(script, i); + if (flags.includes('e')) { + found.commands.push(sedUnescape(replacement.text)); + found.runsInput = true; + } + return i; +} + +/** The command whose letter is at `i`. Returns where it ends, or -1 (see above). */ +function readSedCommand(script, i, found) { + const command = script[i]; + const next = i + 1; + if (SED_LINE_COMMANDS.has(command)) return lineEnd(script, next); + if (SED_TEXT_COMMANDS.has(command)) return readSedText(script, next, command, found); + if (command === 's' || command === 'y') return readSedSubstitution(script, next, command, found); + if (!SED_LABEL_COMMANDS.has(command)) return next; + let end = skipBlanks(script, next); + while (end < script.length && !/[\s;]/.test(script[end])) end++; + return end; +} + +/** + * What a sed script runs through a shell (GNU sed). An `s` command with the + * `e` flag runs the pattern space once the replacement is made, and an `e` + * command runs its text, or the pattern space when it has none. The script is + * read command by command, as sed reads it, so the text `a`, `i` and `c` add, + * a comment, a label or a file name is never taken for a command. `commands` + * holds the command text the script itself supplies; `runsInput` says the text + * sed reads is run too. + */ +function sedExecution(script) { + const found = { commands: [], runsInput: false }; + let i = 0; + while (i >= 0 && i < script.length) { + if (/[\s;]/.test(script[i])) i++; + else i = readSedCommand(script, sedCommandStart(script, i), found); + } + return found; +} + +module.exports = { SED_PROGRAMS, sedScripts, sedScriptTexts, sedExecution }; diff --git a/scripts/lib/shell-quotes.js b/scripts/lib/shell-quotes.js new file mode 100644 index 00000000000..2077e11d3e6 --- /dev/null +++ b/scripts/lib/shell-quotes.js @@ -0,0 +1,240 @@ +'use strict'; + +/** + * Quoted-region scanner for shell command lines. + * + * One forward pass records every quoted region: where it starts and ends, the + * argv0 of the statement containing it (the first non-assignment, non-reserved + * word before the quote; '' when the quote is part of that first word, with + * `argv0Start` holding its offset so a caller can read the words in between) + * and whether the string carries a command substitution. A `$(` or backtick inside + * "..." suspends the string: the substitution body is top-level shell again + * (its own statements and quotes) until the matching `)` / backtick, after + * which the string resumes as a new region. Both halves are flagged + * `substitution`. Regions are appended only once complete, in order, so they + * are disjoint and sorted. The same pass records where each statement's argv0 + * starts, quoted or not. The result is cached per input, so a command line + * holding thousands of quoted tokens is scanned once. + */ + +// Words that open or structure a compound command; none of them receives the +// quoted string that follows, so none may become a statement's argv0. +const SHELL_RESERVED_WORDS = new Set([ + 'if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'for', + 'case', 'esac', 'in', 'select', 'function', 'coproc', '!', '{', '}', '[[', ']]', +]); + +const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/; + +// Unquoted characters that start a new statement (or a nested command). +const STATEMENT_SEPARATORS = new Set([';', '|', '&', '\n', '(', ')', '`']); + +let cache = { input: null, regions: [], statements: [] }; + +function createState() { + return { + regions: [], + statements: [], + suspended: [], + quote: null, + escaped: false, + open: null, + argv0: null, + argv0Start: -1, + word: '', + wordStart: -1, + inWord: false, + }; +} + +function startWord(state, index) { + if (!state.inWord) state.wordStart = index; + state.inWord = true; +} + +function endWord(state) { + if (!state.inWord) return; + if ( + state.argv0 === null && + state.word !== '' && + !SHELL_RESERVED_WORDS.has(state.word) && + !ASSIGNMENT_WORD.test(state.word) + ) { + state.argv0 = state.word; + state.argv0Start = state.wordStart; + state.statements.push({ argv0: state.argv0, argv0Start: state.argv0Start }); + } + state.word = ''; + state.inWord = false; +} + +function newStatement(state) { + endWord(state); + state.argv0 = null; + state.argv0Start = -1; +} + +function openRegion(state, start, quote, argv0, argv0Start, substitution) { + state.quote = quote; + state.open = { start, quote, argv0, argv0Start, substitution }; +} + +function closeRegion(state, end, substitution) { + const region = state.open; + state.regions.push({ ...region, end, substitution: region.substitution || substitution }); + state.open = null; + state.quote = null; +} + +/** + * `$(` or a backtick inside "...": park the outer statement's word state (the + * outer word `FOO="pre$(cmd)post"` continues after the substitution as if it + * were a single character) and scan the body as a fresh statement. Returns + * the number of characters consumed. + */ +function suspendString(state, index, char) { + state.suspended.push({ + backtick: char === '`', + depth: 0, + argv0: state.open.argv0, + argv0Start: state.open.argv0Start, + outer: { word: state.word, inWord: state.inWord, argv0: state.argv0 }, + }); + closeRegion(state, index, true); + state.word = ''; + state.inWord = false; + state.argv0 = null; + return char === '$' ? 2 : 1; +} + +function resumeString(state, index, outer) { + state.suspended.pop(); + state.word = outer.outer.word; + state.inWord = outer.outer.inWord; + state.argv0 = outer.outer.argv0; + openRegion(state, index, '"', outer.argv0, outer.argv0Start, true); +} + +/** A character inside a quoted string. Returns the number of characters consumed. */ +function scanQuotedChar(state, input, index) { + const char = input.charAt(index); + if (state.quote === '"' && char === '\\') { + state.escaped = true; + return 1; + } + if (char === state.quote) { + closeRegion(state, index, false); + return 1; + } + if (state.quote === '"' && (char === '`' || (char === '$' && input.charAt(index + 1) === '('))) { + return suspendString(state, index, char); + } + state.word += char; + state.inWord = true; + return 1; +} + +/** A character outside quotes. Returns the number of characters consumed. */ +function scanBareChar(state, index, char) { + if (char === '\\') { + state.escaped = true; + startWord(state, index); + return 1; + } + if (char === '"' || char === "'") { + startWord(state, index); + openRegion(state, index, char, state.argv0 === null ? '' : state.argv0, state.argv0Start, false); + return 1; + } + const outer = state.suspended.length > 0 ? state.suspended[state.suspended.length - 1] : null; + if (outer !== null) { + const resumes = outer.backtick ? char === '`' : char === ')' && outer.depth === 0; + if (resumes) { + resumeString(state, index, outer); + return 1; + } + if (!outer.backtick && (char === '(' || char === ')')) { + const depth = outer.depth + (char === '(' ? 1 : -1); + state.suspended = [...state.suspended.slice(0, -1), { ...outer, depth }]; + } + } + if (STATEMENT_SEPARATORS.has(char)) { + newStatement(state); + return 1; + } + if (/\s/.test(char)) { + endWord(state); + return 1; + } + state.word += char; + startWord(state, index); + return 1; +} + +function scan(input) { + if (cache.input === input) return cache; + const state = createState(); + for (let i = 0; i < input.length; ) { + const char = input.charAt(i); + if (state.escaped) { + state.escaped = false; + state.word += char; + state.inWord = true; + i += 1; + continue; + } + i += state.quote ? scanQuotedChar(state, input, i) : scanBareChar(state, i, char); + } + if (state.open !== null) state.regions.push({ ...state.open, end: input.length }); + cache = { input, regions: state.regions, statements: state.statements }; + return cache; +} + +/** + * Every quoted region of `input`, sorted by start and disjoint. + * + * @param {string} input + * @returns {Array<{start: number, end: number, quote: string, argv0: string, argv0Start: number, substitution: boolean}>} + */ +function quotedRegions(input) { + return scan(input).regions; +} + +/** + * Every statement of `input` whose argv0 ends before the input does, with + * the offset where that argv0 starts: top-level statements and those inside a + * substitution alike. + * + * @param {string} input + * @returns {Array<{argv0: string, argv0Start: number}>} + */ +function commandStatements(input) { + return scan(input).statements; +} + +/** + * The quoted region that strictly contains `idx`, or null when `idx` is not + * inside a quote. Regions are disjoint and sorted, so this is a binary search. + * + * @param {string} input + * @param {number} idx + */ +function quotedRegionAt(input, idx) { + const regions = quotedRegions(input); + let lo = 0; + let hi = regions.length - 1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + const region = regions[mid]; + if (idx <= region.start) { + hi = mid - 1; + } else if (idx >= region.end) { + lo = mid + 1; + } else { + return region; + } + } + return null; +} + +module.exports = { quotedRegions, quotedRegionAt, commandStatements, SHELL_RESERVED_WORDS, ASSIGNMENT_WORD }; diff --git a/scripts/lib/shell-statements.js b/scripts/lib/shell-statements.js new file mode 100644 index 00000000000..b29a2395e3b --- /dev/null +++ b/scripts/lib/shell-statements.js @@ -0,0 +1,104 @@ +'use strict'; + +/** + * Where a shell statement ends, and what can tie it to the commands after it, + * for a guard that reads a command line without running a shell. + */ + +const { quotedRegions, SHELL_RESERVED_WORDS } = require('./shell-quotes'); + +/** + * 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)); +} + +/** + * Where the statement that starts at `start` ends: at an unquoted `;`, `|`, + * `&` or newline, or at a `)` that closes the substitution or subshell around + * it. A substitution inside the statement is part of it. `opaque` says the + * shell may still change the statement's words: a parameter expansion or a + * substitution in them. + */ +function statementBounds(input, start) { + let quote = null; + let opaque = false; + let depth = 0; + let backtick = false; + for (let i = start; i < input.length; i++) { + const char = input.charAt(i); + if (quote === "'") { + if (char === "'") quote = null; + continue; + } + if (char === '\\') { + i++; + continue; + } + if (char === '$' && /[\w{(@*#?$!-]/.test(input.charAt(i + 1))) opaque = true; + if (char === '`') { + // A backtick that closes a substitution around the statement reads as + // opening one, so the rest of the line counts: more operands, not fewer. + opaque = true; + backtick = !backtick; + } else if (quote === '"') { + if (char === '"') quote = null; + } else if (char === "'" || char === '"') { + quote = char; + } else if (char === '(') { + opaque = true; + depth++; + } else if (char === ')') { + if (depth === 0) return { end: i, opaque }; + depth--; + } else if (depth === 0 && !backtick && /[;|&\n]/.test(char)) { + return { end: i, opaque }; + } + } + return { end: input.length, opaque }; +} + +/** + * 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)); +} + +module.exports = { startsAtSubstitution, statementBounds, endsStatement, mayGroupStatements }; diff --git a/tests/hooks/block-no-verify.test.js b/tests/hooks/block-no-verify.test.js index 8b07d5f00f2..5d63e867f2e 100644 --- a/tests/hooks/block-no-verify.test.js +++ b/tests/hooks/block-no-verify.test.js @@ -251,6 +251,392 @@ if (test('allows --no-verbose (not a prefix of --no-verify)', () => { assert.strictEqual(r.code, 0, `expected exit 0, got ${r.code}: ${r.stderr}`); })) passed++; else failed++; +// --- A git command line quoted as an argument to another program is data --- + +if (test('allows a quoted git command line passed as an argument to another program', () => { + for (const command of [ + "node /tmp/cli.js 'git commit --no-verify -m x'", + 'node /tmp/cli.js "git push --no-verify"', + "printf '%s' 'git commit --no-verify -m x' | node /tmp/x.js", + "python3 /tmp/check.py 'git commit --no-verify'", + "node /tmp/cli.js --expect 'git push --no-verify'", + "grep -n 'git commit --no-verify' docs/hooks.md", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// A runtime given an eval flag executes its quoted argument as source, so a +// bypass in that source runs git for real and stays blocked. +if (test('blocks a git bypass inside a runtime eval payload', () => { + for (const command of [ + 'node -e "require(\'child_process\').execSync(\'git commit --no-verify -m x\')"', + "node -e 'require(\"child_process\").execSync(\"git push --no-verify\")'", + 'node --eval="git commit --no-verify -m x"', + 'node -p "cp.execSync(\'git push --no-verify\')"', + "python3 -c 'import os; os.system(\"git push --no-verify\")'", + "perl -e 'system(\"git commit --no-verify -m x\")'", + "ruby -e 'system(\"git push --no-verify\")'", + "php -r 'shell_exec(\"git commit --no-verify -m x\");'", + 'deno eval "git push --no-verify"', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows a runtime flag that loads code but leaves the quoted argument as data', () => { + for (const command of [ + // node -r preloads a module; the script and its arguments stay data. + "node -r setup.js cli.js 'git push --no-verify'", + 'node --require ts-node/register cli.js "git commit --no-verify -m x"', + "ruby -r./setup cli.rb 'git push --no-verify'", + "python3 -B check.py 'git commit --no-verify'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks each runtime through its own eval flag', () => { + for (const command of [ + 'node -p "cp.execSync(\'git push --no-verify\')"', + "php -r 'shell_exec(\"git commit --no-verify -m x\");'", + "perl -E 'system(\"git push --no-verify\")'", + "lua -e 'os.execute(\"git commit --no-verify -m x\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +// find, fd and parallel run a command line of their own for each file or +// input line; a quoted git handed to them runs for real. +if (test('blocks a quoted git command line run by find, fd or parallel', () => { + for (const command of [ + "find . -exec sh -c 'git commit --no-verify -m x' \\;", + "find . -name '*.md' -execdir bash -c 'git push --no-verify' \\;", + "fd -e md -x sh -c 'git commit -n -m x'", + "find . -exec 'sh' -c 'git commit --no-verify -m x' \\;", + "parallel 'git push --no-verify {}' ::: origin upstream", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +// Without one of their exec flags, find and fd only search for or print a +// quoted operand. +if (test('allows a bypass phrase that find or fd only searches for or prints', () => { + for (const command of [ + "find . -name 'git commit --no-verify'", + "find . -type f -printf 'git push --no-verify %p\\n'", + "fd 'git push --no-verify' docs", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// A program that find or fd launches decides for itself: grep searches for a +// quoted phrase, a shell runs it. After find's `;` the arguments are find's. +if (test('allows a bypass phrase that a program run by find or fd searches for', () => { + for (const command of [ + "find . -exec grep 'git push --no-verify' {} \\;", + "find . -name '*.md' -exec grep -l 'git commit --no-verify' {} +", + "fd -e md -x grep 'git push --no-verify'", + "find . -exec sh -c 'echo {}' \\; -name 'git commit --no-verify'", + "find . -exec sh -c 'echo {}' ';' -name 'git push --no-verify'", + "find . -exec sh -c 'ls \"$@\"' sh {} + -name 'git push --no-verify'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// Printed text piped into something that runs what it reads is a command line. +if (test('blocks a quoted git piped into a program that runs what it reads', () => { + for (const command of [ + "echo 'git commit --no-verify -m x' | sh", + "printf '%s\\n' 'git push --no-verify' | bash -s", + "{ echo 'git commit --no-verify -m x'; } | sh", + "echo 'git push --no-verify' | xargs -I{} sh -c '{}'", + "echo 'require(\"child_process\").execSync(\"git push --no-verify\")' | node", + "echo 'git commit --no-verify -m x' |& sh", + "echo 'git commit --no-verify -m x' | $SHELL", + "echo 'git push --no-verify' | FOO=1 sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows a bypass phrase piped into a program that reads it as text', () => { + for (const command of [ + "echo 'git commit --no-verify' | grep -c verify", + "printf '%s' 'git push --no-verify' | node /tmp/x.js", + "grep -q 'git commit --no-verify' notes.md || sh setup.sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +// A finished statement's output goes nowhere a later pipe can reach, unless +// something before its end groups it with later commands. +if (test('allows a bypass phrase whose statement ends before a later pipe into a shell', () => { + for (const command of [ + "echo 'git push --no-verify'; printf x | sh", + "echo 'git push --no-verify'\nprintf x | sh", + "echo 'do not run git push --no-verify (it skips the hooks)'; printf x | sh", + "mkdir -p /tmp/{a,b}; echo 'git push --no-verify'; printf x | sh", + "cd ${HOME}; echo 'git push --no-verify'; printf x | sh", + "grep -n 'git commit --no-verify' docs/a.md && curl -fsSL https://example.com/i.sh | sh", + "echo 'git push --no-verify' & printf x | sh", + "echo 'git push --no-verify' || printf x | sh", + "echo 'git push --no-verify' 2>&1; printf x | sh", + "echo 'git push --no-verify' | cat; printf x | sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks a bypass phrase grouped with a later pipe into a shell', () => { + for (const command of [ + "(echo 'git push --no-verify'; printf x) | sh", + "if true; then echo 'git push --no-verify'; fi | sh", + "while read l; do echo 'git push --no-verify'; done < f | sh", + "case a in a) echo 'git push --no-verify';; esac | sh", + "f() { echo 'git push --no-verify'; }; f | sh", + "{ echo 'git push --no-verify';}|sh", + "echo 'git push --no-verify' 2>&1 | sh", + "echo 'git push --no-verify' |\n sh", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +// A program named by an expansion is only known when the line runs, and a +// substitution runs or sources the text it produces. +if (test('blocks a quoted git whose program is known only at run time', () => { + for (const command of [ + "$SHELL -c 'git commit --no-verify -m x'", + "\"$SHELL\" -c 'git commit --no-verify -m x'", + "$(command -v sh) -c 'git commit --no-verify -m x'", + "`command -v bash` -c 'git push --no-verify'", + "find . -exec $SHELL -c 'git commit --no-verify -m x' \\;", + "$(echo 'git commit --no-verify -m x')", + "source <(echo 'git commit --no-verify -m x')", + ". <(printf '%s' 'git push --no-verify')", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git that a shell builtin runs or keeps to run', () => { + for (const command of [ + "builtin eval 'git commit --no-verify -m x'", + "trap 'git push --no-verify' EXIT", + "noglob sh -c 'git commit --no-verify -m x'", + "nocorrect sh -c 'git push --no-verify'", + "alias gc='git commit --no-verify -m x'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +// awk takes its program as the first operand, without an eval flag, and +// expect runs a Tcl script given with -c; both can spawn git. +// GNU sed runs a command line through a shell for an `s` command with the `e` +// flag and for an `e` command, so what those run is checked, while a sed +// script that only mentions a bypass flag stays data. +if (test('blocks a git bypass that a sed script runs', () => { + for (const command of [ + "printf x | sed 's/x/git commit --no-verify/e'", + "printf x | sed -e 's/x/git commit --no-verify/e'", + "printf x | sed --expression='s/x/git push --no-verify/e'", + "printf x | sed 's|x|git push --no-verify|e'", + "printf x | sed 'e git commit --no-verify'", + "echo 'git push --no-verify' | sed e", + "echo 'git push --no-verify' | sed 's/^//e'", + // Any character but a backslash or a newline can delimit an `s` command. + "printf foo | sed 'sxfooxgit push --no-verifyxe'", + // sed reads an escaped character in a replacement as that character. + "printf x | sed 's/x/git\\ push\\ --no-verify/e'", + // The script is read wherever sed takes it from. + 'printf x | sed s/x/git\\ push\\ --no-verify/e', + 'printf x | sed -es/x/git\\ push\\ --no-verify/e', + "printf x | sed --expr='s/x/git push --no-verify/e'", + "sed -n -- 'e git push --no-verify' notes.md", + "sed notes.md -e 'e git push --no-verify'", + "sed -l 80 'e git push --no-verify' notes.md", + // -ie is -i with the backup suffix e, so the operand is the script. + "sed -ie -n 'e git push --no-verify' notes.md", + "printf x | sudo sed 's/x/git push --no-verify/e'", + "printf x | sed -n '/x/!d; e git push --no-verify'", + // $EXPR may be an option such as -n, and then the quoted operand is the script. + "sed \"$EXPR\" 'e git push --no-verify' notes.md", + // So may the output of a substitution. + "printf x | sed `printf %s -n` 's/x/git push --no-verify/e'", + "printf x | sed $(printf %s -n) 's/x/git push --no-verify/e'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +// sed reads its script command by command: the text `a`, `i` and `c` add, a +// comment, a label or a file name is never a command, and an operand after +// the script, or after an -e or -f option, is an input file. +if (test('allows sed input files, added text and comments that mention a bypass', () => { + for (const command of [ + "sed 's/x/y/' 'e git commit --no-verify'", + "sed -e 's/x/y/' 'e git commit --no-verify'", + "sed --expression='s/x/y/' 'e git push --no-verify'", + "sed -f fix.sed 'e git push --no-verify'", + "sed --file=fix.sed 'e git push --no-verify'", + "sed -i '1i e git push --no-verify is unsafe' README.md", + "sed -i '$a e git push --no-verify is unsafe' README.md", + "sed -i '/hooks/c e git push --no-verify is unsafe' README.md", + "sed -n '# e git push --no-verify' README.md", + // Addresses that match the text of a sed command that runs git. + "sed -n '/s|x|git push --no-verify|e/p' notes.md", + "sed -n '\\%s/x/git push --no-verify/e%p' notes.md", + "sed -n 'w e git push --no-verify' notes.md", + // Labels named e, which the t command branches to. + "echo 'git push --no-verify' | sed -e :e -e '$!N;s/\\n/ /;te'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('allows a sed script that only mentions a bypass flag', () => { + for (const command of [ + "sed -i 's/git commit --no-verify/git commit/' notes.md", + "sed -n '/git push --no-verify/p' docs/hooks.md", + "echo 'git push --no-verify' | sed 's/push/pull/'", + "printf x | sed 's/x/git status/e'", + "sed -i 's/use git commit --no-verify here/use git commit here/' README.md", + "sed -n '/use git commit --no-verify here/p' README.md", + "grep -F 's/x/git push --no-verify/e' notes.md", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks a git bypass in awk program source and an expect -c script', () => { + for (const command of [ + "awk 'BEGIN { system(\"git commit --no-verify -m x\") }'", + "gawk 'BEGIN { system(\"git push --no-verify\") }' /dev/null", + "mawk '{ print | \"git commit -n -m x\" }' input.txt", + "expect -c 'spawn git commit --no-verify -m x'", + // The payload goes on after the call that runs git. + "awk 'BEGIN { system(\"git push --no-verify\") }'", + "node -e 'require(\"child_process\").execSync(\"git push --no-verify\"); console.log(\"done\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('allows an expect script path whose arguments mention a bypass', () => { + const command = "expect release.exp 'git push --no-verify'"; + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); +})) passed++; else failed++; + +if (test('still allows a bypass phrase in an eval payload that does not run git', () => { + for (const command of [ + 'node -e "console.log(\'use --no-verify only in emergencies\')"', + "python3 -c 'print(\"never pass -n to commit\")'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 0, `expected exit 0 for ${command}, got ${r.code}: ${r.stderr}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git command line behind a process prefix or another shell', () => { + for (const command of [ + "setsid sh -c 'git commit --no-verify -m x'", + 'csh -c "git commit --no-verify -m x"', + "tcsh -c 'git push --no-verify'", + "stdbuf -oL bash -c 'git commit -n -m x'", + "taskset -c 0 sh -c 'git push --no-verify'", + "unshare -n sh -c 'git commit --no-verify -m x'", + "runuser -u deploy -- sh -c 'git push --no-verify'", + "npx some-runner 'git commit --no-verify -m x'", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a git command substituted inside a double-quoted data argument', () => { + for (const command of [ + 'echo "$(git commit --no-verify -m x)"', + 'echo "$(git push --no-verify)"', + 'printf "%s" "`git push --no-verify`"', + 'node /tmp/cli.js "result: $(git commit -n -m x)"', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('blocks a quoted git command line inside a compound command or a nested substitution', () => { + for (const command of [ + "( sh -c 'git commit --no-verify -m x' )", + "{ sh -c 'git push --no-verify'; }", + "if sh -c 'git commit --no-verify -m x'; then echo ok; fi", + "for f in a b; do sh -c 'git commit --no-verify -m x'; done", + 'echo "$(echo "x"; git commit --no-verify -m x)"', + 'echo "before $(sh -c \'git commit --no-verify -m x\') after"', + 'echo "$(echo "$(git push --no-verify)")"', + "FOO=\"pre$(echo x)post\" sh -c 'git commit --no-verify -m x'", + "PREFIX=\"`date`\" sh -c 'git push --no-verify'", + "sh -c 'git push --no-verify'; echo done", + "sh -c 'git push --no-verify' && echo done", + 'sh -c "git commit --no-verify -m x" || true', + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + +if (test('stays fast on a large quoted data payload full of git tokens', () => { + const payload = 'git commit --no-verify -m x '.repeat(12000); + const command = `node /tmp/cli.js '${payload}'`; + assert.ok(command.length > 300000, 'payload should exceed 300 KB'); + const started = Date.now(); + const r = runHook({ tool_input: { command } }); + const elapsed = Date.now() - started; + assert.strictEqual(r.code, 0, `expected exit 0, got ${r.code}: ${r.stderr}`); + assert.ok(elapsed < 5000, `hook took ${elapsed}ms on a 300 KB quoted payload`); +})) passed++; else failed++; + +if (test('still blocks a quoted git command line handed to a shell or command wrapper', () => { + for (const command of [ + 'sh -c "git commit --no-verify -m x"', + "bash -lc 'git push --no-verify'", + 'sudo git commit --no-verify -m x', + "xargs -0 git commit --no-verify", + 'env FOO=1 git commit -n -m x', + "eval 'git commit --no-verify -m x'", + 'node /tmp/cli.js "data" && git commit --no-verify -m x', + "echo 'git commit --no-verify' ; git push --no-verify", + ]) { + const r = runHook({ tool_input: { command } }); + assert.strictEqual(r.code, 2, `expected exit 2 for ${command}, got ${r.code}`); + } +})) passed++; else failed++; + console.log('─'.repeat(50)); console.log(`Passed: ${passed} Failed: ${failed}`); diff --git a/tests/lib/code-receivers.test.js b/tests/lib/code-receivers.test.js new file mode 100644 index 00000000000..6535b211c0d --- /dev/null +++ b/tests/lib/code-receivers.test.js @@ -0,0 +1,69 @@ +'use strict'; +const assert = require('assert'); +const { + commandBasename, + receivesAsData, + sedArguments, + readsCodeFromStdin, +} = require('../../scripts/lib/code-receivers'); + +console.log('=== Testing code-receivers.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +test('commandBasename drops the path and .exe, and lowercases', () => { + assert.deepStrictEqual(['/usr/bin/SED', 'C:\\bin\\node.EXE', 'git'].map(commandBasename), ['sed', 'node', 'git']); +}); + +console.log('\nreceivesAsData (a quoted argument after these words):'); +test('an unrelated program receives it as data', () => { + assert.strictEqual(receivesAsData(['printf']), true); + assert.strictEqual(receivesAsData(['node', 'x.js']), true); + assert.strictEqual(receivesAsData(['find', '.', '-exec', 'grep']), true); +}); +test('a shell, a wrapper, an eval flag or awk runs it', () => { + assert.strictEqual(receivesAsData(['sh', '-c']), false); + assert.strictEqual(receivesAsData(['sudo']), false); + assert.strictEqual(receivesAsData(['node', '-e']), false); + assert.strictEqual(receivesAsData(['find', '.', '-exec', 'sh', '-c']), false); + assert.strictEqual(receivesAsData(['awk']), false); +}); +test('a program named by an expansion is unknown, so it may run it', () => { + assert.strictEqual(receivesAsData(['$SHELL', '-c']), false); +}); + +console.log('\nsedArguments:'); +test("sed's arguments, also behind a wrapper", () => { + assert.deepStrictEqual(sedArguments(['sed', '-n', 'p']), ['-n', 'p']); + assert.deepStrictEqual(sedArguments(['sudo', '-u', 'x', 'sed', 'e']), ['e']); +}); +test('null when the statement does not run sed', () => { + assert.strictEqual(sedArguments(['grep', 'sed']), null); +}); + +console.log('\nreadsCodeFromStdin:'); +test('a shell, a runtime without a script, or sed that runs its input', () => { + for (const words of [['sh'], ['node'], ['python3', '-'], ['sed', 'e'], ['$SHELL']]) { + assert.strictEqual(readsCodeFromStdin(words), true, words.join(' ')); + } +}); +test('a runtime with a script, sed that only edits, or cat', () => { + for (const words of [['node', 'x.js'], ['sed', 's/x/y/'], ['cat']]) { + assert.strictEqual(readsCodeFromStdin(words), false, words.join(' ')); + } +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/sed-script.test.js b/tests/lib/sed-script.test.js new file mode 100644 index 00000000000..386cb917a6b --- /dev/null +++ b/tests/lib/sed-script.test.js @@ -0,0 +1,89 @@ +'use strict'; +const assert = require('assert'); +const { sedScripts, sedScriptTexts, sedExecution } = require('../../scripts/lib/sed-script'); + +console.log('=== Testing sed-script.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +console.log('Which arguments are scripts:'); +test('the first operand is the script, the others are input files', () => { + assert.deepStrictEqual(sedScripts(['-n', 's/x/y/p', 'a.txt', 'b.txt']), ['s/x/y/p']); +}); +test('with -e, every operand is an input file', () => { + assert.deepStrictEqual(sedScripts(['-e', 's/x/y/', 'e git push']), ['s/x/y/']); + assert.deepStrictEqual(sedScripts(['notes.md', '-e', 'p']), ['p']); +}); +test('attached and long forms of -e, including a prefix of --expression', () => { + assert.deepStrictEqual(sedScripts(['-es/x/y/', '--expression=p', '--expr', 'd']), ['s/x/y/', 'p', 'd']); +}); +test('-f and --file name a script that is not on the line', () => { + assert.deepStrictEqual(sedScripts(['-f', 'fix.sed', 'e git push']), []); + assert.deepStrictEqual(sedScripts(['--file=fix.sed', 'e git push']), []); +}); +test('-ie is -i with the backup suffix e', () => { + assert.deepStrictEqual(sedScripts(['-ie', '-n', 'p', 'notes.md']), ['p']); +}); +test('-l takes a value, and -- ends the options', () => { + assert.deepStrictEqual(sedScripts(['-l', '80', 'p']), ['p']); + assert.deepStrictEqual(sedScripts(['-n', '--', '-p', 'f']), ['-p']); +}); +test('every operand may be a script when the words can still change', () => { + assert.deepStrictEqual(sedScripts(['$EXPR', 'e git push', 'f'], true), ['$EXPR', 'e git push', 'f']); +}); +test('sed joins its scripts into one, unless the words can still change', () => { + assert.deepStrictEqual(sedScriptTexts(['-e', 'a\\', '-e', 'text']), ['a\\\ntext']); + assert.deepStrictEqual(sedScriptTexts(['%s', 's/x/y/e'], true), ['%s', 's/x/y/e']); +}); + +console.log('\nWhat a script runs:'); +test('an e command runs its text, to the end of the line', () => { + assert.deepStrictEqual(sedExecution('e git push; echo done'), { + commands: ['git push; echo done'], + runsInput: false, + }); +}); +test('an e command without text runs the pattern space', () => { + assert.deepStrictEqual(sedExecution('1e'), { commands: [], runsInput: true }); +}); +test('the e flag of s runs the replacement, with any delimiter', () => { + for (const script of ['s/x/git push/e', 's|x|git push|e', 'sxfooxgit pushxe']) { + assert.deepStrictEqual(sedExecution(script).commands, ['git push'], script); + } +}); +test('an escaped character in the replacement stands for itself', () => { + assert.deepStrictEqual(sedExecution('s/x/git\\ push/e').commands, ['git push']); +}); +test('the text of a, i and c, a comment and a file name run nothing', () => { + for (const script of ['1i e git push', '$a e git push', '/x/c e git push', '# e git push', 'w e git push']) { + assert.deepStrictEqual(sedExecution(script), { commands: [], runsInput: false }, script); + } +}); +test('labels named e are not e commands', () => { + assert.deepStrictEqual(sedExecution(':e\n$!N;s/\\n/ /;te'), { commands: [], runsInput: false }); +}); +test('an address regex is not read as a command', () => { + assert.deepStrictEqual(sedExecution('/s|x|git push|e/p'), { commands: [], runsInput: false }); + assert.deepStrictEqual(sedExecution('\\%s/x/git push/e%p'), { commands: [], runsInput: false }); +}); +test('an unfinished s command ends the reading: sed rejects the script', () => { + assert.deepStrictEqual(sedExecution('s/x/y\ne git push'), { commands: [], runsInput: false }); +}); +test('a y command is read past, whatever its parts hold', () => { + assert.deepStrictEqual(sedExecution('y/e/E/;e git push').commands, ['git push']); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/shell-quotes.test.js b/tests/lib/shell-quotes.test.js new file mode 100644 index 00000000000..f26cd265253 --- /dev/null +++ b/tests/lib/shell-quotes.test.js @@ -0,0 +1,57 @@ +'use strict'; +const assert = require('assert'); +const { quotedRegions, quotedRegionAt, commandStatements } = require('../../scripts/lib/shell-quotes'); + +console.log('=== Testing shell-quotes.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +test('each quoted region, with the argv0 of its statement', () => { + assert.deepStrictEqual(quotedRegions("echo 'a b' \"c\""), [ + { start: 5, quote: "'", argv0: 'echo', argv0Start: 0, substitution: false, end: 9 }, + { start: 11, quote: '"', argv0: 'echo', argv0Start: 0, substitution: false, end: 13 }, + ]); +}); +test('a substitution splits a double-quoted string, and both halves say so', () => { + const regions = quotedRegions('echo "x $(printf y) z"'); + assert.deepStrictEqual( + regions.map(({ start, end, substitution }) => ({ start, end, substitution })), + [ + { start: 5, end: 8, substitution: true }, + { start: 18, end: 21, substitution: true }, + ] + ); +}); +test('quotedRegionAt finds the region around an index, or null', () => { + const input = "echo 'a b' \"c\""; + assert.strictEqual(quotedRegionAt(input, 7).start, 5); + assert.strictEqual(quotedRegionAt(input, 2), null); +}); +test('commandStatements lists the argv0 of every statement', () => { + assert.deepStrictEqual(commandStatements('FOO=1 sed e f | if grep -q x f; then :; fi'), [ + { argv0: 'sed', argv0Start: 6 }, + { argv0: 'grep', argv0Start: 19 }, + { argv0: ':', argv0Start: 37 }, + ]); +}); +test('commandStatements includes a statement inside a substitution', () => { + assert.deepStrictEqual( + commandStatements('echo "$(sed e f)"').map(({ argv0 }) => argv0), + ['echo', 'sed'] + ); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1); diff --git a/tests/lib/shell-statements.test.js b/tests/lib/shell-statements.test.js new file mode 100644 index 00000000000..38797572e46 --- /dev/null +++ b/tests/lib/shell-statements.test.js @@ -0,0 +1,77 @@ +'use strict'; +const assert = require('assert'); +const { + startsAtSubstitution, + statementBounds, + endsStatement, + mayGroupStatements, +} = require('../../scripts/lib/shell-statements'); + +console.log('=== Testing shell-statements.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}: ${e.message}`); + failed++; + } +} + +console.log('statementBounds:'); +test('a statement ends at ; or at a pipe', () => { + assert.deepStrictEqual(statementBounds('sed -n p f; echo x', 0), { end: 10, opaque: false }); + assert.deepStrictEqual(statementBounds("sed '$d' f | cat", 0), { end: 11, opaque: false }); +}); +test('a statement inside a substitution ends where the substitution closes', () => { + assert.deepStrictEqual(statementBounds('echo "$(sed e f)" x', 9), { end: 15, opaque: false }); +}); +test('a parameter expansion makes the words opaque, a quoted $ does not', () => { + assert.deepStrictEqual(statementBounds('sed $OPTS f', 0), { end: 11, opaque: true }); + assert.strictEqual(statementBounds("sed '$d' f", 0).opaque, false); +}); +test('a substitution is part of the statement, and makes it opaque', () => { + assert.deepStrictEqual(statementBounds("sed $(printf -n) 'e x' f; echo", 0), { end: 24, opaque: true }); + assert.deepStrictEqual(statementBounds("sed `printf -n` 'e x' f", 0), { end: 23, opaque: true }); +}); + +console.log('\nendsStatement:'); +test('; && || and a background & end a statement', () => { + assert.strictEqual(endsStatement('a; b', 1), true); + assert.strictEqual(endsStatement('a && b', 2), true); + assert.strictEqual(endsStatement('a || b', 2), true); + assert.strictEqual(endsStatement('a & b', 2), true); +}); +test('a pipe and the & of a redirection do not', () => { + assert.strictEqual(endsStatement('a | b', 2), false); + assert.strictEqual(endsStatement('a 2>&1', 4), false); + assert.strictEqual(endsStatement('a &> f', 2), false); + assert.strictEqual(endsStatement('a >&2', 3), false); +}); + +console.log('\nmayGroupStatements:'); +test('a group, a subshell or a compound command can carry output on', () => { + assert.strictEqual(mayGroupStatements('{ echo x; }', 10), true); + assert.strictEqual(mayGroupStatements('( echo x )', 10), true); + assert.strictEqual(mayGroupStatements('if true; then echo', 18), true); +}); +test('quoted parentheses and a brace inside a word do not', () => { + assert.strictEqual(mayGroupStatements("echo '(x)'", 10), false); + assert.strictEqual(mayGroupStatements('ls /tmp/{a,b}', 13), false); +}); + +console.log('\nstartsAtSubstitution:'); +test('a statement right inside $( ), backticks or <( ) starts at a substitution', () => { + assert.strictEqual(startsAtSubstitution('echo $(sed e f)', 7), true); + assert.strictEqual(startsAtSubstitution('echo `sed e f`', 6), true); + assert.strictEqual(startsAtSubstitution('source <(echo x)', 9), true); + assert.strictEqual(startsAtSubstitution('sed e f', 0), false); +}); + +console.log(`\nPassed: ${passed} Failed: ${failed}`); +if (failed > 0) process.exit(1);