CWE Glossary
- CWE-22: Path Traversal
- CWE-78: OS Command Injection
- CWE-79: Cross-Site Scripting
- CWE-89: SQL Injection
- CWE-90: LDAP Injection
- CWE-91: XML Injection
- CWE-94: Code Injection
- CWE-98: PHP File Inclusion
- CWE-113: HTTP Response Splitting
- CWE-119: Buffer Errors
- CWE-130: Improper Handling of Length Parameter Inconsistency
- CWE-193: Off-by-one Error
- CWE-200: Information Exposure
- CWE-211: Information Exposure Through Externally-Generated Error Message
- CWE-236: Improper Handling of Undefined Parameters
- CWE-276: Incorrect Default Permissions
- CWE-284: Improper Access Control
- CWE-285: Improper Authorization
- CWE-287: Improper Authentication
- CWE-297: Improper Validation of Certificate with Host Mismatch
- CWE-306: Missing Authentication for Critical Function
- CWE-312: Cleartext Storage of Sensitive Information
- CWE-345: Insufficient Verification of Data Authenticity
- CWE-352: Cross-Site Request Forgery
- CWE-384: Session Fixation
- CWE-427: Uncontrolled Search Path Element
- CWE-434: Unrestricted Upload of File with Dangerous Type
- CWE-476: NULL Pointer Dereference
- CWE-521: Weak Password Requirements
- CWE-601: Open Redirect
- CWE-611: Improper Restriction of XML External Entity Reference ('XXE')
- CWE-613: Insufficient Session Expiration
- CWE-618: Exposed Unsafe ActiveX Method
- CWE-671: Lack of Administrator Control over Security
- CWE-798: Use of Hard-coded Credentials
- CWE-799: Improper Control of Interaction Frequency
- CWE-822: Untrusted Pointer Dereference
- CWE-835: Infinite Loop
- CWE-918: Server-Side Request Forgery (SSRF)
- CWE-942: Overly Permissive Cross-domain Whitelist
CWE is a trademark of the MITRE Corporation.
Code Injection [CWE-94]
Code Injection weakness describes improper control of code generation.
Created: September 11, 2012
Latest Update: December 28, 2020
Table of Content
- Description
- Potential impact
- Attack patterns
- Affected software
- Exploitation Examples
- Severity and CVSS Scoring
- Mitigations
- Vulnerability Remediation Techniques and Examples
- References
- 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:
- $var ="param";
- $sInput = $_GET["param"];
- 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:
- CAPEC-35: Leverage Executable Code in Nonexecutable Files
- CAPEC-77: Manipulating User-Controlled Variables
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:
The server will return the following data containing output of the injected command:
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:
PHP
- $param=preg_replace("/[^a-z0-9]/i", "", $param);
PERL
- $param=~s/[^a-z0-9]//gi;
ASP.NET
- <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
- <cfscript>
- param=ReReplace(param,'[^A-Za-z0-9]','','all');
- </cfscript>
- <cfscript>
- param=ReReplace(param,'[^[:alnum:]]','','all');
- </cfscript>
Python
- param = re.sub("[^a-zA-Z0-9\-_]+", "_", param)
JAVA/JSP
- 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
- CWE-94: Improper Control of Generation of Code ('Code Injection') [cwe.mitre.org]
- Code Injection [www.owasp.org]
10. Code Injection Vulnerabilities, Exploits and Examples
- HTB23290: Remote Code Execution in Exponent
- HTB23255: Arbitrary Variable Overwrite in eShop WordPress Plugin
- HTB23212: CSRF and Remote Code Execution in EGroupware
- HTB23198: Multiple Vulnerabilities in Eventum
- HTB23173: Remote Code Execution in GLPI
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