Node.js
- Use
- child_process.execFile / spawn with an args array (no shell)
- Avoid
- child_process.exec, execSync, or spawn with { shell: true }
Vulnerable
const { exec } = require("node:child_process");
// host comes from the request — "8.8.8.8; rm -rf /" runs rm
exec("ping -c1 " + host, (e, out) => res.send(out));Fixed
const { execFile } = require("node:child_process");
// host is a single argv entry; shell metacharacters are inert
execFile("ping", ["-c1", "--", host], (e, out) => res.send(out));- exec() and execSync() always run their string through /bin/sh (or cmd.exe) — treat them as unsafe for any value that includes user input.
- spawn()/execFile() are safe only without shell: true. Setting shell: true re-introduces the shell and the bug.
- Prefer a library (e.g. dns.lookup instead of shelling out to ping/nslookup) when one exists.