Command Injection is a severe vulnerability where user input, under our control, influences web queries executing system commands. This allows executing commands directly on the server's backend, risking network compromise. Web programming languages provide functions to run OS commands, potentially used for tasks like installing plugins or running applications. Injecting malicious payloads into user input can alter commands, leading to unauthorized actions.
For instance, in a web application coded in PHP
, commands may be executed on the backend server using functions like exec
, system
, shell_exec
, passthru
, or popen
. Each of these functions serves a slightly different purpose.
The code below demonstrates a PHP vulnerability to command injections:
<?php
if (isset($_GET['filename'])) {
system("touch /tmp/" . $_GET['filename'] . ".pdf");
}
?>
This vulnerability isn't exclusive to PHP; it can occur in any web development framework or language. In a Node.js application, developers might utilize child_process.exec
or child_process.spawn
for similar functionalities.
The code below demonstrates a Node.js vulnerability to command injections:
app.get("/createfile", function(req, res){
child_process.exec(`touch /tmp/${req.query.filename}.txt`);
})
Detecting basic OS Command Injection vulnerabilities involves a similar process to exploiting them. We try appending our command through different injection methods. If the command output deviates from the expected result, we've successfully exploited the vulnerability.
If there is a fuction that create file that appears to ask us for a file name to create, we can guess that our input (file name) goes into a touch
command.
touch OUR_INPUT
So here we can test for OS command injection and see if the web application is vulnerable to OS command injection or not.
Detecting OS command injection involves testing the application's behavior with malicious input, checking for inadequate input validation, unexpected error messages, differences in command output, and time delays.
To inject an additional command to the intended one, we may use any of the following operators:
Injection Operator | Injection Character | URL-Encoded Character | Executed Command |
---|---|---|---|
Semicolon | ; |
%3b |
Both |
New Line | \\n |
%0a |
Both |
Background | & |
%26 |
Both (second output generally shown first) |
Pipe | ` | ` | %7c |
AND | && |
%26%26 |
Both (only if first succeeds) |
OR | ` | ` | |
Sub-Shell | ```` | %60%60 |
Both (Linux-only) |
Sub-Shell | $() |
%24%28%29 |
Both (Linux-only) |