Skip to content
Myr

Fix arguments of Windows batch files that read them with `%~1`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Like Rust, arguments that do not need quoting are not quoted anymore, so `%1` now receives `-f` instead of `"-f"`. Fixes #1261

authored by Sindre Sorhus · committed by Sindre Sorhus · parent af6264a · Browse files · 6 files+94 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+94 added−23 removed

  • tests:+30 added−7 removed
  • other:+64 added−16 removed

6 files+94 added−23 removed

modified:.github/security.md+5 added
modified:docs/escaping.md+1 added-1 removed
modified:docs/windows.md+10 added
55 unmodified lines
56```js57await execa`npm run ${'task with space'}`;58```5960`.cmd` and `.bat` files are run through `cmd.exe`, so their arguments are also escaped to prevent `cmd.exe` from interpreting them. This uses the same escaping as [Rust](https://github.com/rust-lang/rust/blob/main/library/std/src/sys/args/windows.rs), which is safe whether the batch file reads its arguments (`%1`, `"%~1"`) or forwards them (`%*`), like the shims in `node_modules/.bin` do.6162> [!WARNING]63> Batch files can still misuse their arguments, which no escaping can prevent:64> - `%~1` receives the escaped argument: each `"` is doubled, and so are trailing backslashes.65> - Using `%~1` outside double quotes, or `%1` inside double quotes (like `if "%1" == ""`), lets `cmd.exe` interpret the argument's special characters, which allows command injection.66> - Forwarding arguments with `call`, or enabling delayed expansion, makes `cmd.exe` expand `%` or `!` in them again.67>68> Also, arguments cannot contain line breaks, since `cmd.exe` cannot escape them. This applies to any file run through `cmd.exe`, i.e. any file other than `.exe` and `.com`.6970When using a [shell](shell.md), the user must manually perform shell-specific quoting, on both Unix and Windows. When the [`shell`](api.md#optionsshell) option is `true`, [`cmd.exe`](https://en.wikipedia.org/wiki/Cmd.exe) is used on Windows and `sh` on Unix. Unfortunately, both shells use different quoting rules. With `cmd.exe`, this mostly involves double quoting arguments and prepending double quotes with a backslash.7172```js73if (isWindows) {
29 unmodified lines
modified:lib/arguments/command-file.js+48 added-15 removed
16 unmodified lines
1718// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`19const directlyExecutableRegExp = /\.(?:com|exe)$/i;2021// `.cmd` and `.bat` files re-expand their own arguments via `%*`/`%1`, so metacharacters must survive being interpreted by `cmd.exe` twice: once when the batch file is invoked and once when it forwards the arguments22const batchFileRegExp = /\.(?:bat|cmd)$/i;2321const escapeWindowsCommand = parsed => {22 // Resolve the file to an absolute path, following its shebang to the interpreter if any23 const resolvedFile = resolveWithShebang(parsed);24
14 unmodified lines
39 for (const value of [parsed.file, ...parsed.commandArguments]) {40 assertNoLineBreak(value);41 }4246 const isDoubleEscape = resolvedFile !== undefined && batchFileRegExp.test(resolvedFile);47 // POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENT43 /*44 POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENT.4546 Unlike Rust, which quotes the batch file's path, the file is caret-escaped. `cmd.exe` only interprets it once, and the file might not be resolved, for example when it is a `cmd.exe` builtin, which would not run if quoted.47 */48 const escapedFile = escapeMetaChars(path.normalize(resolvedFile ?? parsed.file));49 const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument, isDoubleEscape));49 const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument));50 const commandLine = `"${[escapedFile, ...escapedArguments].join(' ')}"`;5152 // Let `node:child_process` pass the already-escaped command line through untouched53 parsed.options.windowsVerbatimArguments = true;54 return {55 file: process.env.comspec || 'cmd.exe',56 // `/e:on` enables the command extensions the `%` escaping relies on, and `/v:off` disables delayed expansion so `!` is literal, even when the registry changes either default56 commandArguments: ['/d', '/s', '/c', commandLine],57 commandArguments: ['/d', '/e:on', '/v:off', '/s', '/c', commandLine],58 options: parsed.options,59 };60};61
111 unmodified lines
173// See https://web.archive.org/web/20241220221102/https://www.robvanderwoude.com/escapechars.php174// eslint-disable-next-line regexp/sort-character-class-elements175const metaCharsRegExp = /[()\][%!^"`<>&|;, *?]/g;176176// Prefix every `cmd.exe` metacharacter with a caret to neutralize it177// Prefix every `cmd.exe` metacharacter with a caret to neutralize it. This is only used for the file, since arguments are quoted instead.178const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');179180const backslashRunRegExp = /\\+/g;181181const escapeArgument = (rawArgument, doubleEscape) => {182// Matches any character requiring quoting: anything except ASCII letters, digits, a few punctuation characters that `cmd.exe` never interprets, and non-ASCII characters other than control characters183const quotedCharacterRegExp = /[^\w#$*+\-./:?@\\\u{80}-\u{10FFFF}]|\p{Control}/u;184185/*186Escape an argument the same way as Rust's `std::process::Command` does for batch files, which fixed the "BatBadBut" vulnerability (CVE-2024-24576): https://github.com/rust-lang/rust/blob/main/library/std/src/sys/args/windows.rs (`append_bat_arg()`). yt-dlp uses the same algorithm.187188Any argument containing a `cmd.exe` metacharacter is wrapped in double quotes, which keeps `cmd.exe` from interpreting it. `cmd.exe` might interpret it more than once: when invoking a batch file, then again when that batch file forwards it with `%*`, like npm cmd-shims do. Caret escaping depends on that count, so it breaks batch files reading their arguments directly with `%~1`, like Maven's `mvn.cmd`. Quoting does not, as long as the quotes stay balanced.189190Rust only uses this for batch files. We use it for any file run through `cmd.exe`, since it is also correct when `cmd.exe` interprets the argument only once.191192Limitations, which no escaping can fix since they depend on how the batch file uses its arguments:193- A batch file reading `%~1` gets the escaped argument without its surrounding quotes: double quotes are doubled, and trailing backslashes too.194- A batch file using `%~1` outside double quotes, or `%1` inside double quotes (like `if "%1" == ""`), lets `cmd.exe` interpret its metacharacters. Since `%1` includes the argument's surrounding quotes, the extra ones unquote it.195- A batch file forwarding its arguments with `call` expands `%` again, and one enabling delayed expansion expands `!` again.196*/197const escapeArgument = rawArgument => {198 /*183 Escape backslashes and double quotes for `cmd.exe`, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.199 Escape backslashes, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.200201 A run of backslashes only needs doubling when it precedes a double quote, or the end of the argument since that becomes a double quote once the argument is wrapped below. Otherwise the backslashes would be taken as escaping that quote. Every double quote is then escaped in turn.202203 Each backslash run is matched exactly once and consumed, so a long run cannot trigger the quadratic backtracking a naive pattern would, which would be a denial-of-service risk.204205 Double quotes are escaped as `""` instead of `\"`. Both are a literal double quote inside a quoted argument for the subprocess, but only `""` keeps the quotes balanced for `cmd.exe`, which does not know about backslashes. Otherwise, the metacharacters after the double quote would not be quoted anymore, allowing command injection.206207 `%` cannot be escaped inside double quotes, so it is replaced by `%%cd:~,%` instead. That is a literal `%` followed by an empty substring of the `%cd%` variable, which `cmd.exe` expands to nothing. This prevents `%VAR%` from being expanded.208 */189 const argument = `${rawArgument}`209 const argument = `${rawArgument}`;210 if (!shouldQuoteArgument(argument)) {211 return argument;212 }213214 const escapedArgument = argument215 .replaceAll(backslashRunRegExp, (backslashes, offset, string) => {216 const nextCharacter = string[offset + backslashes.length];217 const isPrecedesDoubleQuote = nextCharacter === '"' || nextCharacter === undefined;218 return isPrecedesDoubleQuote ? backslashes.repeat(2) : backslashes;219 })195 .replaceAll('"', '\\"');220 .replaceAll('"', '""')221 .replaceAll('%', '%%cd:~,%');222197 // Wrap the whole argument in double quotes, then caret-escape the metacharacters, a second time when targeting a cmd-shim198 const escapedArgument = escapeMetaChars(`"${argument}"`);199 return doubleEscape ? escapeMetaChars(escapedArgument) : escapedArgument;223 return `"${escapedArgument}"`;224};225226/*227An empty argument must be quoted, otherwise it would be dropped.228An argument ending with a backslash must be quoted, otherwise a batch file wrapping it in double quotes, like `"%~1"`, would have that backslash escape its closing double quote.229Since `"` and `%` require quoting, an unquoted argument never needs any escaping.230*/231const shouldQuoteArgument = argument => argument === ''232 || argument.endsWith('\\')233 || quotedCharacterRegExp.test(argument);
modified:test/arguments/command-resolution.js+25 added-7 removed
362 unmodified lines
363 assert.equal(stdout, 'Hello World');364 });365366 /*367 Metacharacters are double-escaped for batch files, since `cmd.exe` interprets them once when the batch file is invoked and once when it re-expands the arguments with `%*`.367 Metacharacters must survive `cmd.exe` interpreting them twice for batch files: once when the batch file is invoked and once when it re-expands the arguments with `%*`.368 The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example.369 */370 const setupCmdShim = async () => {371 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');
2 unmodified lines
374 await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);375 return shimPath;376 };377378 test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async () => {378 test('Escapes metacharacters for node_modules/.bin cmd-shims', async () => {379 const shimPath = await setupCmdShim();380 const commandArgument = '"(foo|bar>baz|foz)"';381 const {stdout} = await execa(shimPath, [commandArgument]);382 assert.equal(stdout, commandArgument);
1 unmodified line
384 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);385 assert.equal(stdoutSync, commandArgument);386 });387388 test('Double-escapes explicit batch files excluded from PATHEXT', async () => {388 test('Escapes metacharacters for explicit batch files excluded from PATHEXT', async () => {389 const commandArgument = '"& whoami &"';390 const command = path.join(FIXTURES_DIRECTORY, 'echo-shim.cmd');391 const {stdout} = await execa(command, [commandArgument], nodeOnlyOptions);392 assert.equal(stdout, commandArgument);
6 unmodified lines
399 const command = path.join(FIXTURES_DIRECTORY, 'echo.js');400 await testResolvesCommand(command, nodeOnlyOptions);401 });402403 test('Double-escapes metacharacters for preferLocal cmd-shims', async () => {403 test('Escapes metacharacters for preferLocal cmd-shims', async () => {404 await setupCmdShim();405 const commandArgument = 'a&whoami';406 const originalPathExt = process.env.PATHEXT;407 process.env.PATHEXT = '.EXE';
86 unmodified lines
494 test('Roundtrips consecutive double quotes through cmd.exe', () => testCmdRoundtrip(['""', '"""', 'a""b', '""""']));495 test('Roundtrips arguments with spaces through cmd.exe', () => testCmdRoundtrip(['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']));496497 /*498 `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same double-escaping.498 `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same escaping.499 `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.500 */501 const testBatEscaping = async commandArgument => {502 const {stdout} = await execa('echo-shim.bat', [commandArgument]);
6 unmodified lines
509 // The same nested-quote injection must stay inert when the batch file is a `.bat`.510 test('Does not allow command injection via nested quotes in `.bat` arguments', () => testBatEscaping('"& whoami &"'));511 // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.512 test('Roundtrips shell metacharacters through a `.bat` file', () => testBatEscaping('(foo|bar>baz|foz)'));513 // A `.bat` file not in `node_modules/.bin/` must still be double-escaped, since the location is irrelevant: any batch file re-expands its arguments.513 // A `.bat` file not in `node_modules/.bin/` must still be escaped against the double expansion, since the location is irrelevant: any batch file can re-expand its arguments.514 test('Does not expand environment variables in `.bat` arguments', () => testBatEscaping('%PATH%'));515 // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.516 test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', () => testBatEscaping('a\\"&b\\\\"|c\\'));517 // Several tricky arguments passed together must each be double-escaped independently and arrive in order, not merged nor reordered.517 // Several tricky arguments passed together must each be escaped independently and arrive in order, not merged nor reordered.518 test('Roundtrips multiple tricky arguments through a `.bat` file', async () => {519 const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];520 const expectedStdout = commandArguments.join('\n');521
3 unmodified lines
525 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);526 assert.equal(stdoutSync, expectedStdout);527 });528529 /*530 Unlike cmd-shims, some batch files read their own arguments with `%1` or `%~1` instead of forwarding them with `%*`, like Maven's `mvn.cmd`.531 `read-arguments.cmd` prints its first argument, then its second one when the first one is `-f`.532 `ECHO` ends lines with CRLF.533 */534 const testReadArguments = async (commandArguments, expectedLines) => {535 const {stdout} = await execa('read-arguments.cmd', commandArguments);536 assert.deepEqual(stdout.split('\r\n'), expectedLines);537538 const {stdout: stdoutSync} = execaSync('read-arguments.cmd', commandArguments);539 assert.deepEqual(stdoutSync.split('\r\n'), expectedLines);540 };541542 test('Passes arguments to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\repo\\pom.xml'], ['first is -f', 'file is "C:\\repo\\pom.xml"']));543 test('Passes metacharacters to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\my repo\\a&b|c%PATH%.xml'], ['first is -f', 'file is "C:\\my repo\\a&b|c%PATH%.xml"']));544 // Like Rust, only arguments that need quoting are quoted, so `%1` matches what the user passed, like when run from a terminal545 test('Only quotes arguments that need it for batch files reading them with `%1`', () => testReadArguments(['a b'], ['first is "a b"']));546547 // `cmd.exe` interprets CR and LF as command separators and provides no way to escape548 // them, so those are rejected to prevent command injection.549 test('Rejects arguments containing a line break', () => {550 assertThrows(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});
15 unmodified lines
added:test/fixtures/read-arguments.cmd+5 added
1@ECHO off2ECHO first is %13IF "%~1" == "-f" (4 ECHO file is "%~2"5)