From a9010fe5555e6086a9d9ae50069579400ef0685e Mon Sep 17 00:00:00 2001
From: Mariusz Felisiak <felisiak.mariusz@gmail.com>
Date: Wed, 22 Jun 2022 12:44:04 +0200
Subject: [PATCH] [3.2.x] Fixed CVE-2022-34265 -- Protected
 Trunc(kind)/Extract(lookup_name) against SQL injection.

Thanks Takuto Yoshikai (Aeye Security Lab) for the report.
---
 django/db/backends/base/operations.py         |  3 ++
 django/db/models/functions/datetime.py        |  4 +++
 docs/releases/3.2.14.txt                      | 11 ++++++
 .../datetime/test_extract_trunc.py            | 34 +++++++++++++++++++
 4 files changed, 52 insertions(+)

diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py
index 0fcc607bcfb0..cdcd9885ba27 100644
--- a/django/db/backends/base/operations.py
+++ b/django/db/backends/base/operations.py
@@ -10,6 +10,7 @@
 from django.utils.dateparse import parse_duration
 from django.utils.deprecation import RemovedInDjango20Warning
 from django.utils.encoding import force_text
+from django.core.validators import _lazy_re_compile
 
 
 class BaseDatabaseOperations(object):
@@ -35,6 +36,8 @@ class BaseDatabaseOperations:
         'difference': 'EXCEPT',
     }
 
+    extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+")
+
     def __init__(self, connection):
         self.connection = connection
         self._cache = None
diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py
index 90e6f41be057..47651d281f19 100644
--- a/django/db/models/functions/datetime.py
+++ b/django/db/models/functions/datetime.py
@@ -42,6 +42,8 @@ def __init__(self, expression, lookup_name=None, tzinfo=None, **extra):
         super(Extract, self).__init__(expression, **extra)
 
     def as_sql(self, compiler, connection):
+        if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.lookup_name):
+            raise ValueError("Invalid lookup_name: %s" % self.lookup_name)
         sql, params = compiler.compile(self.lhs)
         lhs_output_field = self.lhs.output_field
         if isinstance(lhs_output_field, DateTimeField):
@@ -147,6 +149,8 @@ def __init__(self, expression, output_field=None, tzinfo=None, is_dst=None, **ex
         super(TruncBase, self).__init__(expression, output_field=output_field, **extra)
 
     def as_sql(self, compiler, connection):
+        if not connection.ops.extract_trunc_lookup_pattern.fullmatch(self.kind):
+            raise ValueError("Invalid kind: %s" % self.kind)
         inner_sql, inner_params = compiler.compile(self.lhs)
         # Escape any params because trunc_sql will format the string.
         inner_sql = inner_sql.replace('%s', '%%s')
diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py
index 258600127f93..27ed3ae63ee5 100644
--- a/tests/db_functions/test_datetime.py
+++ b/tests/db_functions/test_datetime.py
@@ -132,6 +132,23 @@ def test_extract_year_lessthan_lookup(self):
         self.assertEqual(qs.count(), 2)
         self.assertEqual(str(qs.query).count('extract'), 0)
 
+    def test_extract_lookup_name_sql_injection(self):
+        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
+        end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
+        if settings.USE_TZ:
+            start_datetime = timezone.make_aware(start_datetime)
+            end_datetime = timezone.make_aware(end_datetime)
+        self.create_model(start_datetime, end_datetime)
+        self.create_model(end_datetime, start_datetime)
+
+        msg = "Invalid lookup_name: "
+        with self.assertRaisesMessage(ValueError, msg):
+            DTModel.objects.filter(
+                start_datetime__year=Extract(
+                    "start_datetime", "day' FROM start_datetime)) OR 1=1;--"
+                )
+            ).exists()
+
     def test_extract_func(self):
         start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
         end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
@@ -393,6 +410,23 @@ def test_extract_second_func(self):
         )
         self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)
 
+    def test_trunc_lookup_name_sql_injection(self):
+        start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
+        end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
+        if settings.USE_TZ:
+            start_datetime = timezone.make_aware(start_datetime)
+            end_datetime = timezone.make_aware(end_datetime)
+        self.create_model(start_datetime, end_datetime)
+        self.create_model(end_datetime, start_datetime)
+        msg = "Invalid kind: "
+        with self.assertRaisesMessage(ValueError, msg):
+            DTModel.objects.filter(
+                start_datetime__date=Trunc(
+                    "start_datetime",
+                    "year', start_datetime)) OR 1=1;--",
+                )
+            ).exists()
+
     def test_trunc_func(self):
         start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
         end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
