What is Command Injection
Command Injection (OS Command Injection) occurs when user input is passed to a shell command without proper sanitization, allowing execution of arbitrary OS commands.
OWASP: Part of A03:2021 Injection. Often leads to full server compromise.
How It Happens
# Python — vulnerable code
domain = request.form['domain']
result = subprocess.check_output(f"ping -c 1 {domain}", shell=True)
With domain = "google.com; id" the shell executes: ping -c 1 google.com; id
Chain Operators
| Operator | Example | Behavior |
|---|---|---|
| Semicolon | cmd1; cmd2 |
Both execute |
| AND | cmd1 && cmd2 |
cmd2 only if cmd1 succeeds |
| Pipe | cmd1 \| cmd2 |
stdout → stdin |
| Subshell | $(cmd) |
Command substitution |
Defense
# ❌ Vulnerable
subprocess.check_output(f"ping {user_input}", shell=True)
# ✅ Safe
subprocess.run(["ping", "-c", "1", user_input], shell=False)
Always validate input with an allowlist and use shell=False with argument lists.