CWE-95 Variante Incompleto Medium likelihood

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…

Definición

What is 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.
Eval injection is a critical flaw where untrusted data, such as a URL parameter or form field, is fed directly into a function that interprets a string as code. Functions like eval(), setTimeout() with strings, or new Function() are common culprits. When an attacker can control this input, they can break out of the intended data context and inject malicious commands, potentially taking over the application's process, accessing sensitive data, or compromising the server. To prevent this, developers must avoid using dynamic code evaluation entirely whenever possible. If it's unavoidable, the only robust defense is strict input validation using a whitelist of permitted characters and patterns. Never rely on blacklisting or simple escaping, as these methods are error-prone and often bypassed. Instead, use safe language features or APIs designed for the task, such as parameterized queries for databases or JSON parsers for data structures.
Vulnerability Diagram CWE-95
Eval Injection user calc input 2+2);steal();// JavaScript handler eval("calc(" + input + ")") → calc(2+2);steal();//) eval = full JS engine JS engine runs attacker's code eval() makes any string injectable as runtime code.
Impacto en el mundo real

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.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    edit-config.pl: This CGI script is used to modify settings in a configuration file.

  2. 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. 3

    This would produce the following string in handleConfigAction():

  4. 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. 5

    This simple script asks a user to supply a list of numbers as input and adds them together.

Ejemplo de código vulnerable

Vulnerable Perl

edit-config.pl: This CGI script is used to modify settings in a configuration file.

Vulnerable Perl
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";
  }
Payload del atacante

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:

Payload del atacante
add_key(",","); system("/bin/ls");
Ejemplo de código seguro

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.

Seguro Python
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()
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de prevención

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].
Señales de detección

How to detect CWE-95

Automated Static Analysis High

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.)

Auto-corrección de Plexicus

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.

Preguntas frecuentes

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.

Listo cuando tú lo estés

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.