Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)
Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
This vulnerability occurs when an application takes user input and passes it directly into a dynamic code execution function, like eval(), without properly sanitizing it. This allows an attacker to…
What is CWE-95?
Real-world CVEs caused by CWE-95
-
Framework for LLM applications allows eval injection via a crafted response from a hosting provider.
-
Python compiler uses eval() to execute malicious strings as Python code.
-
Chain: regex in EXIF processor code does not correctly determine where a string ends (CWE-625), enabling eval injection (CWE-95), as exploited in the wild per CISA KEV.
-
Chain: backslash followed by a newline can bypass a validation step (CWE-20), leading to eval injection (CWE-95), as exploited in the wild per CISA KEV.
-
Eval injection in PHP program.
-
Eval injection in Perl program.
-
Eval injection in Perl program using an ID that should only contain hyphens and numbers.
-
Direct code injection into Perl eval function.
Ruta del atacante paso a paso
- 1
edit-config.pl: This CGI script is used to modify settings in a configuration file.
- 2
The script intends to take the 'action' parameter and invoke one of a variety of functions based on the value of that parameter - config_file_add_key(), config_file_set_key(), or config_file_delete_key(). It could set up a conditional to invoke each function separately, but eval() is a powerful way of doing the same thing in fewer lines of code, especially when a large number of functions or variables are involved. Unfortunately, in this case, the attacker can provide other values in the action parameter, such as:
- 3
This would produce the following string in handleConfigAction():
- 4
Any arbitrary Perl code could be added after the attacker has "closed off" the construction of the original function call, in order to prevent parsing errors from causing the malicious eval() to fail before the attacker's payload is activated. This particular manipulation would fail after the system() call, because the "_key(\$fname, \$key, \$val)" portion of the string would cause an error, but this is irrelevant to the attack because the payload has already been activated.
- 5
This simple script asks a user to supply a list of numbers as input and adds them together.
Vulnerable Perl
edit-config.pl: This CGI script is used to modify settings in a configuration file.
use CGI qw(:standard);
sub config_file_add_key {
my ($fname, $key, $arg) = @_;
```
# code to add a field/key to a file goes here*
}
sub config_file_set_key {
```
my ($fname, $key, $arg) = @_;
```
# code to set key to a particular file goes here*
}
sub config_file_delete_key {
```
my ($fname, $key, $arg) = @_;
```
# code to delete key from a particular file goes here*
}
sub handleConfigAction {
```
my ($fname, $action) = @_;
my $key = param('key');
my $val = param('val');
```
# this is super-efficient code, especially if you have to invoke*
*# any one of dozens of different functions!*
my $code = "config_file_$action_key(\$fname, \$key, \$val);";
eval($code);}
$configfile = "/home/cwe/config.txt";
print header;
if (defined(param('action'))) {
```
handleConfigAction($configfile, param('action'));
}
else {
print "No action specified!\n";
} The script intends to take the 'action' parameter and invoke one of a variety of functions based on the value of that parameter - config_file_add_key(), config_file_set_key(), or config_file_delete_key(). It could set up a conditional to invoke each function separately, but eval() is a powerful way of doing the same thing in fewer lines of code, especially when a large number of functions or variables are involved. Unfortunately, in this case, the attacker can provide other values in the action parameter, such as:
add_key(",","); system("/bin/ls"); Secure Python
A way to accomplish this without the use of eval() is to apply an integer conversion on the input within a try/except block. If the user-supplied input is not numeric, this will raise a ValueError. By avoiding eval(), there is no opportunity for the input string to be executed as code.
def main():
sum = 0
numbers = input("Enter a space-separated list of numbers: ").split(" ")
try:
for num in numbers:
sum = sum + int(num)
print(f"Sum of {numbers} = {sum}")
except ValueError:
print("Error: invalid input")
main() How to prevent CWE-95
- Architecture and Design / Implementation If possible, refactor your code so that it does not need to use eval() at all.
- Implementation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
- Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
- Implementation For Python programs, it is frequently encouraged to use the ast.literal_eval() function instead of eval, since it is intentionally designed to avoid executing code. However, an adversary could still cause excessive memory or stack consumption via deeply nested structures [REF-1372], so the python documentation discourages use of ast.literal_eval() on untrusted data [REF-1373].
How to detect CWE-95
Plexicus detecta automáticamente CWE-95 y abre un PR de corrección en menos de 60 segundos.
Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.
Frequently asked questions
¿Qué es CWE-95?
This vulnerability occurs when an application takes user input and passes it directly into a dynamic code execution function, like eval(), without properly sanitizing it. This allows an attacker to inject and execute arbitrary code within the application's context.
¿Qué gravedad tiene CWE-95?
MITRE califica la probabilidad de explotación como Media — la explotación es realista pero suele requerir condiciones específicas.
¿Qué lenguajes o plataformas se ven afectados por CWE-95?
MITRE lists the following affected platforms: Java, JavaScript, Python, Perl, PHP, Ruby, Interpreted, AI/ML.
¿Cómo puedo prevenir CWE-95?
If possible, refactor your code so that it does not need to use eval() at all. Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable…
¿Cómo detecta y corrige Plexicus CWE-95?
El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-95 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.
¿Dónde puedo aprender más sobre CWE-95?
MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/95.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.
Weaknesses related to CWE-95
Improper Control of Generation of Code ('Code Injection')
This vulnerability occurs when an application builds executable code using unvalidated external input, such as user data. Because the…
Improper Neutralization of Special Elements Used in a Template Engine
This vulnerability occurs when an application uses a template engine to process user-controlled input but fails to properly sanitize…
Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')
Static Code Injection occurs when an application incorporates unvalidated or improperly sanitized user input directly into a static,…
Further reading
- MITRE — CWE-95 oficial https://cwe.mitre.org/data/definitions/95.html
- How ast.literal_eval can cause memory exhaustion https://www.reddit.com/r/learnpython/comments/zmbhcf/how_astliteral_eval_can_cause_memory_exhaustion/
- ast - Abstract Syntax Trees https://docs.python.org/3/library/ast.html#ast.literal_eval
Deja de pagar por desarrollador.
Empieza a cerrar el bucle.
Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.