---
title: "CWE-94: Improper Control of Generation of Code"
url: https://radicalnotion.ai/cwe/cwe-94
type: cwe
description: "The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment."
updated: 2026-11-10
source: RadicalNotion.AI
license: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/)
---

# CWE-94: Improper Control of Generation of Code

- **Abstraction:** Base
- **Structure:** Simple
- **Status:** Draft
- **Likelihood of exploit:** Medium
- **CVEs with this as primary weakness:** 5,961
- **Of those, in CISA KEV:** 74
- **New in 2026:** 1,435
- **CWE catalog version:** 4.21

## Description

The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.

## Alternate terms

- Code Injection

## Modes of introduction

| Phase | Note |
| --- | --- |
| Implementation | REALIZATION: This weakness is caused during implementation of an architectural security tactic. |

## Applicable platforms

**Languages:** Interpreted (Sometimes), Python (Undetermined)

**Technologies:** AI/ML (Undetermined)

## Common consequences

| Scope | Impact | Note |
| --- | --- | --- |
| Access Control | Bypass Protection Mechanism | In some cases, injectable code controls authentication; this may lead to a remote vulnerability. |
| Access Control | Gain Privileges or Assume Identity | Injected code can access resources that the attacker is directly prevented from accessing. |
| Integrity, Confidentiality, Availability | Execute Unauthorized Code or Commands | When a product allows a user's input to contain code syntax, it might be possible for an attacker to craft the code in such a way that it will alter the intended control flow of the product. As a result, code injection can often result in the execution of arbitrary code. Code injection attacks can also lead to loss of data integrity in nearly all cases, since the control-plane data injected is always incidental to data recall or writing. |
| Non-Repudiation | Hide Activities | Often the actions performed by injected control code are unlogged. |

## Potential mitigations

### Architecture and Design (Refactoring)

Refactor your program so that you do not have to dynamically generate code.

### Architecture and Design

Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which code can be executed by your product.

Examples include the Unix chroot jail and AppArmor. In general, managed code may provide some protection.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

### Implementation (Input Validation)

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.

To reduce the likelihood of code injection, use stringent allowlists that limit which constructs are allowed. If you are dynamically constructing code that invokes a function, then verifying that the input is alphanumeric might be insufficient. An attacker might still be able to reference a dangerous function that you did not intend to allow, such as system(), exec(), or exit().

### Testing

Use dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

### Operation (Compilation or Build Hardening)

Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).

### Operation (Environment Hardening)

Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).

### 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\].

Effectiveness: Discouraged Common Practice

## Detection methods

### Automated Static Analysis

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

Effectiveness: High

## Demonstrative examples

### Example 1

This example attempts to write user messages to a message file and allow users to view them.

Bad code:

```php
$MessageFile = "messages.out";
if ($_GET["action"] == "NewMessage") {
    $name = $_GET["name"];
    $message = $_GET["message"];
    $handle = fopen($MessageFile, "a+");
    fwrite($handle, "<b>$name</b> says '$message'<hr>\n");
    fclose($handle);
    echo "Message Saved!<p>\n";
}
else if ($_GET["action"] == "ViewMessages") {
    include($MessageFile);
}
```

Attack code:

```
name=h4x0r
message=%3C?php%20system(%22/bin/ls%20-l%22);?%3E
```

Attack code:

```
<?php system("/bin/ls -l");?>
```

### Example 2

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

Bad code:

```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";
}
```

Attack code:

```
add_key(",","); system("/bin/ls");
```

Result code:

```
config_file_add_key(",","); system("/bin/ls");
```

### Example 3

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

Bad code:

```python
def main():
    sum = 0
    try:
        numbers = eval(input("Enter a comma-separated list of numbers: "))
    except SyntaxError:
        print("Error: invalid input")
        return
    for num in numbers:
        sum = sum + num
    print(f"Sum of {numbers} = {sum}")
main()
```

Attack code:

```
__import__('subprocess').getoutput('rm -r *')
```

Good code:

```python
def main():
    sum = 0
    numbers = input("Enter a comma-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()
```

### Example 4

The following code is a workflow job written using YAML. The code attempts to download pull request artifacts, unzip from the artifact called pr.zip and extract the value of the file NR into a variable "pr\_number" that will be used later in another job. It attempts to create a github workflow environment variable, writing to $GITHUB\_ENV. The environment variable value is retrieved from an external resource.

Bad code:

```other
name: Deploy Preview
jobs:
    deploy:
        runs-on: ubuntu-latest
        steps:
            - name: 'Download artifact'
            uses: actions/github-script
            with:
                script: |
                    var artifacts = await github.actions.listWorkflowRunArtifacts({
                        owner: context.repo.owner,
                        repo: context.repo.repo,
                        run_id: ${{ github.event.workflow_run.id }},
                    });
                    var matchPrArtifact = artifacts.data.artifacts.filter((artifact) => {
                        return artifact.name == "pr"
                    })[0];
                    var downloadPr = await github.actions.downloadArtifact({
                        owner: context.repo.owner,
                        repo: context.repo.repo,
                        artifact_id: matchPrArtifact.id,
                        archive_format: 'zip',
                    });
                    var fs = require('fs');
                    fs.writeFileSync('${{github.workspace}}/pr.zip', Buffer.from(downloadPr.data));
            - run: |
                unzip pr.zip
                echo "pr_number=$(cat NR)" >> $GITHUB_ENV
```

## Observed examples

| CVE | Description |
| --- | --- |
| CVE-2023-29374 | Math component in an LLM framework translates user input into a Python expression that is input into the Python exec() method, allowing code execution - one variant of a "prompt injection" attack. |
| CVE-2024-5565 | Python-based library uses an LLM prompt containing user input to dynamically generate code that is then fed as input into the Python exec() method, allowing code execution - one variant of a "prompt injection" attack. |
| CVE-2024-4181 | Framework for LLM applications allows eval injection via a crafted response from a hosting provider. |
| CVE-2022-2054 | Python compiler uses eval() to execute malicious strings as Python code. |
| CVE-2021-22204 | 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. |
| CVE-2020-8218 | "Code injection" in VPN product, as exploited in the wild per CISA KEV. |
| CVE-2008-5071 | Eval injection in PHP program. |
| CVE-2002-1750 | Eval injection in Perl program. |
| CVE-2008-5305 | Eval injection in Perl program using an ID that should only contain hyphens and numbers. |
| CVE-2002-1752 | Direct code injection into Perl eval function. |
| CVE-2002-1753 | Eval injection in Perl program. |
| CVE-2005-1527 | Direct code injection into Perl eval function. |
| CVE-2005-2837 | Direct code injection into Perl eval function. |
| CVE-2005-1921 | MFV. code injection into PHP eval statement using nested constructs that should not be nested. |
| CVE-2005-2498 | MFV. code injection into PHP eval statement using nested constructs that should not be nested. |
| CVE-2005-3302 | Code injection into Python eval statement from a field in a formatted file. |
| CVE-2007-1253 | Eval injection in Python program. |
| CVE-2001-1471 | Chain: Resultant eval injection. An invalid value prevents initialization of variables, which can be modified by attacker and later injected into PHP eval statement. |
| CVE-2002-0495 | Perl code directly injected into CGI library file from parameters to another CGI program. |
| CVE-2005-1876 | Direct PHP code injection into supporting template file. |
| CVE-2005-1894 | Direct code injection into PHP script that can be accessed by attacker. |
| CVE-2003-0395 | PHP code from User-Agent HTTP header directly inserted into log file implemented as PHP script. |

## Real CVEs with this weakness (sample of 12 of 5,961)

| CVE | Title | Severity | CVSS | EPSS | CISA KEV | Published |
| --- | --- | --- | --- | --- | --- | --- |
| CVE-2025-37164 | Hewlett Packard Enterprise (HPE) OneView Code Injection Vulnerability | critical | 10.0 | - | Yes | 2025-12-16 |
| CVE-2023-33246 | Apache RocketMQ: Possible remote code execution vulnerability when using the update configuration function | critical | 10.0 | - | Yes | 2023-05-24 |
| CVE-2022-24816 | Improper Control of Generation of Code in jai-ext | critical | 10.0 | - | Yes | 2022-04-13 |
| CVE-2022-22965 | Remote Code Execution in Spring Framework | critical | 10.0 | - | Yes | 2022-04-01 |
| CVE-2022-22947 | Spring Cloud Gateway vulnerable to Code Injection when Gateway Actuator endpoint enabled, exposed, unsecured | critical | 10.0 | - | Yes | 2022-03-03 |
| CVE-2021-39144 | XStream is vulnerable to a Remote Command Execution attack | critical | 10.0 | - | Yes | 2021-08-23 |
| CVE-2021-22205 | GitLab Community and Enterprise Editions Remote Code Execution Vulnerability | critical | 10.0 | - | Yes | 2021-04-23 |
| CVE-2019-4716 | IBM Planning Analytics Remote Code Execution Vulnerability | critical | 10.0 | - | Yes | 2019-12-18 |
| CVE-2019-7609 | Kibana Arbitrary Code Execution | critical | 10.0 | - | Yes | 2019-03-25 |
| CVE-2018-14667 | Richfaces vulnerable to arbitrary code execution | critical | 10.0 | - | Yes | 2018-11-06 |
| CVE-2018-7602 | Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-004 | critical | 10.0 | - | Yes | 2018-07-19 |
| CVE-2017-7494 | Samba Remote Code Execution Vulnerability | critical | 10.0 | - | Yes | 2017-05-30 |

## Related attack patterns (CAPEC)

- [CAPEC-242](https://radicalnotion.ai/capec/capec-242): Code Injection
- [CAPEC-35](https://radicalnotion.ai/capec/capec-35): Leverage Executable Code in Non-Executable Files
- [CAPEC-77](https://radicalnotion.ai/capec/capec-77): Manipulating User-Controlled Variables

## Related weaknesses

| Relationship | CWE | Name |
| --- | --- | --- |
| Parent | [CWE-74](https://radicalnotion.ai/cwe/cwe-74) | Improper Neutralization of Special Elements in Output Used by a Downstream Component |
| Parent | [CWE-913](https://radicalnotion.ai/cwe/cwe-913) | Improper Control of Dynamically-Managed Code Resources |
| Child | [CWE-95](https://radicalnotion.ai/cwe/cwe-95) | Improper Neutralization of Directives in Dynamically Evaluated Code |
| Child | [CWE-96](https://radicalnotion.ai/cwe/cwe-96) | Improper Neutralization of Directives in Statically Saved Code |
| Child | [CWE-1336](https://radicalnotion.ai/cwe/cwe-1336) | Improper Neutralization of Special Elements Used in a Template Engine |
| Related | [CWE-98](https://radicalnotion.ai/cwe/cwe-98) | Improper Control of Filename for Include/Require Statement in PHP Program |

## Taxonomy mappings

| Taxonomy | Entry | Id | Fit |
| --- | --- | --- | --- |
| PLOVER | Code Evaluation and Injection | CODE | - |
| ISA/IEC 62443 | Req CR 3.5 | Part 4-2 | - |
| ISA/IEC 62443 | Req SR 3.5 | Part 3-3 | - |
| ISA/IEC 62443 | Req SVV-1 | Part 4-1 | - |
| ISA/IEC 62443 | Req SVV-3 | Part 4-1 | - |

## Frequently asked questions

### What is CWE-94?

The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.

### What CVEs are caused by CWE-94?

5,961 recorded CVEs are attributed to CWE-94, including CVE-2025-37164, CVE-2023-33246 and CVE-2022-24816. 74 are listed in CISA's Known Exploited Vulnerabilities (KEV) catalog.

### How do you prevent CWE-94?

Refactor your program so that you do not have to dynamically generate code.

### How is CWE-94 detected?

Automated Static Analysis: 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.)

### What are the consequences of CWE-94?

Exploiting CWE-94 can lead to: Bypass Protection Mechanism, Gain Privileges or Assume Identity, Execute Unauthorized Code or Commands, Hide Activities.

### Is CWE-94 actively exploited?

Yes. 74 CWE-94 vulnerabilities are in CISA's KEV catalog of actively exploited flaws, out of 5,961 recorded CVEs.

Primary source: [MITRE CWE](https://cwe.mitre.org/data/definitions/94.html)

---

Source: [RadicalNotion.AI](https://radicalnotion.ai/cwe/cwe-94). Licensed CC BY-NC 4.0; attribute RadicalNotion.AI and link the source page when you reuse this data.
