Command Injection and OS Command Execution
You'll learn how attackers can manipulate your application into running dangerous system commands—and how to stop them.
What Is Command Injection?
Command injection occurs when your application passes user-controlled input directly to the operating system shell without proper validation. Instead of just executing your intended command, an attacker can inject additional commands that the OS will run with your application's privileges.
Think of it like giving someone instructions to "open the door labeled [user input]." If they type "main door; also unlock the safe," you've just executed two commands instead of one.
How It Works
When your code uses functions that invoke the system shell (like system(), exec(), or shell_exec()), special characters like ;, |, &, $(), and backticks have special meaning. An attacker can exploit these:
# Intended: ping 192.168.1.1
# Injected: ping 192.168.1.1; rm -rf /
The semicolon terminates the first command and starts a second, potentially catastrophic one.
Prevention Strategies
Never pass unsanitized user input to shell commands. If you must interact with the OS:
- Avoid shell execution entirely - Use language-native APIs instead (like file system libraries rather than
lscommands) - Use parameterized command APIs - Functions that separate the command from arguments without invoking a shell
- Strict allowlisting - Only permit predefined, safe values
- Escape shell metacharacters - Though risky and error-prone
- Run with minimal privileges - Apply the principle of least privilege
The safest approach is avoiding OS commands altogether when processing user input.
Key Takeaway: Command injection lets attackers execute arbitrary system commands through unsanitized user input passed to shell functions—prevent it by avoiding shell invocation entirely or using secure, parameterized alternatives that don't interpret special characters.