datamodel-code-generator is vulnerable to code injection when a developer passes an --extra-template-data file whose comment value contains a literal \r (carriage return). The comment variable is rendered into a Python # comment in six built-in templates with no line-terminator escaping. Python's tokenizer treats a bare CR as a physical-line terminator (see Python language reference — Physical lines), so the comment ends at the \r and the text after it is parsed as Python, including, when the CR is followed by suitable indentation, as a statement within the class body that follows on the next template line.
The vulnerable templates each contain # {{ comment }} with no escaping:
src/datamodel_code_generator/model/template/TypeAliasAnnotation.jinja2:12 and :19src/datamodel_code_generator/model/template/TypeAliasType.jinja2:12 and :19src/datamodel_code_generator/model/template/TypeStatement.jinja2:12 and :19src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2:4src/datamodel_code_generator/model/template/pydantic_v2/RootModel.jinja2:19src/datamodel_code_generator/model/template/pydantic_v2/RootModelTypeAlias.jinja2:13The pydantic_v2/BaseModel.jinja2:4 site is representative:
class {{ class_name }}({{ base_class }}):{% if comment is defined %} # {{ comment }}{% endif %}
When the developer-supplied extras file populates comment for a model, the value reaches the template via DataModel.extra_template_data (set in src/datamodel_code_generator/model/base.py:736-742) and Jinja2 interpolates it raw. None of the templates use comment_safe, escape_docstring, or any other line-terminator filter.
Complete self contained POC is available at my secret gist: https://gist.github.com/thegr1ffyn/8ad6b8cb3cc2be9d3a0144aeb6896a3f
datamodel-codegen --extra-template-data <file> where the extras file is influenced by attacker-controlled input. Realistic scenarios include:
comment sources.import time.comment.--extra-template-data, or rejecting extras files whose comment values contain \r, \x0b, or \x0c before invocation.The fix normalizes comment values from built-in --extra-template-data before template rendering. Inline comments now convert CRLF, bare CR, vertical tab, and form feed into LF and prefix continuation lines with #, so attacker-controlled text stays inside the generated Python comment block.
Upgrade to datamodel-code-generator 0.60.2 or later.
This issue affects datamodel-code-generator versions >= 0.14.1, <= 0.60.1 and is fixed in 0.60.2.
Submitted by: Hamza Haroon (thegr1ffyn)