Code Injection
ID |
php.code_injection |
Severity |
critical |
Resource |
Injection |
Language |
Php |
Tags |
CWE:95, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1 |
Description
Improper neutralization of directives in dynamically evaluated code ('Eval Injection').
Code Injection vulnerabilities occur when an application dynamically executes code containing untrusted input from users.
Rationale
Code Injection vulnerabilities in PHP arise when user input is directly evaluated or executed by the application. This typically occurs through the use of functions like eval()
, create_function()
, or when improperly handling serialized input using functions like unserialize()
. Unsanitized input can lead to the execution of arbitrary PHP code, possibly allowing an attacker to manipulate the server environment, access sensitive data, or escalate privileges.
Consider the following PHP example, where a user-supplied string is evaluated directly:
<?php
$code = $_GET['code'];
eval($code);
?>
In this problematic example, any PHP code passed as a code
query parameter will be executed by the server. This could be exploited by an attacker to execute arbitrary commands, modify files, or extract sensitive information.
Remediation
To mitigate Code Injection vulnerabilities, follow these best practices:
-
Avoid Dynamic Code Execution: Where possible, avoid using dynamic script execution or reflection with untrusted input.
-
Input Validation and Sanitization: Assume all input is potentially malicious. Rigorously validate all user inputs to confirm they adhere to expected formats, and sanitize them (a whitelisting approach is recommended) to remove potentially harmful content.
-
Canonicalization: Decode and canonicalize inputs to a standard internal representation before validation. This helps prevent bypassing input filters through encoding tricks
The rewritten example of safer PHP code excluding code execution using eval()
:
<?php
$input = $_GET['input'];
// Implement strict validation
if (isSafe($input)) {
// Perform action based on validated input
} else {
// Handle invalid input
echo 'Invalid input!';
}
function isSafe($input)
{
// Implement specific validation logic
return preg_match('/^[a-zA-Z0-9]+$/', $input);
}
?>
Configuration
The detector has the following configurable parameters:
-
sources
, that indicates the source kinds to check. -
neutralizations
, that indicates the neutralization kinds to check.
Unless you need to change the default behavior, you typically do not need to configure this detector.
References
-
CWE-95 : Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection').
-
OWASP Top 10 2021 - A03 : Injection.
-
OWASP Code Injection explained.