CVE-2026-54656: Datamodel code generator `datamodel-code-generator` Vulnerable To Code Execution Vulnerability

HIGH
Advisory Identifier: GHSA-8m8r-38jm-f355
CVSS 7.8
CWE-94
Published
Advisory Summary

CVE-2026-54656 is a HIGH (CVSS 7.8) `datamodel-code-generator` vulnerable to code execution vulnerability (CWE-94: Improper Control of Generation of Code ('Code Injection')) affecting Datamodel code generator libraries in the PyPI ecosystem. The issue involves `datamodel-code-generator` vulnerable to code execution on import via unescaped `validators` entries in --extra-template-data. Remediation is available by upgrading affected packages to version 0.60.2.

CVE-2026-54656 at a Glance

CVE Identifier CVE-2026-54656
GHSA Identifier GHSA-8m8r-38jm-f355
Severity HIGH
CVSS v3.1 Base Score 7.8
CWE Classification CWE-94: Improper Control of Generation of Code ('Code Injection')
Affected Product Datamodel code generator
Package Ecosystem PyPI
Published Date
Last Updated

Security Impact

CVSS: 7.8

The security impact metrics below are parsed directly from the CVSS v3.1 vector string (CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H).

Attack Vector Local (AV:L)
Attack Complexity Low (AC:L)
Privileges Required None (PR:N)
User Interaction Required (UI:R)
Scope Unchanged (S:U)
Confidentiality High (C:H)
Integrity High (I:H)
Availability High (A:H)

How to Fix CVE-2026-54656

To remediate this vulnerability, upgrade all affected Datamodel code generator dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

datamodel-code-generator fixed: 0.60.2
pip install datamodel-code-generator>=0.60.2
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

pip show datamodel-code-generator

How to Check if You Are Affected

To determine whether your Python environment is affected by CVE-2026-54656, inspect your installed packages using pip:

pip show datamodel-code-generator

Analyze the terminal output to locate any version of Datamodel code generator in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 0.60.2), your application is affected.

Note: The pip show datamodel-code-generator command checks currently installed packages in your active Python environment.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-94: Improper Control of Generation of Code ('Code Injection'), where 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. In Datamodel code generator, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

### Summary When the Pydantic v2 output mode is in use, `datamodel-code-generator` reads a `validators` array from each model entry in the `--extra-template-data` file and synthesises a Pydantic `@field_validator(...)` decorator from each entry. The field names and the validator mode are interpolated into the decorator call wrapped in *unescaped* single quotes. A value containing `'` breaks out of the string literal, letting an attacker emit an arbitrary positional Python expression into the decorator. The expression is evaluated at class-definition time, i.e. the moment the developer imports the generated module. This is the same trust model as the recently-published GHSA-wjv6-jcfj-mf9r (extras-file comment injection) but the impact is full RCE rather than a docstring leak. ### Details Sink: `src/datamodel_code_generator/model/pydantic_v2/base_model.py`, `_process_validators` (lines 405–449, at tag `0.60.1` / commit `a321547e`): ```python def _process_validators(self) -> None: validators = self.extra_template_data.get("validators") if not validators: return ... for validator in validators: fields = validator.get("fields") or [validator.get("field")] fields = [f for f in fields if f] if not fields: continue function_path: str = validator["function"] function_name = function_path.rsplit(".", 1)[-1] mode = validator.get("mode", "after") fields_str = ", ".join(f"'{f}'" for f in fields) # (A) UNESCAPED ... mode_str = f"mode='{mode}'" # (B) UNESCAPED prepared_validators.append({ "fields_str": fields_str, "mode_str": mode_str, "method_name": method_name, "function_name": function_name, "mode": mode, }) self._additional_imports.append(Import.from_full_path(function_path)) # (C) ``` The strings from (A) and (B) flow verbatim into `src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2`: ```jinja @field_validator({{ v.fields_str }}, {{ v.mode_str }}) ``` There is no `repr()` call, no identifier check, and no quote-escaping. Secondary sink at (C): `Import.from_full_path(function_path)` splits on the last `.` and emits `from <prefix> import <suffix>`. A `;` in `function_path` therefore lands in the generated import line and runs as a statement at module load. ### PoC A self-contained one-file PoC is available here: https://gist.github.com/thegr1ffyn/34d5c647e74487ffb2be27c76dace2aa ### Impact Arbitrary code execution in the developer's interpreter / CI runner the moment the generated module is imported. Anyone who accepts a `--extra-template-data` file from an untrusted source is impacted: - Pull requests adding or modifying project-local `*.template-data.json` / `.codegen.json` files consumed by a `make codegen` rule or pre-commit hook. - Configuration snippets pasted from issue templates, READMEs, or third-party guides. - Multi-tenant CI systems where one tenant's config file is read by another tenant's build. Same blast radius as GHSA-wjv6-jcfj-mf9r, but silent RCE rather than a docstring leak — significantly higher impact under the same threat model. > Introduced in 0.52.1 by commit [`a2b27562`](https://github.com/koxudaxi/datamodel-code-generator/commit/a2b27562) (*Add --validators option for Pydantic v2 field validators*). ### Resolution The fix validates `validators` entries with Pydantic models before rendering them. Field names must be valid non-keyword Python identifiers, `function` must be a dotted Python identifier path, and `mode` must be one of Pydantic's supported validator modes. The generated decorator arguments now render field names with `repr()` and mode with `!r`, so validated values are still emitted as Python string literals. ### Remediation Upgrade to `datamodel-code-generator` `0.60.2` or later. This issue affects `datamodel-code-generator` versions `>= 0.52.1, <= 0.60.1` and is fixed in `0.60.2`. Submitted by: Hamza Haroon (thegr1ffyn)

CVE-2026-54656 Affected Datamodel code generator Versions

1 component(s)
Fixed Versions:
0.60.2
Product / Package Ecosystem Affected Versions Fixed Version
datamodel-code-generator
PyPI
≥ 0.52.1
< 0.60.2
0.60.2

References

Frequently Asked Questions

What is CVE-2026-54656?
CVE-2026-54656 is a security vulnerability in Datamodel code generator involving `datamodel-code-generator` vulnerable to code execution on import via unescaped `validators` entries in --extra-template-data under CWE-94: Improper Control of Generation of Code ('Code Injection').
Which Datamodel code generator versions are affected?
Affected versions include releases prior to 0.60.2 across affected packages: datamodel-code-generator.
What version fixes CVE-2026-54656?
Upgrading to 0.60.2 (or the latest patched release for your respective branch) resolves the vulnerability.
Is datamodel-code-generator affected?
Yes, datamodel-code-generator is affected in releases prior to 0.60.2. Upgrade your dependency to 0.60.2 or later.
What is the CVSS score of CVE-2026-54656?
CVE-2026-54656 has a CVSS v3.1 base score of 7.8 (HIGH) with vector string CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H.
What CWE is associated with CVE-2026-54656?
CVE-2026-54656 is classified under CWE-94: Improper Control of Generation of Code ('Code Injection') (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.).
How can I check PyPI dependencies for CVE-2026-54656?
Run the dependency tree command: 'pip show datamodel-code-generator'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-8m8r-38jm-f355",
  "modified" : "2026-07-28T21:44:09Z",
  "published" : "2026-07-28T21:44:09Z",
  "aliases" : [ "CVE-2026-54656" ],
  "summary" : "`datamodel-code-generator` vulnerable to code execution on import via unescaped `validators` entries in --extra-template-data",
  "details" : "### Summary\n\nWhen the Pydantic v2 output mode is in use, `datamodel-code-generator` reads a `validators` array from each model entry in the `--extra-template-data` file and synthesises a Pydantic `@field_validator(...)` decorator from each entry. The field names and the validator mode are interpolated into the decorator call wrapped in *unescaped* single quotes. A value containing `'` breaks out of the string literal, letting an attacker emit an arbitrary positional Python expression into the decorator. The expression is evaluated at class-definition time, i.e. the moment the developer imports the generated module. This is the same trust model as the recently-published GHSA-wjv6-jcfj-mf9r (extras-file comment injection) but the impact is full RCE rather than a docstring leak.\n\n### Details\n\nSink: `src/datamodel_code_generator/model/pydantic_v2/base_model.py`, `_process_validators` (lines 405–449, at tag `0.60.1` / commit `a321547e`):\n\n```python\ndef _process_validators(self) -> None:\n    validators = self.extra_template_data.get(\"validators\")\n    if not validators:\n        return\n    ...\n    for validator in validators:\n        fields = validator.get(\"fields\") or [validator.get(\"field\")]\n        fields = [f for f in fields if f]\n        if not fields:\n            continue\n        function_path: str = validator[\"function\"]\n        function_name = function_path.rsplit(\".\", 1)[-1]\n        mode = validator.get(\"mode\", \"after\")\n        fields_str = \", \".join(f\"'{f}'\" for f in fields)     # (A) UNESCAPED\n        ...\n        mode_str = f\"mode='{mode}'\"                          # (B) UNESCAPED\n        prepared_validators.append({\n            \"fields_str\": fields_str,\n            \"mode_str\":   mode_str,\n            \"method_name\": method_name,\n            \"function_name\": function_name,\n            \"mode\": mode,\n        })\n        self._additional_imports.append(Import.from_full_path(function_path))  # (C)\n```\n\nThe strings from (A) and (B) flow verbatim into `src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2`:\n\n```jinja\n@field_validator({{ v.fields_str }}, {{ v.mode_str }})\n```\n\nThere is no `repr()` call, no identifier check, and no quote-escaping.\n\nSecondary sink at (C): `Import.from_full_path(function_path)` splits on the last `.` and emits `from <prefix> import <suffix>`. A `;` in `function_path` therefore lands in the generated import line and runs as a statement at module load.\n\n### PoC\n\nA self-contained one-file PoC is available here: https://gist.github.com/thegr1ffyn/34d5c647e74487ffb2be27c76dace2aa\n\n### Impact\n\nArbitrary code execution in the developer's interpreter / CI runner the moment the generated module is imported. Anyone who accepts a `--extra-template-data` file from an untrusted source is impacted:\n\n- Pull requests adding or modifying project-local `*.template-data.json` / `.codegen.json` files consumed by a `make codegen` rule or pre-commit hook.\n- Configuration snippets pasted from issue templates, READMEs, or third-party guides.\n- Multi-tenant CI systems where one tenant's config file is read by another tenant's build.\n\nSame blast radius as GHSA-wjv6-jcfj-mf9r, but silent RCE rather than a docstring leak — significantly higher impact under the same threat model.\n\n\n \n> Introduced in 0.52.1 by commit [`a2b27562`](https://github.com/koxudaxi/datamodel-code-generator/commit/a2b27562) (*Add --validators option for Pydantic v2 field validators*).\n\n### Resolution\n\nThe fix validates `validators` entries with Pydantic models before rendering them. Field names must be valid non-keyword Python identifiers, `function` must be a dotted Python identifier path, and `mode` must be one of Pydantic's supported validator modes. The generated decorator arguments now render field names with `repr()` and mode with `!r`, so validated values are still emitted as Python string literals.\n\n### Remediation\n\nUpgrade to `datamodel-code-generator` `0.60.2` or later.\n\nThis issue affects `datamodel-code-generator` versions `>= 0.52.1, <= 0.60.1` and is fixed in `0.60.2`.\n\nSubmitted by: Hamza Haroon (thegr1ffyn)",
  "severity" : [ {
    "type" : "CVSS_V3",
    "score" : "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "PyPI",
      "name" : "datamodel-code-generator"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "0.52.1"
      }, {
        "fixed" : "0.60.2"
      } ]
    } ],
    "database_specific" : {
      "last_known_affected_version_range" : "<= 0.60.1"
    }
  } ],
  "references" : [ {
    "type" : "WEB",
    "url" : "https://github.com/koxudaxi/datamodel-code-generator/security/advisories/GHSA-8m8r-38jm-f355"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/koxudaxi/datamodel-code-generator/commit/a43d02906111a2fdcaf13ee5b62eb2da85376f19"
  }, {
    "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"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-94" ],
    "severity" : "HIGH",
    "github_reviewed" : true,
    "github_reviewed_at" : "2026-07-28T21:44:09Z",
    "nvd_published_at" : null
  }
}