skip to content

A Node.js conversion endpoint builds a child_process.exec command string from the uploaded file's name; what is wrong, and how should the call be rewritten?

level: seniorimportance: must knowfreq 60%

answer

  1. who parses the string
  2. an array never meets /bin/sh
  3. shell: true undoes it
  4. a leading dash is still an option
  5. DEP0190 in Node 24

basics

~20 s

exec hands the whole string to /bin/sh, so a file name containing shell syntax runs commands. Use execFile or spawn with a fixed binary path and an argument array, keep shell off, and never pass the client's name through.

solid answer

~50 s

`exec()` always starts a shell (`/bin/sh -c` on Unix) and gives it the interpolated string, so a name such as `a.docx; rm -rf ~` or one containing `$(...)` becomes shell code running as the service's user; Node's docs say never to pass unsanitized input to it. Rewrite it as `execFile(converterPath, ['--', inputPath, outputPath])`: with the default `shell: false`, each array element reaches the program as one argument and no shell ever parses it. Then close the remaining gaps. Never set `shell: true`: in Node 24 passing `args` with it is runtime deprecation `DEP0190`, because the array is only joined with spaces. Call the binary by absolute path instead of a `PATH` lookup. Store the upload under a name you generate. Use `--` where the converter honours it, so a name starting with `-` is not read as an option, and add a `timeout`.

code

javascript · 16 lines
javascript
import { exec, execFile } from 'node:child_process';
import { promisify } from 'node:util';

const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);

const name = 'report.docx; echo INJECTED';

// The shell parses the string: the text after ';' runs as a second command.
console.log((await execAsync(`echo converting ${name}`)).stdout);
// converting report.docx
// INJECTED

// No shell: the whole name is one argument.
console.log((await execFileAsync('echo', ['converting', name])).stdout);
// converting report.docx; echo INJECTED

go deeper

for a junior

Recall that exec runs its string through a shell, and that execFile and spawn with an argument array do not.

for a middle

Explain how Node builds /bin/sh -c from exec and from shell: true, why quoting inside the string fails, and what DEP0190 warns about in Node 24.

for a senior

Review the call end to end: absolute binary path, generated file names, '--', no shell, timeout and output limits, a minimal env, and the Windows batch-file exception.

for a principal

Make argument arrays the enforced default for every subprocess call, with lint or review rules that flag exec and shell: true for justification.

## What exec actually runs `child_process.exec(command)` is implemented as a `spawn()` with the `shell` option forced on. On Unix, Node runs **`/bin/sh -c <command>`**; on Windows it runs `process.env.ComSpec` (falling back to `cmd.exe`) with `/d /s /c`. The shell then does everything a shell does to that string: it splits words, expands `$VAR` and `$(...)`, honours quotes and backticks, and treats `;`, `&&`, `|` and `>` as operators. Node's documentation is blunt: *never pass unsanitized user input to this function*. Interpolating an uploaded file's name therefore hands the client a way to append commands: - `report.docx; rm -rf ~` runs a second command after the converter. - `$(id).docx` runs `id` while the shell is still building the argument list. - Wrapping the name in quotes does not fix it: inside double quotes `$(...)` and backticks still expand, and a name containing a quote character closes yours. `JSON.stringify(name)` produces exactly such a double-quoted string. The general theory of injection belongs to the application-security material. What matters for Node is *which call sites start a shell*. ## Argument arrays: what execFile and spawn change `execFile(file, args)` and `spawn(command, args)` default to **`shell: false`**. Node passes `file` and each element of `args` to the operating system as separate entries of the new process's argument vector. No shell runs, so there is no parser to confuse: `report.docx; echo INJECTED` arrives at the converter as one odd but harmless file name. The same property is why globbing and redirection do not work with these functions. | Call | Shell parses the input? | Safe with an attacker-chosen file name? | |---|---|---| | ``exec(`convert ${name}`)`` | Yes, always | No | | `execFile(bin, [name])` | No | Yes, against shell injection | | `execFile(bin, [name], { shell: true })` | Yes; args are space-joined | No | | ``spawn('sh', ['-c', `convert ${name}`])`` | Yes; you started the shell yourself | No | ## How the protection gets switched back off Moving from `exec` to `execFile` is the start, not the whole fix. A review should look for these ways back in: - **`shell: true`** (or a shell path) on `spawn` or `execFile`. Node then builds the command as `${file} ${args.join(' ')}`, without escaping. Since **v24.0.0** this combination emits the runtime deprecation warning **`DEP0190`**, which says so in its own text: the arguments are "not escaped, only concatenated". - **Calling a shell explicitly**, as in `spawn('sh', ['-c', ...])` with the name inside the script string. - **Windows batch files.** `.bat` and `.cmd` files cannot run without a shell, so `execFile` cannot launch them; `exec`, `spawn` with `shell`, or `cmd.exe /c` all bring `cmd.exe` parsing back. Prefer calling a real executable. - **Option injection.** An argument array stops the *shell* from reinterpreting a value, not the *program*. A name that begins with `-` or `--` reaches the converter as something that looks like one of its options. Use the `--` end-of-options marker when the converter follows that convention, and avoid putting client-supplied text first. - **`PATH` lookup.** A bare program name is resolved through `options.env.PATH` (or `process.env.PATH`). Use an absolute path from configuration. ## A hardened call 1. Store the upload under a **server-generated name** in a private working directory; keep the client's name only as data, never as a path or argument. 2. Run the converter by **absolute path** with `execFile` or `spawn` and an **array** of arguments; leave `shell` at its default `false`. 3. Put `--` before file arguments where the converter supports it. 4. Bound the run: `timeout` with a `killSignal`, and a deliberate `maxBuffer`, or stream the output with `spawn`. 5. Narrow what the child can reach: pass a minimal `env`, set `cwd` to the working directory, and where the host allows it run the child as a less privileged user with `uid` and `gid`. ## What changed in Node 24 `DEP0190` started as a documentation-only deprecation in v22.15.0 and v23.11.0 and became a **runtime** deprecation in v24.0.0, so on Node 24 the first such call prints a `DeprecationWarning` with that code. The call still runs; the warning is a pointer at the call site, not a defence. Treating the warning as a failed build in CI (for example with `--throw-deprecation`) turns it into one.

  • Is spawn(converter, [name], { shell: true }) any safer than exec?
    No. With `shell` set, Node joins the command and the arguments with spaces and runs the result through `/bin/sh -c`, exactly as `exec` would, so the array gives no protection. Node 24 flags the pattern with the runtime deprecation `DEP0190`. Drop the `shell` option and the same array becomes safe against shell parsing.
  • The converter must run on Windows and ships only as a .cmd wrapper. What changes?
    Node cannot start `.bat` or `.cmd` files without `cmd.exe`, so `execFile` will not launch them and every working option (`exec`, `spawn` with `shell`, or `cmd.exe /c`) brings back command-line parsing. Prefer the real executable behind the wrapper. If you cannot, keep client-supplied text out of the command line entirely, for example by passing only server-generated paths.
  • Does using execFile mean the uploaded file name can be used as the input path?
    No. The array stops shell parsing, but the name can still contain `../` segments or start with `-`, and it identifies a path the client chose. Save the upload under a generated name in a private directory and pass that path; keep the original name only as metadata.

exec is dictating a sentence to an assistant who carries out every instruction they hear in it; execFile is handing over a form with labelled boxes, where whatever is written in the 'file name' box stays a file name, though the recipient can still misread a box that starts with a dash.

  • Wrapping the file name in double quotes inside the exec string makes it safe.
  • execFile is safe even with shell: true because the arguments are an array.
  • JSON.stringify(name) escapes a value well enough for exec.
  • An argument array also stops a name starting with a dash being read as an option.
  • spawn('sh', ['-c', cmd]) is as safe as execFile because it uses spawn.

Assumes Node 24: passing an args array together with shell: true has been a runtime deprecation (DEP0190) since v24.0.0, after a documentation-only deprecation in v22.15.0 and v23.11.0.