diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index e68fd9efb7..5a1b68507b 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1620,6 +1620,7 @@ class Query(BaseExpression): return target_clause def add_filtered_relation(self, filtered_relation, alias): + self.check_alias(alias) filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( diff --git a/docs/releases/4.2.24.txt b/docs/releases/4.2.24.txt index d6e198fb9c..e501483917 100644 --- a/docs/releases/4.2.24.txt +++ b/docs/releases/4.2.24.txt @@ -5,3 +5,10 @@ Django 4.2.24 release notes *September 3, 2025* Django 4.2.24 fixes a security issue with severity "high" in 4.2.23. + +CVE-2025-57833: Potential SQL injection in ``FilteredRelation`` column aliases +============================================================================== + +:class:`.FilteredRelation` was subject to SQL injection in column aliases, +using a suitably crafted dictionary, with dictionary expansion, as the +``**kwargs`` passed to :meth:`.QuerySet.annotate` or :meth:`.QuerySet.alias`. diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py index e0cdbf1e0b..a8474abc77 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -12,6 +12,7 @@ from django.db.models import ( Exists, ExpressionWrapper, F, + FilteredRelation, FloatField, Func, IntegerField, @@ -1121,6 +1122,15 @@ class NonAggregateAnnotationTestCase(TestCase): with self.assertRaisesMessage(ValueError, msg): Book.objects.annotate(**{crafted_alias: Value(1)}) + def test_alias_filtered_relation_sql_injection(self): + crafted_alias = """injected_name" from "annotations_book"; --""" + msg = ( + "Column aliases cannot contain whitespace characters, quotation marks, " + "semicolons, or SQL comments." + ) + with self.assertRaisesMessage(ValueError, msg): + Book.objects.annotate(**{crafted_alias: FilteredRelation("author")}) + def test_alias_forbidden_chars(self): tests = [ 'al"ias', @@ -1146,6 +1156,11 @@ class NonAggregateAnnotationTestCase(TestCase): with self.assertRaisesMessage(ValueError, msg): Book.objects.annotate(**{crafted_alias: Value(1)}) + with self.assertRaisesMessage(ValueError, msg): + Book.objects.annotate( + **{crafted_alias: FilteredRelation("authors")} + ) + class AliasTests(TestCase): @classmethod @@ -1418,3 +1433,12 @@ class AliasTests(TestCase): ) with self.assertRaisesMessage(ValueError, msg): Book.objects.alias(**{crafted_alias: Value(1)}) + + def test_alias_filtered_relation_sql_injection(self): + crafted_alias = """injected_name" from "annotations_book"; --""" + msg = ( + "Column aliases cannot contain whitespace characters, quotation marks, " + "semicolons, or SQL comments." + ) + with self.assertRaisesMessage(ValueError, msg): + Book.objects.alias(**{crafted_alias: FilteredRelation("authors")})