CWE Glossary

CWE is a trademark of the MITRE Corporation.

Stay in touch

Application security insights and invitations to exclusive events in your inbox


Your data will stay confidential Private and Confidential

OS Command Injection [CWE-78]

This weakness describes improper neutralization of special elements, which could result in modification of the intended OS command that is sent to a downstream component.

Created: September 11, 2012
Latest Update: November 19, 2018

Table of Content

  1. Description
  2. Potential impact
  3. Attack patterns
  4. Affected software
  5. Exploitation Examples
  6. Severity and CVSS Scoring
  7. Mitigations
  8. Vulnerability Remediation Techniques and Examples
  9. References
  10. Latest Related Security Advisories

1. Description

An attacker can execute malicious commands on a target operating system. OS command injection weaknesses can expose an environment to an attacker even if he does not have direct access to the operating system.

If the weakness occurs in a high privileged program, it may allow an attacker to specify commands that would not be available otherwise, or call alternate commands with privileges that the attacker does not have.

The danger of this weakness is aggravated if the breached process does not follow the principle of the least privilege because the malicious command may gain system privileges and allow the attacker to cause additional damage.

There are two major subtypes of OS Command Injection:

  • An application is going to execute a fixed program that is under its control and accepts external input as arguments to that program.

    Example: The program uses the system("nslookup [HOSTNAME]") call to run nslookup and the HOSTNAME is given as an argument by the user. The hacker cannot prevent nslookup from executing, but if the program does not remove separators from the externally supplied HOSTNAME argument, the attacker could place separators inside the argument and execute his own command.

  • The application uses input to select which program to run and what commands to use. The application sanitizes the input and then simply redirects the entire command to the operating system.

    Example: Application uses exec([COMMAND]) whereas [COMMAND] is supplied from and external source. The hacker that controls [COMMAND] argument can execute arbitrary commands or programs on the system.

2. Potential impact

An attacker can leverage this weakness to execute arbitrary commands, disclose sensitive information and cause denial of service. Any malicious activities would appear to come from the vulnerable application and will be executed in the security context of that application.

3. Attack patterns

The following CAPEC (Common Attack Pattern Enumeration and Classification) vectors are related to OS command injection weakness:


In an alternative WASC Threat Classification this weakness is described as an attack technique under WASC-31.

4. Affected software

Software that uses external input to send commands to the operating system can be vulnerable to this weakness. The weakness is common for many web applications.

5. Exploitation Examples

Let's have a look at vulnerability #2 in HTB23069 security advisory (CVE-2012-0992). Exploitation requirements dictate that user is logged-in into the application.

After successful authentication, apply the PoC code from the advisory:
http://[host]/interface/fax/fax_dispatch.php?file=1%27%20||%20ls%20%2Dla%20%3E%20123%20||

Execution result is shown on the image below:

HTB23069 advisory (CVE-2012-0992) CWE-78 PoC exploitation example

This PoC code creates a file named 123 in the current directory with output of the "ls –la" command. We can access the file directly to view its contents:

HTB23069 advisory (CVE-2012-0992) CWE-78 PoC exploitation example

This vulnerability can be used by any authenticated user to execute arbitrary commands on the target system with the privileges of the webserver as well as completely compromise the vulnerable application.

6. Severity and CVSS Scoring

When scoring OS Command Injection weaknesses, security specialists must consider the maximum possible impact. If an attacker can execute arbitrary commands with privileges of a system user the vulnerability must be scored as C:C/I:C/A:C.

In the case of web applications, when an attacker has no access to the system, we recommend to use the following score: C:C/I:C/A:C. It contradicts recommendations of FIRST but is fair in our opinion.

Usually OS command injection vulnerabilities in web applications are scored with maximum confidentiality, integrity and availability ratings:
10 (AV:N/AC:L/Au:N/C:C/I:C/A:C) - Critical severity.

HTB22922 security advisory - (PHP command execution in phpAlbum.net) can be used as an example of this score.

The CVSS score may depend on certain conditions such as knowledge of user credentials. HTB23069 security advisory (CVE-2012-0992) is scored as:
9 (AV:N/AC:L/Au:S/C:C/I:C/A:C) - Critical severity.

To exploit this vulnerability the user must be authenticated within the application.


We use the CVSSv2 scoring system in our HTB Security Advisories to calculate the risk of the discovered vulnerabilities. Not all of the vulnerabilities are scored in strict accordance to FIRST recommendations. Our CVSSv2 scores are based on our long internal experience in software auditing and penetration testing, taking into consideration a lot of practical nuances and details. Therefore, sometimes they may differ from those ones that are recommended by FIRST.

7. Mitigations

To defend systems from this weakness, developers need to use library calls when possible, to create the desired functionality without external input. When external input is inescapable, developers need to use secure input and output handling. Sanitizing functions that attempt to catch each potentially dangerous character are prone to bypasses, a safer approach is to ensure that the data appears as it should before being processed, by using an appropriate regular expression.

As a temporary solution we strongly recommend blocking access to the vulnerable script until the issue is resolved. This can be achieved either using native functionality of the webserver or changing system access permissions to file.

Apache

Edit the configuration of your virtual host (usually this can be done via ".htaccess" file) and add the following lines:
<Files script.php>
order deny,allow
deny from all
</Files>

You can also allow access to file from specific IP address:
<Files script.php>
order deny,allow
deny from all
allow from 10.0.0.1
</Files>

IIS

Edit the web.config file to limit access to the vulnerable "script.aspx":
The following rule allows access from IP address 10.0.0.1 and from subnet 192.168.0.0/24. Access from other IP addresses is restricted:
<configuration>
  <location path="script.aspx">
    <system.webServer>
      <security>
        <ipSecurity>
        <add ipAddress="10.0.0.1" />
        <add ipAddress="192.168.0.0" subnetMask="255.255.255.0" />
      </ipSecurity>
      </security>
    </system.webServer>
  </location>
</configuration>

You can also allow or restrict access to certain systems groups. The following configuration example allows only members of the "Administrators" group to access the vulnerable "script.aspx" file:
<configuration>
  <location path="script.aspx">
    <system.webServer>
      <security>
        <authorization>
          <remove users="*" roles="" verbs="" />
          <add accessType="Allow" roles="Administrators" />
        </authorization>
      </security>
    </system.webServer>
  </location>
</configuration>

Tomcat

Add the following lines to your web.xml configuration file for a specific web application to restrict access to "script.jsp" file:
<security-constraint>
  <web-resource-collection>
    <web-resource-name>Forbidden</web-resource-name>
    <url-pattern>/script.jsp</url-pattern>
  </web-resource-collection>
  <auth-constraint />
</security-constraint>

nginx

Add the following rule to the "nginx.conf" file to restrict access to the "script.php" file located in the webroot folder:
location /script.php {
  deny all;
}

8. Vulnerability Remediation Techniques and Examples

8.1 General recommendations for software developers

All parameters should be enclosed in quotes in most cases to prevent successful exploitation of the vulnerability. Special symbols within parameter values must be escaped or replaced by safe symbols. Sometimes it is necessary to subtract all special symbols and spaces.

Assume that the "param" variable receives input via HTTP GET or HTTP POST request and then is used as a part of the filename within functions that manipulate files. In this case developers should follow instructions below to avoid the appearance of vulnerable code.

The following examples demonstrate sanitation of input data for popular programming languages:

PHP
  1. $param=escapeshellarg($param);
  2. system(«nslookup $param»);
or
  1. $param=preg_replace("/[^a-z0-9\-\.]/i", "", $param);
  2. system("nslookup $param");
PERL
  1. $param=~s/[^a-z0-9\-\.]//gi;
  2. $param="\"".$param."\"";
  3. system("nslookup ".$param);
ASP.NET
  1. <asp:RegularExpressionValidator runat="server" id="ParamValidator" ControlToValidate="param" ErrorMessage="Invalid input. You are allowed to enter characters and digits only" ValidationExpression="^[a-zA-Z0-9\-\.]" />
ColdFusion
  1. <cfscript>
  2. param=ReReplace(param,'[^a-z0-9\-\.]','','all');
  3. </cfscript>
Python
  1. param = re.sub("[^a-zA-Z0-9\-\.]+", "_", param)
JAVA/JSP
  1. param.replaceAll("[^a-z0-9\-\.]","");

These are general recommendations. Every case must be treated separately, considering application logic, peculiarities of each system and required functionality.

Caution: do not blindly copy-paste the above-mentioned solutions into your application code. In some cases this may result in incorrect behavior of the application or inconsistent patch. Carefully read the References or consult security specialists in case you are not sure how to patch a vulnerability.

8.2 Using Web Application Firewall (WAF)

Web Application Firewall can be an efficient solution to prevent vulnerability exploitation while you are developing or waiting for a security patch. We do not recommend using WAF as a long-term solution, neither as a replacement to properly developed security patch.

As an example, we will use an open source web application firewall ModSecurity developed by Trustwave. There are many rule sets for ModSecurity licensed under ASLv2 and widely distributed by security companies and organizations. These rule sets can be applied to cover all basic cases of vulnerabilities’ exploitation and can be used on production servers.

The following rule is part of the core rule set modsecurity_crs_40_generic_attacks.conf and can be used to protect web application against basic command injection attacks:

SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* "(?i:(?:[\;\|\`]\W*?\bcc|\b(wget|curl))\b|\/cc(?:[\'\"\|\;\`\-\s]|$))" "phase:2,rev:'2',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'8',capture, t:none, t:normalisePath,ctl:auditLogParts=+E,block,msg:'System Command Injection',id:'950907', tag:'OWASP_CRS/WEB_ATTACK/COMMAND_INJECTION', tag:'WASCTC/WASC-31',tag:'OWASP_TOP_10/A1',tag:'PCI/6.5.2',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-OWASP_CRS/WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0},skipAfter:END_COMMAND_INJECTION1"
SecMarker END_COMMAND_INJECTION1

The rule searches for “bcc”, “wget”, “curl” and “cc” substrings within the request. OS command injection is hard to detect and block this way because there might be numerous ways to execute commands on the system.

Let’s have a look at OS command injection vulnerability in CosCms described in HTB23145 (CVE-2013-1668). The application uses the PHP "exec()" function to perform certain actions on the uploaded file. An attacker can create an HTTP POST request with a specially crafted filename and execute arbitrary commands on the system, as demonstrated by the PoC code. To mitigate this vulnerability we will have to validate filenames and allow only safe characters:

SecRule FILES_NAMES|FILES "!^([a-zA-Z\.0-9\:\\\\]+)$" "phase:2,rev:'2',ver:'HTBRIDGE /0.1',maturity:'9',accuracy:'7', t:none, ctl:auditLogParts=+E,block,msg:'OS Command Injection in CosCms HTB23145',id:'1000000002',severity:'2',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',capture,tag:'HTBRIDGE/WEB_ATTACK/OS',setvar:'tx.msg=%{rule.msg}'"

9. References

  1. CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') [cwe.mitre.org]
  2. OS Command Injection [www.owasp.org]
  3. Least Privilege [buildsecurityin.us-cert.gov]
  4. Top 25 Series - Rank 9 - OS Command Injection [software-security.sans.org]
  5. The World Wide Web Security FAQ: 6. CGI (Server) Scripts [www.w3.org]
  6. CS390S, Week 9:Meta-Character Vulnerabilities [www.cs.purdue.edu]

10. Latest HTB Security Advisories with CWE-78


Copyright Disclaimer: Any above-mentioned content can be copied and used for non-commercial purposes only if proper credit to High-Tech Bridge is given.

↑ Back to Top
High-Tech Bridge on Facebook High-Tech Bridge on Twitter High-Tech Bridge on LinkedIn High-Tech Bridge RSS Feeds Send by Email
Share
Let's Talk