CWE-95 Variant Incomplete 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…

Definition

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.
Real-world impact

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.

How attackers exploit it

Step-by-step attacker path

  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.

Vulnerable code example

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";
  }
Attacker payload

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:

Attacker payload
add_key(",","); system("/bin/ls");
Secure code example

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.

Secure 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.
Prevention checklist

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].
Detection signals

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

Plexicus auto-fix

Plexicus auto-detects CWE-95 and opens a fix PR in under 60 seconds.

Codex Remedium scans every commit, identifies this exact weakness, and ships a reviewer-ready pull request with the patch. No tickets. No hand-offs.

Frequently asked questions

Frequently asked questions

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.

How serious is CWE-95?

MITRE rates the likelihood of exploit as Medium — exploitation is realistic but typically requires specific conditions.

What languages or platforms are affected by CWE-95?

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

How can I prevent 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…

How does Plexicus detect and fix CWE-95?

Plexicus's SAST engine matches the data-flow signature for CWE-95 on every commit. When a match is found, our Codex Remedium agent opens a fix PR with the corrected code, tests, and a one-line summary for the reviewer.

Where can I learn more about CWE-95?

MITRE publishes the canonical definition at https://cwe.mitre.org/data/definitions/95.html. You can also reference OWASP and NIST documentation for adjacent guidance.

Ready when you are

Don't Let Security
Weigh You Down.

Stop choosing between AI velocity and security debt. Plexicus is the only platform that runs Vibe Coding Security and ASPM in parallel — one workflow, every codebase.