Command Injection
A vulnerability that allows attackers to execute arbitrary operating system commands on a server by injecting malicious input into system command calls.
Command Injection (also called OS Command Injection or Shell Injection) is a vulnerability that allows attackers to execute arbitrary operating system commands on the server by injecting malicious input into system command calls.
How It Works
When an application passes user input to a system shell without proper sanitization, attackers can break out of the intended command and execute their own commands using shell metacharacters.
Prevention
- Avoid shell commands: Use language-native APIs instead of shell execution
- Use parameterized APIs: Pass arguments as arrays, not concatenated strings
- Input validation: Allowlist expected characters/patterns
- Escape shell metacharacters: Use
shlex.quote()(Python),escapeshellarg()(PHP) - Least privilege: Run processes with minimal permissions
Safe Alternatives
# Python - UNSAFE
os.system("ping " + host)
# Python - SAFE (subprocess with list)
subprocess.run(["ping", "-c", "1", host], capture_output=True)
# PHP - UNSAFE
system("nslookup " . $host);
# PHP - SAFE
$output = dns_get_record($host, DNS_A);