CWE-94: Improper Control of Generation of Code ('Code Injection')

What is CWE-94?

CWE-94 is Improper Control of Generation of Code ('Code Injection'). The flaw arises when the product constructs part or all of a code segment from externally influenced input without properly neutralizing special elements that can alter the intended syntax or behavior. The database currently holds 1,171 vulnerabilities mapped to CWE-94 and 12 of them are in the CISA Known Exploited Vulnerabilities catalog.

OWASP TOP 10:2025 RANK5 — A05:2025 — Injection
Related CVES (365 days)1,171
AbstractionBase
Likelihood of exploitMedium

Vulnerabilities mapped to CWE-94

1,171 vulnerabilities296% increase year over year

Vulnerabilities in CISA KEV for CWE-94

12 vulnerabilities50% increase year over year

Official definition

ByMitre CWE

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.

Detailed description

This weakness occurs when a product incorporates externally influenced data from an upstream component into a code segment without adequately controlling special characters or structures in that data. An attacker may alter the syntax, control flow, or operations performed by the generated code rather than supplying ordinary data. Because the generated code may execute with the product's privileges, the impact depends on context and can extend beyond the original input-processing operation.

Characteristics

The defining characteristic is the flow of externally influenced data into code generation while special elements that can change syntax or control flow are not correctly neutralized. The weakness commonly appears when code is generated dynamically or when input reaches code evaluation and execution mechanisms. The record lists interpreted languages as a sometimes applicable platform and AI/ML as an applicable technology with undetermined prevalence.

Common consequences

Potential consequences include bypassing authentication or other access control protections when injected code controls authentication, gaining privileges or assuming another identity, and accessing resources that should be unavailable to the attacker. Injected code can execute unauthorized code or commands and affect confidentiality, integrity, and availability; the record notes that integrity loss can commonly result because injected control-plane data is incidental to data retrieval or writing. Actions performed by injected control code may also be unlogged, enabling concealment of activity and affecting non-repudiation.

ImpactScopeExplanation
Bypass Protection MechanismAccess ControlIn some cases, injectable code controls authentication; this may lead to a remote vulnerability.
Gain Privileges or Assume IdentityAccess ControlInjected code can access resources that the attacker is directly prevented from accessing.
Execute Unauthorized Code or CommandsIntegrity, Confidentiality, AvailabilityWhen 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.
Hide ActivitiesNon-RepudiationOften the actions performed by injected control code are unlogged.

Risk mitigations

  • Avoid dynamic code generation: Refactor the program during architecture and design so that it does not need to generate code dynamically.
  • Constrain execution: Run the code in a jail or comparable sandbox with strict process to operating system boundaries. Examples in the record include Unix chroot and AppArmor. This can restrict executable code and limit operating system impact, but may be infeasible, does not prevent compromise of the rest of the application, and must be designed carefully to avoid jail-related weaknesses such as CWE-243.
  • Validate against strict allowlists: Treat all input as malicious and accept only values that strictly conform to the specification, including length, type, ranges, syntax, required or extra fields, consistency, and business rules. For dynamically generated calls, checking that input is alphanumeric alone is insufficient because an attacker might still select an unintended dangerous function such as system, exec, or exit. Denylists should not be the sole defense, although they can help identify likely attacks or inputs that should be rejected.
  • Test diverse inputs: During testing, use fuzzing, robustness testing, and fault injection with large and varied input suites. The product should not become unstable, crash, or produce incorrect results.
  • Use taint-aware execution environments: During operation, use an environment that automatically propagates taint and blocks command execution involving tainted variables, such as Perl's -T switch. Inputs must still be validated correctly because dangerous data can be mistakenly marked untainted; the record points to CWE-183 and CWE-184 for related concerns.
  • Python-specific caution: ast.literal_eval is often encouraged instead of eval because it is designed not to execute code. However, the record discourages treating it as a general solution for untrusted data because deeply nested structures can still cause excessive memory or stack consumption.
  1. Refactoring · Architecture and DesignRefactor your program so that you do not have to dynamically generate code.
  2. Architecture and DesignRun 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.
  3. Input Validation · ImplementationAssume 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().
  4. TestingUse 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.
  5. Compilation or Build Hardening · OperationRun 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).
  6. Environment Hardening · OperationRun 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).
  7. Implementation · Effectiveness: Discouraged Common PracticeFor 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 methods

Automated static analysis, commonly called Static Application Security Testing (SAST), can identify some instances by analyzing source or compiled code without execution. It typically models data flow and control flow, then searches for potentially vulnerable paths from input sources to sinks where data interacts with external components or lower layers such as the operating system; the record rates this approach as high effectiveness, but it does not claim complete coverage.

MethodApproachEffectiveness
Automated Static AnalysisAutomated 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.)High

Representative vulnerabilities

The following are representative examples, not an exhaustive list of vulnerabilities in this weakness. The record includes these groups:

Below are representative vulnerabilities related to this CWE, prioritized by severity.

Sources (2)

CWE™ Program, operated by The MITRE Corporation. Copyright © 2006–2026, The MITRE Corporation. The MITRE Corporation hereby grants you a non-exclusive, royalty-free license to use CWE for research, development, and commercial purposes. CWE Terms of Use.

Learn more

Run an in-depth assessment with complete web risk management

CyStack VulnScan continuously discovers assets, validates vulnerabilities, and helps security teams prioritize remediation across the organization.