Skip to content

Commit

Permalink
[3.2.x] Fixed CVE-2022-28346 -- Protected QuerySet.annotate(), aggreg…
Browse files Browse the repository at this point in the history
…ate(), 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 93cae5c from main.
  • Loading branch information
felixxm committed Apr 11, 2022
1 parent bdb92db commit 2044dac
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 0 deletions.
14 changes: 14 additions & 0 deletions django/db/models/sql/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 8 additions & 0 deletions docs/releases/2.2.28.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 8 additions & 0 deletions docs/releases/3.2.13.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
========

Expand Down
9 changes: 9 additions & 0 deletions tests/aggregation/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")})
43 changes: 43 additions & 0 deletions tests/annotations/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)})
9 changes: 9 additions & 0 deletions tests/expressions/test_queryset_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions tests/queries/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 2044dac

Please sign in to comment.