Security advisory GHSA-2gwj-7jmv-h26r: SQL Injection in Django
Package: django (pypi), vulnerable version: 2.2.27, fixed in: 2.2.28
CWE: CWE-89
Files changed by the fix:
django/db/models/sql/query.py

Fix diff:
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index f5f85a4d348e..1df916b724ec 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -41,10 +41,15 @@
 )
 from django.utils.deprecation import RemovedInDjango40Warning
 from django.utils.functional import cached_property
+from django.utils.regex_helper import _lazy_re_compile
 from django.utils.tree import Node
 
 __all__ = ['Query', 'RawQuery']
 
+# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
+# SQL comments are forbidden in column aliases.
+FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
+
 
 def get_field_names_from_opts(opts):
     return set(chain.from_iterable(
@@ -1034,8 +1039,16 @@ def join_parent_model(self, opts, model, alias, seen):
             alias = seen[int_model] = join_info.joins[-1]
         return alias or seen[None]
 
+    def check_alias(self, alias):
+        if FORBIDDEN_ALIAS_PATTERN.search(alias):
+            raise ValueError(
+                "Column aliases cannot contain whitespace characters, quotation marks, "
+                "semicolons, or SQL comments."
+            )
+
     def add_annotation(self, annotation, alias, is_summary=False, select=True):
         """Add a single annotation expression to the Query."""
+        self.check_alias(alias)
         annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
                                                    summarize=is_summary)
         if select:
@@ -2088,6 +2101,7 @@ def add_extra(self, select, select_params, where, params, tables, order_by):
             else:
                 param_iter = iter([])
             for name, entry in select.items():
+                self.check_alias(name)
                 entry = str(entry)
                 entry_params = []
                 pos = entry.find("%s")
diff --git a/docs/releases/2.2.28.txt b/docs/releases/2.2.28.txt
index 0669e2d599b6..a894bddb3c55 100644
--- a/docs/releases/2.2.28.txt
+++ b/docs/releases/2.2.28.txt
@@ -5,3 +5,11 @@ Django 2.2.28 release notes
 *April 11, 2022*
 
 Django 2.2.28 fixes two security issues with severity "high" in 2.2.27.
+
+CVE-2022-28346: Potential SQL injection in ``QuerySet.annotate()``, ``aggregate()``, and ``extra()``
+====================================================================================================
+
+:meth:`.QuerySet.annotate`, :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.
diff --git a/docs/releases/3.2.13.txt b/docs/releases/3.2.13.txt
index c26a969f950a..ee20aa2ca1a5 100644
--- a/docs/releases/3.2.13.txt
+++ b/docs/releases/3.2.13.txt
@@ -7,6 +7,14 @@ Django 3.2.13 release notes
 Django 3.2.13 fixes two security issues with severity "high" in
 3.2.12 and a regression in 3.2.4.
 
+CVE-2022-28346: Potential SQL injection in ``QuerySet.annotate()``, ``aggregate()``, and ``extra()``
+====================================================================================================
+
+:meth:`.QuerySet.annotate`, :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.
+
 Bugfixes
 ========
 
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index 49123396dd51..d3d744c3d47d 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -1340,3 +1340,12 @@ def test_aggregation_random_ordering(self):
             ('Stuart Russell', 1),
             ('Peter Norvig', 2),
         ], lambda a: (a.name, a.contact_count), ordered=False)
+
+    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."
+        )
+        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 8337f344ed99..8082c7af7585 100644
--- a/tests/annotations/tests.py
+++ b/tests/annotations/tests.py
@@ -766,6 +766,40 @@ def test_annotation_aggregate_with_m2o(self):
             {'name': 'Wesley J. Chun', 'max_pages': 0},
         ])
 
+    def test_alias_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: Value(1)})
+
+    def test_alias_forbidden_chars(self):
+        tests = [
+            'al"ias',
+            "a'lias",
+            "ali`as",
+            "alia s",
+            "alias\t",
+            "ali\nas",
+            "alias--",
+            "ali/*as",
+            "alias*/",
+            "alias;",
+            # [] are used by MSSQL.
+            "alias[",
+            "alias]",
+        ]
+        msg = (
+            "Column aliases cannot contain whitespace characters, quotation marks, "
+            "semicolons, or SQL comments."
+        )
+        for crafted_alias in tests:
+            with self.subTest(crafted_alias):
+                with self.assertRaisesMessage(ValueError, msg):
+                    Book.objects.annotate(**{crafted_alias: Value(1)})
+
 
 class AliasTests(TestCase):
     @classmethod
@@ -996,3 +1030,12 @@ def test_values_alias(self):
             with self.subTest(operation=operation):
                 with self.assertRaisesMessage(FieldError, msg):
                     getattr(qs, operation)('rating_alias')
+
+    def test_alias_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: Value(1)})
diff --git a/tests/expressions/test_queryset_values.py b/tests/expressions/test_queryset_values.py
index a15cc26023b0..457a357d041b 100644
--- a/tests/expressions/test_queryset_values.py
+++ b/tests/expressions/test_queryset_values.py
@@ -26,6 +26,15 @@ def test_values_expression(self):
             [{'salary': 10}, {'salary': 20}, {'salary': 30}],
         )
 
+    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."
+        )
+        with self.assertRaisesMessage(ValueError, msg):
+            Company.objects.values(**{crafted_alias: F("ceo__salary")})
+
     def test_values_expression_group_by(self):
         # values() applies annotate() first, so values selected are grouped by
         # id, not firstname.
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index d487026e4d36..4e6ff67e4906 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -1677,6 +1677,15 @@ def test_extra_select_literal_percent_s(self):
             'bar %s'
         )
 
+    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."
+        )
+        with self.assertRaisesMessage(ValueError, msg):
+            Note.objects.extra(select={crafted_alias: "1"})
+
 
 class SelectRelatedTests(TestCase):
     def test_tickets_3045_3288(self):