CWE-95 Variante Incomplet 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…

Définition

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.
Impact réel

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.

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  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.

Exemple de code vulnérable

Vulnerable Perl

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

Vulnérable 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";
  }
Charge utile de l'attaquant

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:

Charge utile de l'attaquant
add_key(",","); system("/bin/ls");
Exemple de code sécurisé

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.

Sécurisé 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.
Liste de contrôle de prévention

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].
Signaux de détection

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

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-95 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que 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.

Quelle est la gravité de CWE-95 ?

MITRE évalue la probabilité d'exploitation comme Moyenne — l'exploitation est réaliste mais nécessite généralement des conditions spécifiques.

Quels langages ou plateformes sont affectés par CWE-95 ?

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

Comment puis-je prévenir 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…

Comment Plexicus détecte et corrige CWE-95 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-95 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-95 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/95.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.