Command Injection
What is Command Injection?¶
- Exploiting an application to execute OS commands with the application's privileges.
- Also known as Remote Code Execution (RCE).
- Example: Command injection on a web server running as user "joe" executes commands as "joe."
Discovering Command Injection¶
- How it Works: Programming languages use functions to make system calls. User input is passed to these functions, creating the vulnerability.
- Example Scenario:
- Application stores MP3 files.
- User inputs a song title (
$titlevariable). $titleis passed togrepto searchsongtitle.txt.- Output determines if the song exists. Vulnerability: User input is directly used in the command.

Exploiting Command Injection¶
- Command Combination: Use shell operators (
;,&,&&) to execute multiple commands at once.&&does not work on Windows. - Detection Methods:
- Blind: No direct output. Investigate application behavior.
- Use
pingorsleepfor time delays. - Redirect output with
>. - Use
curlfor out-of-band communication.
- Use
- Verbose: Direct feedback from the application. Example:
whoamireveals the user the application runs as.
- Blind: No direct output. Investigate application behavior.
Remediating Command Injection¶
- Vulnerable Functions: Avoid using functions that directly interact with the OS (e.g.,
exec(),passthru(),system()in PHP). -
Input Validation: Sanitize user input.
- Specify accepted data formats/types (e.g., only numerical data).
- Remove special characters (
>,&,/).

-
Whitelisting: Use a whitelist of allowed characters or inputs. This is much better than blacklisting.
- Parameterization/Prepared Statements: Treat user input as data, not as commands. This is the most effective defense.
- Principle of Least Privilege: Run applications with minimal necessary privileges. Limit the impact of a successful command injection attack.
- Encoding: Encode user input to prevent special characters from being interpreted as commands.