From 2044dac5c6968441be6f534c4139bcf48c5c7e48 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Fri, 1 Apr 2022 08:10:22 +0200 Subject: [PATCH] [3.2.x] Fixed CVE-2022-28346 -- Protected QuerySet.annotate(), aggregate(), and extra() against SQL injection in column aliases. Thanks Splunk team: Preston Elder, Jacob Davis, Jacob Moore, Matt Hanson, David Briggs, and a security researcher: Danylo Dmytriiev (DDV_UA) for the report. Backport of 93cae5cb2f9a4ef1514cf1a41f714fef08005200 from main. --- django/db/models/sql/query.py | 14 ++++++++ docs/releases/2.2.28.txt | 8 +++++ docs/releases/3.2.13.txt | 8 +++++ tests/aggregation/tests.py | 9 +++++ tests/annotations/tests.py | 43 +++++++++++++++++++++++ tests/expressions/test_queryset_values.py | 9 +++++ tests/queries/tests.py | 9 +++++ 7 files changed, 100 insertions(+) diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index f5f85a4d34..1df916b724 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -41,10 +41,15 @@ from django.db.models.sql.where import ( ) 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 @@ class Query(BaseExpression): 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 @@ class Query(BaseExpression): 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 0669e2d599..a894bddb3c 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 c26a969f95..ee20aa2ca1 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 49123396dd..d3d744c3d4 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1340,3 +1340,12 @@ class AggregateTestCase(TestCase): ('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 8337f344ed..8082c7af75 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -766,6 +766,40 @@ class NonAggregateAnnotationTestCase(TestCase): {'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 @@ class AliasTests(TestCase): 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 a15cc26023..457a357d04 100644 --- a/tests/expressions/test_queryset_values.py +++ b/tests/expressions/test_queryset_values.py @@ -26,6 +26,15 @@ class ValuesExpressionsTests(TestCase): [{'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 d487026e4d..4e6ff67e49 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -1677,6 +1677,15 @@ class Queries5Tests(TestCase): '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):