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…

Definição

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

Como os atacantes a exploram

Trajeto do atacante passo a passo

  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.

Exemplo de código vulnerável

Vulnerable Perl

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

Vulnerável 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 do 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 do atacante
add_key(",","); system("/bin/ls");
Exemplo 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 verificação de prevenção

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].
Sinais de deteção

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

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-95 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o 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.

Qual a gravidade do CWE-95?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

Que linguagens ou plataformas são afetadas pelo CWE-95?

MITRE lists the following affected platforms: Java, JavaScript, Python, Perl, PHP, Ruby, Interpreted, AI/ML.

Como posso prevenir o 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…

Como é que o Plexicus deteta e corrige o CWE-95?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-95 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-95?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/95.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.