Total Tests:

CWE Glossary

CWE is a trademark of the MITRE Corporation.

Stay in Touch

Get exclusive updates and invitations to our events and webinars:

Your data will stay confidential Private and Confidential

Code Injection [CWE-94]

Code Injection weakness describes improper control of code generation.

Code Injection [CWE-94]

Created: September 11, 2012
Latest Update: December 28, 2020

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

Want to have an in-depth understanding of all modern aspects of
Code Injection [CWE-94]? Read carefully this article and bookmark it to get back later, we regularly update this page.

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:

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.

How to Detect Code Injection Vulnerabilities
Website Security Test
  • GDPR & PCI DSS Test
  • Website CMS Security Test
  • CSP & HTTP Headers Check
  • WordPress & Drupal Scanning
Try For Free

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:
6.1 [CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/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:

But if injection occurs within PHP code, the vulnerability could be used to compromise the entire system and it should be scored as:
9.8 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H] - Critical severity.

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:

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

10. Code Injection Vulnerabilities, Exploits and Examples

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

↑ Back to Top
Book a Call Ask a Question
Talk to ImmuniWeb Experts
ImmuniWeb AI Platform
Have a technical question?

Our security experts will answer within
one business day. No obligations.

Have a sales question?
Tel: +41 22 560 6800 (Switzerland)
Tel: +1 720 605 9147 (USA)
Your data will stay private and confidential