OS Command Injection
OS Command Injection
OS command injection is a web security vulnerability that allows an attacker to execute arbitrary OS commands on the server that is running an application, and typically fully compromise the application and all its data.
Very often, an attacker can leverage an OS command injection vulnerability to compromise other parts of the hosting infrastructure, exploiting trust relationships to pivot the attack to other systems within the organization.
Consider the following PHP code:
$dir = $_GET['input'];
system("echo " . $dir);
The program expects a string and simply prints that string on the screen. However, if we feed in a payload
%3Bis the URL encoding of
;), then id will be executed and the output of
idwill be printed on the screen.
In Linux, there are three ways for multiple command execution:
command1 && command2:
command1 || command2:
command1 ; command2:
In Linux, there are two ways for command substitution:
`command`: the string inside the backticks will be interpreted as command.
$(command): essentially the same as backticks.
When you have identified an OS command injection vulnerability, it is generally useful to execute some initial commands to obtain information about the system that you have compromised. Below is a summary of some commands that are useful on Linux and Windows platforms:
Many instances of OS command injection are blind vulnerabilities. This means that the application does not return the output from the command within its HTTP response. Blind vulnerabilities can still be exploited, but different techniques are required.
Consider a web site that lets users submit feedback about the site. The user enters their email address and feedback message. The server-side application then generates an email to a site administrator containing the feedback. To do this, it calls out to the
The output from the
echopayload would not be effective. In this situation, you can use a variety of other techniques to detect and exploit a vulnerability.
By far the most effective way to prevent OS command injection vulnerabilities is to never call out to OS commands from application-layer code. In virtually every case, there are alternate ways of implementing the required functionality using safer platform APIs.
If it is considered unavoidable to call out to OS commands with user-supplied input, then strong input validation must be performed. Some examples of effective validation include:
- Validating against a whitelist of permitted values.
- Validating that the input is a number.
- Validating that the input contains only alphanumeric characters, no other syntax or whitespace.
Never attempt to sanitize input by escaping shell metacharacters. In practice, this is just too error-prone and vulnerable to being bypassed by a skilled attacker.