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

Code Injection [CWE-94]

This weakness describes improper control of code generation.

Created: September 11, 2012
Latest Update: August 5, 2015

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

This weakness describes a situation where software uses untrusted input to contrast all parts of code and does not perform or incorrectly performs neutralization of special characters that might influence syntax or behavior of the code segment.

Basically an attacker might be able to inject and execute arbitrary code within the application. The following example in PHP demonstrates usage of the eval() function in untrusted input:

  1. $var ="param";
  2. $sInput = $_GET["param"];
  3. Eval("\$var=\$sInput;");

An attacker is able to pass in the "param" parameter arbitrary PHP code which will be executed:
http://[host]/script.php?param=1;phpinfo();

The above example demonstrates call to the phpinfo() function. This weakness could be exploited further to execute arbitrary OS commands on the target system via system() call.

2. Potential impact

The maximum impact of this weakness depends on software design and implementation. This weakness may allow an attacker to execute arbitrary code within the application and to compromise the vulnerable system.

3. Attack patterns

There are following CAPEC attack patterns which correspond to this weakness:


This weakness is not described as an attack technique in WASC Threat Classification database.

4. Affected software

Any software that evaluates untrusted input or uses it to construct code is potentially vulnerable to this weakness.

5. Exploitation Examples

Let's have a look at HTB23070 security advisory (CVE-2012-0993).

Successful exploitation of the vulnerability requires that the "viewer_size_image" plugin is active.

To demonstrate the vulnerability we will use a simple telnet utility to alter the HTTP query and set a specially crafted COOKIE value for the "viewer_size_image_saved" parameter, as shown on the image below:

HTB23070 advisory (CVE-2012-0993) CWE-94 PoC exploitation example

The server will return the following data containing output of the injected command:

HTB23070 advisory (CVE-2012-0993) CWE-94 PoC exploitation example

The output contains details of the installed PHP version, this means that the "phpinfo()" function is executed successfully. An attacker can execute arbitrary PHP code on the target system and gain complete control over it.

6. Severity and CVSS Scoring

Severity of the vulnerability depends on the language that was used to create the application. If injection occurs within javascript code the maximum potential impact is cross-site scripting. In case of reflected XSS it should be scored as:
4.3 (AV:N/AC:M/Au:N/C:N/I:P/A:N) - Medium severity.

If javascript code can be stored in database or files and then executed in the browser it should be scored as:
5 (AV:N/AC:L/Au:N/C:N/I:P/A:N) – Medium severity.

But if injection occurs within PHP code, the vulnerability could be used to compromise the entire system and it should be scored as:
10 (AV:N/AC:L/Au:N/C:C/I:C/A:C) - Critical severity.

Metrics can vary depending on additional exploitation requirements. For example, vulnerability described in the HTB23093 security advisory (CVE-2012-2931) is scored as AV:N/AC:L/Au:S/C:C/I:C/A:C - 9.0, because an attacker needs to be authenticated within the application first.


We use 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

The usage of untrusted input to construct parts of code is considered poor practice. Developers should avoid using raw input data to construct code. If code generation depends on external input predefined choices should be used.

8. Vulnerability Remediation Techniques and Examples

8.1 General recommendations for software developers

In most cases, it is enough to remove all potentially dangerous symbols to defend the application. Assume that the "param" parameter is passed via HTTP GET or POST request to the application and is later used in the eval() function. The examples below demonstrate usage of regular expressions in popular languages to remove potentially dangerous symbols and make the input data safe:

PHP
  1. $param=preg_replace("/[^a-z0-9]/i", "", $param);
PERL
  1. $param=~s/[^a-z0-9]//gi;
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-Za-z0-9]','','all');
  3. </cfscript>
or
  1. <cfscript>
  2.   param=ReReplace(param,'[^[:alnum:]]','','all');
  3. </cfscript>
Python
  1. param = re.sub("[^a-zA-Z0-9\-_]+", "_", param)
JAVA/JSP
  1. param = param.replaceAll("[^A-Za-z0-9]", "");

These are general recommendations. Every case must be treated separately, considering logic of the way the application works, as well as singularity of the system and tasks. Direct coping of the data into the code can cause disruption of the application function or improper patching of the vulnerability.

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.

Let’s have a look at PHP code injection vulnerability in TinyWebGallery descibed in HTB23093 (CVE-2012-2931). The application does not perform validation of the “user” HTTP POST parameter before writing data into .htusers.php file. We can eliminate this threat by allowing only alphabetical symbols in vulnerable parameter:

SecRule ARGS:user "!^([a-zA-Z]+)$" "phase:2,rev:'2',ver:'HTBRIDGE /0.1',maturity:'9',accuracy:'7', t:none,ctl:auditLogParts=+E, block,msg:'PHP Code Injection in TinyWebGallery HTB23093 ',id:'1000000007',severity:'2', logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}', capture,tag:'HTBRIDGE/WEB_ATTACK/PHP',setvar:'tx.msg=%{rule.msg}'"

9. References

  1. CWE-94: Improper Control of Generation of Code ('Code Injection') [cwe.mitre.org]
  2. Code Injection [www.owasp.org]

10. Latest HTB Security Advisories with CWE-94


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