π Learn & Master Command Injection
Comprehensive guide covering theory, bypass techniques, real-world examples, and prevention strategies
What is Command Injection?
Command Injection is a security vulnerability that allows attackers to execute arbitrary operating system commands on the server hosting an application. It occurs when an application passes unsafe user input to a system shell, enabling attackers to run malicious commands, access sensitive files, or completely compromise the system.
How Command Injection Works
Attackers exploit command injection by injecting shell metacharacters (;, &&, ||, |, `) into user input that gets passed to system commands. These metacharacters allow chaining multiple commands or redirecting output.
β Vulnerable Code Example
1// PHP - Unsafe command execution2$ip = $_GET['ip'];3$output = shell_exec("ping -c 4 " . $ip);4echo $output;56// Attacker input: 127.0.0.1; cat /etc/passwd7// Executes: ping -c 4 127.0.0.1; cat /etc/passwdβ Secure Code
1// PHP - Input validation & escapeshellarg()2$ip = $_GET['ip'];3if (filter_var($ip, FILTER_VALIDATE_IP)) {4 $output = shell_exec("ping -c 4 " . escapeshellarg($ip));5 echo $output;6} else {7 die("Invalid IP");8}Types of Command Injection
Simple command chaining using separators like ; && || |
No direct output; use time delays or out-of-band channels
Evade WAF/filters using encoding, obfuscation, wildcards
Full RCE via reverse shells, backdoors, privilege escalation
What Can Happen?
- π£Remote Code Execution:
Execute arbitrary OS commands, install backdoors, create user accounts
- πData Exfiltration:
Read sensitive files (/etc/passwd, SSH keys), database credentials, source code
- π’System Compromise:
Full server takeover, lateral movement, privilege escalation to root
- π¦ Malware Deployment:
Deploy ransomware, cryptominers, botnet agents, persistent backdoors
How to Prevent Command Injection
- βAvoid System Commands: Use language APIs instead of shell commands when possible
- βInput Validation: Whitelist allowed characters, reject special shell metacharacters
- βEscape Functions: Use escapeshellarg() / escapeshellcmd() in PHP, shlex in Python
- βParameterized Commands: Never concatenate user input into commands
- βPrinciple of Least Privilege: Run processes with minimal permissions, use sandboxing
- βWAF & Monitoring: Deploy WAF rules, monitor for suspicious command patterns