PYSEC-2026-3562
Vulnerability from pysec - Published: 2026-08-04 11:34 - Updated: 2026-08-04 13:36Summary
datamodel-code-generator honours a custom x-python-type JSON-Schema extension that lets a schema author override the generated Python type for a field. The value is forwarded verbatim into the generated Python source as the field annotation, with a single sanitisation pass that is trivial to bypass. An attacker who controls a JSON Schema fed to datamodel-codegen can therefore embed an arbitrary Python statement in the generated module, which executes at class-definition time the moment the developer imports the file. No --extra-template-data and no special flags are required; the vulnerable code is reachable with default settings.
Details
Sink: src/datamodel_code_generator/parser/jsonschema.py, _get_python_type_override (lines 2055–2096, at tag 0.60.1 / commit a321547e):
def _get_python_type_override(self, obj: JsonSchemaObject) -> DataType | None:
x_python_type = obj.extras.get("x-python-type")
if not x_python_type or not isinstance(x_python_type, str):
return None
schema_type = obj.type if isinstance(obj.type, str) else None
if self._is_compatible_python_type(schema_type, x_python_type):
return None
base_type = self._get_python_type_base(x_python_type)
import_ = self._resolve_type_import(base_type)
type_str = x_python_type
prefix = x_python_type.split("[", maxsplit=1)[0]
if "." in prefix: # only sanitiser
type_str = base_type + x_python_type[len(prefix):]
...
...
result = self.data_type(type=type_str, import_=import_)
...
return result
DataType.type flows unescaped into {{ field.type_hint }} in every model template
(model/template/pydantic_v2/BaseModel.jinja2,
model/template/dataclass.jinja2,
model/template/TypedDictClass.jinja2,
model/template/msgspec.jinja2, …).
The only sanitiser — the dot-rewrite at the marked line — fires only when . is in the substring before the first [ in the value. Placing [ early (e.g. X[1]; <payload>) keeps prefix == "X" so the rewrite is skipped and the whole value lands in the generated annotation.
from __future__ import annotations (emitted by default) makes the X[1] portion a lazy string, so X does not need to resolve at runtime. Everything after ; is parsed as a real statement in the class body and is executed when the class is constructed during import.
Output-model types confirmed vulnerable in testing: pydantic_v2.BaseModel, dataclasses.dataclass, typing.TypedDict. msgspec.Struct emits structurally identical code.
PoC
A self-contained PoC is available at: https://gist.github.com/thegr1ffyn/1a7ff2561a581074c49785230b2c5700
Impact
Arbitrary code execution in the developer's interpreter / CI runner as soon as the generated module is imported. Reachable from any workflow that ingests an untrusted JSON Schema:
- OpenAPI / JSON-Schema documents fetched from third-party services or public registries.
- Customer-supplied schemas in B2B platforms that auto-generate client SDKs from user input.
- Schema files added by a malicious commit in a polyglot repository that triggers CI code generation.
The compromise is silent: the schema is valid JSON, the generator emits syntactically clean Python (the trojan statement is a single indented line in the class body), and only the use of the generated file triggers the payload.
Anyone running datamodel-codegen against an attacker-supplied schema is impacted. CI runners and developer workstations are the primary blast radius.
Resolution
The fix validates x-python-type before constructing the generated type annotation. The value is parsed with ast.parse(..., mode="eval") and accepted only when the AST is shaped like a Python type annotation, including names, attributes, subscripts, tuple/list annotation arguments, | unions, and safe literal values where annotation syntax allows them. Statements, calls, and other executable expressions are rejected before code generation. The validator is cached to avoid repeated AST parsing for repeated values.
Remediation
Upgrade to datamodel-code-generator 0.60.2 or later.
This issue affects datamodel-code-generator versions >= 0.51.0, <= 0.60.1 and is fixed in 0.60.2.
Submitted by: Hamza Haroon (thegr1ffyn)
| Name | purl | datamodel-code-generator | pkg:pypi/datamodel-code-generator |
|---|
{
"affected": [
{
"package": {
"ecosystem": "PyPI",
"name": "datamodel-code-generator",
"purl": "pkg:pypi/datamodel-code-generator"
},
"ranges": [
{
"events": [
{
"introduced": "0.51.0"
},
{
"fixed": "0.60.2"
}
],
"type": "ECOSYSTEM"
}
],
"versions": [
"0.51.0",
"0.52.0",
"0.52.1",
"0.52.2",
"0.53.0",
"0.54.0",
"0.54.1",
"0.55.0",
"0.56.0",
"0.56.1",
"0.57.0",
"0.58.0",
"0.59.0",
"0.59.1",
"0.60.0",
"0.60.1"
]
}
],
"aliases": [
"CVE-2026-54655",
"GHSA-m34r-v34r-rf9q"
],
"details": "### Summary\n`datamodel-code-generator` honours a custom `x-python-type` JSON-Schema extension that lets a schema author override the generated Python type for a field. The value is forwarded verbatim into the generated Python source as the field annotation, with a single sanitisation pass that is trivial to bypass. An attacker who controls a JSON Schema fed to `datamodel-codegen` can therefore embed an arbitrary Python statement in the generated module, which executes at class-definition time the moment the developer imports the file. No `--extra-template-data` and no special flags are required; the vulnerable code is reachable with default settings.\n\n### Details\nSink: `src/datamodel_code_generator/parser/jsonschema.py`, `_get_python_type_override` (lines 2055\u20132096, at tag `0.60.1` / commit `a321547e`):\n\n```python\ndef _get_python_type_override(self, obj: JsonSchemaObject) -\u003e DataType | None:\n x_python_type = obj.extras.get(\"x-python-type\")\n if not x_python_type or not isinstance(x_python_type, str):\n return None\n schema_type = obj.type if isinstance(obj.type, str) else None\n if self._is_compatible_python_type(schema_type, x_python_type):\n return None\n base_type = self._get_python_type_base(x_python_type)\n import_ = self._resolve_type_import(base_type)\n type_str = x_python_type\n prefix = x_python_type.split(\"[\", maxsplit=1)[0]\n if \".\" in prefix: # only sanitiser\n type_str = base_type + x_python_type[len(prefix):]\n ...\n ...\n result = self.data_type(type=type_str, import_=import_)\n ...\n return result\n```\n\n`DataType.type` flows unescaped into `{{ field.type_hint }}` in every model template\n(`model/template/pydantic_v2/BaseModel.jinja2`,\n`model/template/dataclass.jinja2`,\n`model/template/TypedDictClass.jinja2`,\n`model/template/msgspec.jinja2`, \u2026).\n\nThe only sanitiser \u2014 the dot-rewrite at the marked line \u2014 fires only when `.` is in the substring **before the first `[`** in the value. Placing `[` early (e.g. `X[1]; \u003cpayload\u003e`) keeps `prefix == \"X\"` so the rewrite is skipped and the whole value lands in the generated annotation.\n\n`from __future__ import annotations` (emitted by default) makes the `X[1]` portion a lazy string, so `X` does not need to resolve at runtime. Everything after `;` is parsed as a real statement in the class body and is executed when the class is constructed during `import`.\n\nOutput-model types confirmed vulnerable in testing: `pydantic_v2.BaseModel`, `dataclasses.dataclass`, `typing.TypedDict`. `msgspec.Struct` emits structurally identical code.\n\n### PoC\nA self-contained PoC is available at: https://gist.github.com/thegr1ffyn/1a7ff2561a581074c49785230b2c5700\n\n### Impact\nArbitrary code execution in the developer\u0027s interpreter / CI runner as soon as the generated module is imported. Reachable from any workflow that ingests an untrusted JSON Schema:\n\n- OpenAPI / JSON-Schema documents fetched from third-party services or public registries.\n- Customer-supplied schemas in B2B platforms that auto-generate client SDKs from user input.\n- Schema files added by a malicious commit in a polyglot repository that triggers CI code generation.\n\nThe compromise is silent: the schema is valid JSON, the generator emits syntactically clean Python (the trojan statement is a single indented line in the class body), and only the *use* of the generated file triggers the payload.\n\nAnyone running `datamodel-codegen` against an attacker-supplied schema is impacted. CI runners and developer workstations are the primary blast radius.\n\n### Resolution\n\nThe fix validates `x-python-type` before constructing the generated type annotation. The value is parsed with `ast.parse(..., mode=\"eval\")` and accepted only when the AST is shaped like a Python type annotation, including names, attributes, subscripts, tuple/list annotation arguments, `|` unions, and safe literal values where annotation syntax allows them. Statements, calls, and other executable expressions are rejected before code generation. The validator is cached to avoid repeated AST parsing for repeated values.\n\n### Remediation\n\nUpgrade to `datamodel-code-generator` `0.60.2` or later.\n\nThis issue affects `datamodel-code-generator` versions `\u003e= 0.51.0, \u003c= 0.60.1` and is fixed in `0.60.2`.\n\nSubmitted by: Hamza Haroon (thegr1ffyn)",
"id": "PYSEC-2026-3562",
"modified": "2026-08-04T13:36:15.805408Z",
"published": "2026-08-04T11:34:44.234328Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/koxudaxi/datamodel-code-generator/security/advisories/GHSA-m34r-v34r-rf9q"
},
{
"type": "WEB",
"url": "https://github.com/koxudaxi/datamodel-code-generator/commit/2c93c9b712f43391dcfa975a1e4aa0b7c93ccbba"
},
{
"type": "PACKAGE",
"url": "https://github.com/koxudaxi/datamodel-code-generator"
},
{
"type": "WEB",
"url": "https://github.com/koxudaxi/datamodel-code-generator/releases/tag/0.60.2"
},
{
"type": "PACKAGE",
"url": "https://pypi.org/project/datamodel-code-generator"
},
{
"type": "ADVISORY",
"url": "https://github.com/advisories/GHSA-m34r-v34r-rf9q"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2026-54655"
}
],
"severity": [
{
"score": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
],
"summary": "`datamodel-code-generator` vulnerable to code execution on import via `x-python-type` JSON-Schema extension in datamodel-code-generator"
}
Sightings
| Author | Source | Type | Date | Other |
|---|
Nomenclature
- Seen: The vulnerability was mentioned, discussed, or observed by the user.
- Confirmed: The vulnerability has been validated from an analyst's perspective.
- Published Proof of Concept: A public proof of concept is available for this vulnerability.
- Exploited: The vulnerability was observed as exploited by the user who reported the sighting.
- Patched: The vulnerability was observed as successfully patched by the user who reported the sighting.
- Not exploited: The vulnerability was not observed as exploited by the user who reported the sighting.
- Not confirmed: The user expressed doubt about the validity of the vulnerability.
- Not patched: The vulnerability was not observed as successfully patched by the user who reported the sighting.
The approach is described in our paper Mapping CVEs to MITRE ATT&CK Techniques: A Curated Gold-Set Classifier and the Limits of LLM-Assisted Label Expansion.