Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,22 @@ While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its

This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.

### Windows argument escaping

On Unix systems arguments are passed to a new process as an array of strings, but on Windows they are passed as a single command line string and it is up to the child process to parse it back into an array. Therefore `cross-spawn` and the child process must agree on how the command line is encoded.

`cross-spawn` escapes arguments according to the conventions of the Microsoft C runtime, which most programs use, including Node.js, Python, Java and .NET. However, some programs have their own way of parsing the command line, in which case they may see a different array of arguments than the one you passed.

Commands that are not executables, such as batch files (`.bat` and `.cmd`), are run through `cmd.exe`, which uses non-standard parsing and is especially vulnerable to malicious input, as it may be used to run arbitrary commands. `cross-spawn` escapes the command and its arguments according to `cmd.exe` rules, similarly to other runtimes such as [Rust](https://doc.rust-lang.org/std/process/index.html#windows-argument-splitting). Still, due to the complexity of `cmd.exe`, there are limitations that no escaping can overcome:

- Some characters can't be escaped at all. Line breaks (`\r` and `\n`) can't be escaped and passing them results in an error being thrown.
- Batch files are assumed to forward arguments as received, e.g. with `%*`, `%1` or `"%~1"`. Batch files that use `%~1` unquoted, `call` or enable delayed expansion re-parse their arguments and may be vulnerable to malicious input.
- Programs called by batch files must follow the Microsoft C runtime conventions. Programs that don't, such as those written in Go or that use `CommandLineToArgvW`, may split arguments containing double quotes differently.

Additionally, programs that read their arguments with the legacy ANSI code page instead of Unicode may convert certain Unicode characters into others, such as `"` (U+FF02) into `"`, which changes how arguments are split. This is known as [WorstFit](https://worst.fit) and can't be mitigated by `cross-spawn`.

When passing untrusted input on Windows, validate it so that only a safe subset is allowed, and prefer calling executables directly rather than through batch files.

### Shebangs support

While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
Expand Down
38 changes: 28 additions & 10 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ const semver = require('semver');

const isWin = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
const isBatchFileRegExp = /\.(?:bat|cmd)$/i;
// Windows strips trailing dots and spaces from file names, so `cmd.exe` runs `foo.bat ` as `foo.bat`
// See CVE-2024-36138 for the equivalent Node.js vulnerability
const trailingDotsAndSpacesRegExp = /[. ]+$/;

// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0
const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false;
Expand All @@ -29,6 +32,19 @@ function detectShebang(parsed) {
return parsed.file;
}

function isBatchFile(parsed, commandFile) {
if (commandFile) {
return isBatchFileRegExp.test(commandFile.replace(trailingDotsAndSpacesRegExp, ''));
}

// The command couldn't be resolved, but cmd.exe might still find a batch file after stripping
// trailing dots and spaces, e.g.: `foo ` might run `foo.bat`
const command = parsed.command.replace(trailingDotsAndSpacesRegExp, '');
const file = command !== parsed.command ? resolveCommand(Object.assign({}, parsed, { command })) : null;

return isBatchFileRegExp.test(file || command);
}

function parseNonShell(parsed) {
if (!isWin) {
return parsed;
Expand All @@ -43,23 +59,25 @@ function parseNonShell(parsed) {
// If a shell is required, use cmd.exe and take care of escaping everything correctly
// Note that `forceShell` is an hidden option used only in tests
if (parsed.options.forceShell || needsShell) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);

// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
parsed.command = path.normalize(parsed.command);

// Escape command & arguments
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
// Batch files need a different escaping strategy, see `lib/util/escape.js` for more information
if (isBatchFile(parsed, commandFile)) {
parsed.command = escape.batchCommand(parsed.command);
parsed.args = parsed.args.map((arg) => escape.batchArgument(arg));
} else {
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg));
}

const shellCommand = [parsed.command].concat(parsed.args).join(' ');

parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
// Enable command extensions with /e:on, needed by the %cd:~,% trick, as they might be disabled in the registry
// Disable delayed expansion with /v:off, otherwise !VAR! would be expanded if enabled in the registry
parsed.args = ['/d', '/e:on', '/v:off', '/s', '/c', `"${shellCommand}"`];
parsed.command = process.env.comspec || 'cmd.exe';
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
}
Expand Down
106 changes: 82 additions & 24 deletions lib/util/escape.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,105 @@
'use strict';

// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
// Note that % is not included because escaping it with ^ doesn't prevent %VAR% expansion if
// a variable named `VAR^` exists, see `escapePercent()` below
const metaCharsRegExp = /([()\][!^"`<>&|;, *?])/g;

// cmd.exe treats CR and LF as command separators and there's no way to escape them
// Allowing them would enable command injection, so we reject them instead
const lineBreakRegExp = /[\r\n]/;

function assertNoLineBreaks(arg) {
if (lineBreakRegExp.test(arg)) {
throw new TypeError('The command and its arguments cannot contain line breaks when executed through cmd.exe');
}
}

// %VAR% is expanded even inside double quotes or when escaped with ^, so we replace % with %%cd:~,%
// The latter is an empty substring of the %cd% dynamic variable, which interrupts the expansion
// This must be done after escaping meta chars, as the replacement must not be escaped itself
function escapePercent(arg) {
return arg.replace(/%/g, '%%cd:~,%');
}

// Quotes an argument so that it's parsed back verbatim by programs following the Microsoft C runtime rules,
// where backslashes are only special when they precede a double quote
// Algorithm below is based on https://qntm.org/cmd, but implemented with a loop instead of regular expressions,
// which runs in linear time and correctly handles any number of backslashes
function quoteArgument(arg, escapedQuote) {
let quoted = '"';
let backslashes = 0;

for (const char of arg) {
if (char === '\\') {
backslashes += 1;
continue;
}

if (char === '"') {
// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
quoted += '\\'.repeat(backslashes * 2) + escapedQuote;
} else {
// All other backslashes occur literally
quoted += '\\'.repeat(backslashes) + char;
}

backslashes = 0;
}

// Sequence of backslashes followed by the end of the string (which will become a double quote):
// double up all the backslashes
return `${quoted}${'\\'.repeat(backslashes * 2)}"`;
}

function escapeCommand(arg) {
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
assertNoLineBreaks(arg);

// Escape meta chars and neutralize %VAR% expansion
arg = escapePercent(arg.replace(metaCharsRegExp, '^$1'));

return arg;
}

function escapeArgument(arg, doubleEscapeMetaChars) {
function escapeArgument(arg) {
// Convert to string
arg = `${arg}`;

// Algorithm below is based on https://qntm.org/cmd
// It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
// Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information
assertNoLineBreaks(arg);

// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
// Quote the whole thing, escaping double quotes with a backslash
arg = quoteArgument(arg, '\\"');

// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
// Escape meta chars and neutralize %VAR% expansion
arg = escapePercent(arg.replace(metaCharsRegExp, '^$1'));

// All other backslashes occur literally
return arg;
}

// Quote the whole thing:
arg = `"${arg}"`;
// Batch files (.bat and .cmd) usually proxy their arguments with %* or read them with "%~1",
// which makes cmd.exe parse them a second time, after ^ escapes have already been consumed
// Instead of escaping meta chars with ^, we rely on double quotes, which keep meta chars literal in both parses
// This is the same approach taken by Rust after BatBadBut (CVE-2024-24576)

// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
function escapeBatchCommand(arg) {
assertNoLineBreaks(arg);

// Double escape meta chars if necessary
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}
// Command names can't contain double quotes, so we just need to quote it
return `"${escapePercent(arg)}"`;
}

return arg;
function escapeBatchArgument(arg) {
// Convert to string
arg = `${arg}`;

assertNoLineBreaks(arg);

// Quote the whole thing, escaping double quotes by doubling them, which keeps cmd.exe's quoting balanced
return escapePercent(quoteArgument(arg, '""'));
}

module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
module.exports.batchCommand = escapeBatchCommand;
module.exports.batchArgument = escapeBatchArgument;
68 changes: 68 additions & 0 deletions test/escape.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
'use strict';

const escape = require('../lib/util/escape');

describe('escape', () => {
it('should reject line breaks in the command', () => {
expect(() => escape.command('foo\ncalc.exe')).toThrow(TypeError);
expect(() => escape.command('foo\rcalc.exe')).toThrow(TypeError);
});

it('should reject line breaks in arguments', () => {
['safe.js\ncalc.exe', 'safe.js\rcalc.exe', 'safe.js\r\ncalc.exe', '\n'].forEach((arg) => {
expect(() => escape.argument(arg)).toThrow(TypeError);
});
});

it('should reject line breaks in batch commands and arguments', () => {
expect(() => escape.batchCommand('foo\ncalc.exe')).toThrow(TypeError);
expect(() => escape.batchArgument('safe.js\ncalc.exe')).toThrow(TypeError);
expect(() => escape.batchArgument('safe.js\rcalc.exe')).toThrow(TypeError);
});

it('should quote batch arguments, doubling quotes and neutralizing %', () => {
expect(escape.batchArgument('hello')).toBe('"hello"');
expect(escape.batchArgument('')).toBe('""');
expect(escape.batchArgument(1234)).toBe('"1234"');
expect(escape.batchArgument('a & b')).toBe('"a & b"');
expect(escape.batchArgument('a"b')).toBe('"a""b"');
expect(escape.batchArgument('a\\"b')).toBe('"a\\\\""b"');
expect(escape.batchArgument('C:\\dir\\')).toBe('"C:\\dir\\\\"');
expect(escape.batchArgument('%PATH%')).toBe('"%%cd:~,%PATH%%cd:~,%"');
expect(escape.batchArgument('x^y!')).toBe('"x^y!"');
});

it('should neutralize % instead of escaping it with ^', () => {
// ^% doesn't prevent %VAR% expansion if a variable named `VAR^` exists
expect(escape.argument('%x%')).toBe('^"%%cd:~,%x%%cd:~,%^"');
expect(escape.argument('a,b')).toBe('^"a^,b^"');
expect(escape.command('C:\\foo\\%CD%')).toBe('C:\\foo\\%%cd:~,%CD%%cd:~,%');
});

it('should double backslashes only before a quote or at the end', () => {
expect(escape.argument('a\\b')).toBe('^"a\\b^"');
expect(escape.argument('a\\\\"b')).toBe('^"a\\\\\\\\\\^"b^"');
expect(escape.argument('C:\\dir\\\\')).toBe('^"C:\\dir\\\\\\\\^"');
expect(escape.batchArgument('a\\b')).toBe('"a\\b"');
expect(escape.batchArgument('a\\\\"b')).toBe('"a\\\\\\\\""b"');
expect(escape.batchArgument('C:\\dir\\\\')).toBe('"C:\\dir\\\\\\\\"');
});

it('should escape long sequences of backslashes in linear time', () => {
const arg = `${'\\'.repeat(1e6)}"`;
const start = Date.now();

escape.argument(arg);
escape.batchArgument(arg);

expect(Date.now() - start).toBeLessThan(1000);
});

it('should quote batch commands and neutralize %', () => {
expect(escape.batchCommand('C:\\foo\\%CD%.bat')).toBe('"C:\\foo\\%%cd:~,%CD%%cd:~,%.bat"');
});

it('should not include the offending value in the error message', () => {
expect(() => escape.argument('secret\n')).toThrow(/^(?!.*secret)/);
});
});
1 change: 1 addition & 0 deletions test/fixtures/echo-first-quoted.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@node "%~dp0\echo.js" "%~1"
1 change: 1 addition & 0 deletions test/fixtures/echo-forward.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@node "%~dp0\echo.js" %*
12 changes: 1 addition & 11 deletions test/fixtures/win-ppid.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,4 @@

'use strict';

const spawnSync = require('child_process').spawnSync;

function ppidSync() {
const res = spawnSync('wmic',
['process', 'where', `(processid=${process.pid})`, 'get', 'parentprocessid']);
const lines = res.stdout.toString().split(/\r?\n/);

return parseInt(lines[1].trim(), 10);
}

console.log(ppidSync());
console.log(process.ppid);
Loading