SQL Injection
Description
CVE-2025-59681: Django's QuerySet.annotate(), alias(), aggregate(), and extra() on MySQL/MariaDB could be vulnerable to SQL injection via crafted column aliases passed through dictionaries (via **kwargs). The commit updates the validation of column aliases to forbid unsafe characters (notably including '#'), adjusts the error messages, and adds tests. This directly hardens the code paths that interpolate user-supplied alias strings into SQL, preventing injection through the alias identifiers.
Proof of Concept
PoC exploit (illustrative, pre-fix scenario):
Prerequisites:
- Django project using MySQL or MariaDB
- A model, e.g., Author(id, name, age)
- A view or script that can execute ORM queries with user-controlled alias strings
Python (pre-fix exploit attempt):
from django.db.models import Avg
from myapp.models import Author
# Attacker-supplied crafted alias intended to terminate the column alias and inject SQL
crafted_alias = 'injected_name" from "authors"; --'
# This would be used in a query like:
# Author.objects.aggregate(**{crafted_alias: Avg("age")})
# Pre-fix, this could cause the generated SQL SELECT AVG("authors"."age") AS injected_name" from "authors"; --" ...
# which could lead to a second statement or comment and potential data exposure or manipulation.
# Actual Django behavior after the fix (post-fix): an exception is raised due to forbidden characters
# ValueError: Column aliases cannot contain whitespace characters, hashes, quotation marks, semicolons, or SQL comments.
# Thus, a PoC demonstration would show the pre-fix exploit path, and the post-fix path would be the raised error above.
Commit Details
Author: Mariusz Felisiak
Date: 2025-09-10 07:53 UTC
Message:
Fixed CVE-2025-59681 -- Protected QuerySet.annotate(), alias(), aggregate(), and extra() against SQL injection in column aliases on MySQL/MariaDB.
Thanks sw0rd1ight for the report.
Follow up to 93cae5cb2f9a4ef1514cf1a41f714fef08005200.
Triage Assessment
Vulnerability Type: SQL Injection
Confidence: HIGH
Reasoning:
Commit explicitly addresses CVE-2025-59681 by preventing SQL injection via column aliases in QuerySet.annotate/alias/aggregate/extra for MySQL/MariaDB. It updates the alias validation pattern to forbid unsafe characters (including '#') and adjusts error messages accordingly, with release notes confirming the security fix. Tests also validate the hardened behavior.
Verification Assessment
Vulnerability Type: SQL Injection
Confidence: HIGH
Affected Versions: 5.1.x before 5.1.13 (i.e., <= 5.1.12)
Code Diff
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 39ecab2e91ea..84950d4ec069 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -51,12 +51,12 @@
__all__ = ["Query", "RawQuery"]
# RemovedInDjango70Warning: When the deprecation ends, replace with:
-# Quotation marks ('"`[]), whitespace characters, semicolons, percent signs
-# or inline SQL comments are forbidden in column aliases.
-# FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|%|--|/\*|\*/")
-# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
+# Quotation marks ('"`[]), whitespace characters, semicolons, percent signs,
+# hashes, or inline SQL comments are forbidden in column aliases.
+# FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|%|#|--|/\*|\*/")
+# Quotation marks ('"`[]), whitespace characters, semicolons, hashes, or inline
# SQL comments are forbidden in column aliases.
-FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
+FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|#|--|/\*|\*/")
# Inspired from
# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
@@ -1222,11 +1222,12 @@ def check_alias(self, alias):
)
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
- "Column aliases cannot contain whitespace characters, quotation marks, "
+ "Column aliases cannot contain whitespace characters, hashes, "
# RemovedInDjango70Warning: When the deprecation ends, replace
# with:
- # "semicolons, percent signs, or SQL comments."
- "semicolons, or SQL comments."
+ # "quotation marks, semicolons, percent signs, or SQL "
+ # "comments."
+ "quotation marks, semicolons, or SQL comments."
)
def add_annotation(self, annotation, alias, select=True):
diff --git a/docs/releases/4.2.25.txt b/docs/releases/4.2.25.txt
index 69f238c3c19a..5412777055bf 100644
--- a/docs/releases/4.2.25.txt
+++ b/docs/releases/4.2.25.txt
@@ -7,4 +7,11 @@ Django 4.2.25 release notes
Django 4.2.25 fixes one security issue with severity "high" and one security
issue with severity "low" in 4.2.24.
-...
+CVE-2025-59681: Potential SQL injection in ``QuerySet.annotate()``, ``alias()``, ``aggregate()``, and ``extra()`` on MySQL and MariaDB
+======================================================================================================================================
+
+:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.alias`,
+:meth:`~.QuerySet.aggregate`, and :meth:`~.QuerySet.extra` methods were subject
+to SQL injection in column aliases, using a suitably crafted dictionary, with
+dictionary expansion, as the ``**kwargs`` passed to these methods (follow up to
+:cve:`2022-28346`).
diff --git a/docs/releases/5.1.13.txt b/docs/releases/5.1.13.txt
index a181694be28a..96b81c0102e8 100644
--- a/docs/releases/5.1.13.txt
+++ b/docs/releases/5.1.13.txt
@@ -7,4 +7,11 @@ Django 5.1.13 release notes
Django 5.1.13 fixes one security issue with severity "high" and one security
issue with severity "low" in 5.1.12.
-...
+CVE-2025-59681: Potential SQL injection in ``QuerySet.annotate()``, ``alias()``, ``aggregate()``, and ``extra()`` on MySQL and MariaDB
+======================================================================================================================================
+
+:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.alias`,
+:meth:`~.QuerySet.aggregate`, and :meth:`~.QuerySet.extra` methods were subject
+to SQL injection in column aliases, using a suitably crafted dictionary, with
+dictionary expansion, as the ``**kwargs`` passed to these methods (follow up to
+:cve:`2022-28346`).
diff --git a/docs/releases/5.2.7.txt b/docs/releases/5.2.7.txt
index 11dcff6c7c93..05d03a991e90 100644
--- a/docs/releases/5.2.7.txt
+++ b/docs/releases/5.2.7.txt
@@ -8,6 +8,15 @@ Django 5.2.7 fixes one security issue with severity "high", one security issue
with severity "low", and one bug in 5.2.6. Also, the latest string translations
from Transifex are incorporated.
+CVE-2025-59681: Potential SQL injection in ``QuerySet.annotate()``, ``alias()``, ``aggregate()``, and ``extra()`` on MySQL and MariaDB
+======================================================================================================================================
+
+:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.alias`,
+:meth:`~.QuerySet.aggregate`, and :meth:`~.QuerySet.extra` methods were subject
+to SQL injection in column aliases, using a suitably crafted dictionary, with
+dictionary expansion, as the ``**kwargs`` passed to these methods (follow up to
+:cve:`2022-28346`).
+
Bugfixes
========
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index bd33a532b350..f2ec4bd3436c 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -2244,8 +2244,8 @@ def test_exists_none_with_aggregate(self):
def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "aggregation_author"; --"""
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Author.objects.aggregate(**{crafted_alias: Avg("age")})
diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py
index cf1eebf8d7a3..a114480d48e6 100644
--- a/tests/annotations/tests.py
+++ b/tests/annotations/tests.py
@@ -1161,12 +1161,12 @@ def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
- # "Column aliases cannot contain whitespace characters, quotation "
- # "marks, semicolons, percent signs, or SQL comments."
+ # "Column aliases cannot contain whitespace characters, hashes, "
+ # "quotation marks, semicolons, percent signs, or SQL comments."
# )
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Book.objects.annotate(**{crafted_alias: Value(1)})
@@ -1175,12 +1175,12 @@ def test_alias_filtered_relation_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
- # "Column aliases cannot contain whitespace characters, quotation "
- # "marks, semicolons, percent signs, or SQL comments."
+ # "Column aliases cannot contain whitespace characters, hashes, "
+ # "quotation marks, semicolons, percent signs, or SQL comments."
# )
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Book.objects.annotate(**{crafted_alias: FilteredRelation("author")})
@@ -1199,18 +1199,19 @@ def test_alias_forbidden_chars(self):
"alias;",
# RemovedInDjango70Warning: When the deprecation ends, add this:
# "alias%",
- # [] are used by MSSQL.
+ # [] and # are used by MSSQL.
"alias[",
"alias]",
+ "ali#as",
]
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
- # "Column aliases cannot contain whitespace characters, quotation "
- # "marks, semicolons, percent signs, or SQL comments."
+ # "Column aliases cannot contain whitespace characters, hashes, "
+ # "quotation marks, semicolons, percent signs, or SQL comments."
# )
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
for crafted_alias in tests:
with self.subTest(crafted_alias):
@@ -1516,12 +1517,12 @@ def test_alias_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
- # "Column aliases cannot contain whitespace characters, quotation "
- # "marks, semicolons, percent signs, or SQL comments."
+ # "Column aliases cannot contain whitespace characters, hashes, "
+ # "quotation marks, semicolons, percent signs, or SQL comments."
# )
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Book.objects.alias(**{crafted_alias: Value(1)})
@@ -1530,12 +1531,12 @@ def test_alias_filtered_relation_sql_injection(self):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
- # "Column aliases cannot contain whitespace characters, quotation "
- # "marks, semicolons, percent signs, or SQL comments."
+ # "Column aliases cannot contain whitespace characters, hashes, "
+ # "quotation marks, semicolons, percent signs, or SQL comments."
# )
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Book.objects.alias(**{crafted_alias: FilteredRelation("authors")})
diff --git a/tests/expressions/test_queryset_values.py b/tests/expressions/test_queryset_values.py
index 70e9166655d4..24f22e818751 100644
--- a/tests/expressions/test_queryset_values.py
+++ b/tests/expressions/test_queryset_values.py
@@ -44,8 +44,8 @@ def test_values_expression_containing_percent_sign_deprecation_warns_once(self):
def test_values_expression_alias_sql_injection(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Company.objects.values(**{crafted_alias: F("ceo__salary")})
@@ -54,8 +54,8 @@ def test_values_expression_alias_sql_injection(self):
def test_values_expression_alias_sql_injection_json_field(self):
crafted_alias = """injected_name" from "expressions_company"; --"""
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
JSONFieldModel.objects.values(f"data__{crafted_alias}")
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index 4158a9a596d0..4ee457271904 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -1967,8 +1967,8 @@ def test_extra_select_literal_percent_s(self):
def test_extra_select_alias_sql_injection(self):
crafted_alias = """injected_name" from "queries_note"; --"""
msg = (
- "Column aliases cannot contain whitespace characters, quotation marks, "
- "semicolons, or SQL comments."
+ "Column aliases cannot contain whitespace characters, hashes, quotation "
+ "marks, semicolons, or SQL comments."
)
with self.assertRaisesMessage(ValueError, msg):
Note.objects.extra(select={crafted_alias: "1"})