What is Command Injection and why should you avoid passing user inputs to child_process.exec()?
❓ Interview Prompt: Explain Command Injection, OS shell invocation, shell metacharacters (`;&|`), and using parameterized `child_process.execFile()`.
Command Injection occurs when un-sanitized user input is passed into an OS system shell execution function (like 'child_process.exec()' in Node.js or 'system()' in C/PHP):
Exploit Mechanics:
Code runs: 'exec('ping -c 1 ' + userInput)'.
Attacker inputs: '8.8.8.8 ; cat /etc/passwd'.
The shell executes the ping command AND the injected command ('cat /etc/passwd') sequentially!
Defense:
Avoid system shell invocation! Use 'child_process.execFile()' or 'execFile' variants that execute binaries directly without passing commands through a shell interpreter.
Code Implementation Example
import { execFile } from 'child_process';
// ❌ VULNERABLE: Invokes shell, allowing metacharacter injection (; cat /etc/passwd)
// exec('ping -c 1 ${userInput}');
// ✅ SECURE: execFile passes arguments directly to process without shell interpreter!
execFile('ping', ['-c', '1', userInput], (error, stdout) => {
console.log(stdout);
});Never concatenate user input into system shell exec calls; pass parameters as an array to execFile to bypass shell interpreters.