Skip to content

Commit 93cae5c

Browse files
committed
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.
1 parent 62739b6 commit 93cae5c

File tree

8 files changed

+108
-0
lines changed

8 files changed

+108
-0
lines changed

django/db/models/sql/query.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,15 @@
4040
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
4141
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
4242
from django.utils.functional import cached_property
43+
from django.utils.regex_helper import _lazy_re_compile
4344
from django.utils.tree import Node
4445

4546
__all__ = ["Query", "RawQuery"]
4647

48+
# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
49+
# SQL comments are forbidden in column aliases.
50+
FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
51+
4752

4853
def get_field_names_from_opts(opts):
4954
if opts is None:
@@ -1091,8 +1096,16 @@ def join_parent_model(self, opts, model, alias, seen):
10911096
alias = seen[int_model] = join_info.joins[-1]
10921097
return alias or seen[None]
10931098

1099+
def check_alias(self, alias):
1100+
if FORBIDDEN_ALIAS_PATTERN.search(alias):
1101+
raise ValueError(
1102+
"Column aliases cannot contain whitespace characters, quotation marks, "
1103+
"semicolons, or SQL comments."
1104+
)
1105+
10941106
def add_annotation(self, annotation, alias, is_summary=False, select=True):
10951107
"""Add a single annotation expression to the Query."""
1108+
self.check_alias(alias)
10961109
annotation = annotation.resolve_expression(
10971110
self, allow_joins=True, reuse=None, summarize=is_summary
10981111
)
@@ -2269,6 +2282,7 @@ def add_extra(self, select, select_params, where, params, tables, order_by):
22692282
else:
22702283
param_iter = iter([])
22712284
for name, entry in select.items():
2285+
self.check_alias(name)
22722286
entry = str(entry)
22732287
entry_params = []
22742288
pos = entry.find("%s")

docs/releases/2.2.28.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,11 @@ Django 2.2.28 release notes
55
*April 11, 2022*
66

77
Django 2.2.28 fixes two security issues with severity "high" in 2.2.27.
8+
9+
CVE-2022-28346: Potential SQL injection in ``QuerySet.annotate()``, ``aggregate()``, and ``extra()``
10+
====================================================================================================
11+
12+
:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.aggregate`, and
13+
:meth:`~.QuerySet.extra` methods were subject to SQL injection in column
14+
aliases, using a suitably crafted dictionary, with dictionary expansion, as the
15+
``**kwargs`` passed to these methods.

docs/releases/3.2.13.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ Django 3.2.13 release notes
77
Django 3.2.13 fixes two security issues with severity "high" in
88
3.2.12 and a regression in 3.2.4.
99

10+
CVE-2022-28346: Potential SQL injection in ``QuerySet.annotate()``, ``aggregate()``, and ``extra()``
11+
====================================================================================================
12+
13+
:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.aggregate`, and
14+
:meth:`~.QuerySet.extra` methods were subject to SQL injection in column
15+
aliases, using a suitably crafted dictionary, with dictionary expansion, as the
16+
``**kwargs`` passed to these methods.
17+
1018
Bugfixes
1119
========
1220

docs/releases/4.0.4.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ Django 4.0.4 release notes
77
Django 4.0.4 fixes two security issues with severity "high" and two bugs in
88
4.0.3.
99

10+
CVE-2022-28346: Potential SQL injection in ``QuerySet.annotate()``, ``aggregate()``, and ``extra()``
11+
====================================================================================================
12+
13+
:meth:`.QuerySet.annotate`, :meth:`~.QuerySet.aggregate`, and
14+
:meth:`~.QuerySet.extra` methods were subject to SQL injection in column
15+
aliases, using a suitably crafted dictionary, with dictionary expansion, as the
16+
``**kwargs`` passed to these methods.
17+
1018
Bugfixes
1119
========
1220

tests/aggregation/tests.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2048,6 +2048,15 @@ def test_exists_none_with_aggregate(self):
20482048
)
20492049
self.assertEqual(len(qs), 6)
20502050

2051+
def test_alias_sql_injection(self):
2052+
crafted_alias = """injected_name" from "aggregation_author"; --"""
2053+
msg = (
2054+
"Column aliases cannot contain whitespace characters, quotation marks, "
2055+
"semicolons, or SQL comments."
2056+
)
2057+
with self.assertRaisesMessage(ValueError, msg):
2058+
Author.objects.aggregate(**{crafted_alias: Avg("age")})
2059+
20512060
def test_exists_extra_where_with_aggregate(self):
20522061
qs = Book.objects.annotate(
20532062
count=Count("id"),

tests/annotations/tests.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,6 +1076,40 @@ def test_annotation_aggregate_with_m2o(self):
10761076
],
10771077
)
10781078

1079+
def test_alias_sql_injection(self):
1080+
crafted_alias = """injected_name" from "annotations_book"; --"""
1081+
msg = (
1082+
"Column aliases cannot contain whitespace characters, quotation marks, "
1083+
"semicolons, or SQL comments."
1084+
)
1085+
with self.assertRaisesMessage(ValueError, msg):
1086+
Book.objects.annotate(**{crafted_alias: Value(1)})
1087+
1088+
def test_alias_forbidden_chars(self):
1089+
tests = [
1090+
'al"ias',
1091+
"a'lias",
1092+
"ali`as",
1093+
"alia s",
1094+
"alias\t",
1095+
"ali\nas",
1096+
"alias--",
1097+
"ali/*as",
1098+
"alias*/",
1099+
"alias;",
1100+
# [] are used by MSSQL.
1101+
"alias[",
1102+
"alias]",
1103+
]
1104+
msg = (
1105+
"Column aliases cannot contain whitespace characters, quotation marks, "
1106+
"semicolons, or SQL comments."
1107+
)
1108+
for crafted_alias in tests:
1109+
with self.subTest(crafted_alias):
1110+
with self.assertRaisesMessage(ValueError, msg):
1111+
Book.objects.annotate(**{crafted_alias: Value(1)})
1112+
10791113

10801114
class AliasTests(TestCase):
10811115
@classmethod
@@ -1339,3 +1373,12 @@ def test_values_alias(self):
13391373
with self.subTest(operation=operation):
13401374
with self.assertRaisesMessage(FieldError, msg):
13411375
getattr(qs, operation)("rating_alias")
1376+
1377+
def test_alias_sql_injection(self):
1378+
crafted_alias = """injected_name" from "annotations_book"; --"""
1379+
msg = (
1380+
"Column aliases cannot contain whitespace characters, quotation marks, "
1381+
"semicolons, or SQL comments."
1382+
)
1383+
with self.assertRaisesMessage(ValueError, msg):
1384+
Book.objects.alias(**{crafted_alias: Value(1)})

tests/expressions/test_queryset_values.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@ def test_values_expression(self):
3434
[{"salary": 10}, {"salary": 20}, {"salary": 30}],
3535
)
3636

37+
def test_values_expression_alias_sql_injection(self):
38+
crafted_alias = """injected_name" from "expressions_company"; --"""
39+
msg = (
40+
"Column aliases cannot contain whitespace characters, quotation marks, "
41+
"semicolons, or SQL comments."
42+
)
43+
with self.assertRaisesMessage(ValueError, msg):
44+
Company.objects.values(**{crafted_alias: F("ceo__salary")})
45+
3746
def test_values_expression_group_by(self):
3847
# values() applies annotate() first, so values selected are grouped by
3948
# id, not firstname.

tests/queries/tests.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1898,6 +1898,15 @@ def test_extra_select_literal_percent_s(self):
18981898
Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s"
18991899
)
19001900

1901+
def test_extra_select_alias_sql_injection(self):
1902+
crafted_alias = """injected_name" from "queries_note"; --"""
1903+
msg = (
1904+
"Column aliases cannot contain whitespace characters, quotation marks, "
1905+
"semicolons, or SQL comments."
1906+
)
1907+
with self.assertRaisesMessage(ValueError, msg):
1908+
Note.objects.extra(select={crafted_alias: "1"})
1909+
19011910
def test_queryset_reuse(self):
19021911
# Using querysets doesn't mutate aliases.
19031912
authors = Author.objects.filter(Q(name="a1") | Q(name="nonexistent"))

0 commit comments

Comments
 (0)