Skip to content

Commit 454f2fb

Browse files
committed
[3.2.x] Fixed CVE-2023-36053 -- Prevented potential ReDoS in EmailValidator and URLValidator.
Thanks Seokchan Yoon for reports.
1 parent 07cc014 commit 454f2fb

File tree

8 files changed

+72
-12
lines changed

8 files changed

+72
-12
lines changed

django/core/validators.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,15 @@ class URLValidator(RegexValidator):
9393
message = _('Enter a valid URL.')
9494
schemes = ['http', 'https', 'ftp', 'ftps']
9595
unsafe_chars = frozenset('\t\r\n')
96+
max_length = 2048
9697

9798
def __init__(self, schemes=None, **kwargs):
9899
super().__init__(**kwargs)
99100
if schemes is not None:
100101
self.schemes = schemes
101102

102103
def __call__(self, value):
103-
if not isinstance(value, str):
104+
if not isinstance(value, str) or len(value) > self.max_length:
104105
raise ValidationError(self.message, code=self.code, params={'value': value})
105106
if self.unsafe_chars.intersection(value):
106107
raise ValidationError(self.message, code=self.code, params={'value': value})
@@ -210,7 +211,9 @@ def __init__(self, message=None, code=None, allowlist=None, *, whitelist=None):
210211
self.domain_allowlist = allowlist
211212

212213
def __call__(self, value):
213-
if not value or '@' not in value:
214+
# The maximum length of an email is 320 characters per RFC 3696
215+
# section 3.
216+
if not value or '@' not in value or len(value) > 320:
214217
raise ValidationError(self.message, code=self.code, params={'value': value})
215218

216219
user_part, domain_part = value.rsplit('@', 1)

django/forms/fields.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,9 @@ class EmailField(CharField):
540540
default_validators = [validators.validate_email]
541541

542542
def __init__(self, **kwargs):
543+
# The default maximum length of an email is 320 characters per RFC 3696
544+
# section 3.
545+
kwargs.setdefault("max_length", 320)
543546
super().__init__(strip=True, **kwargs)
544547

545548

docs/ref/forms/fields.txt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,12 @@ For each field, we describe the default widget used if you don't specify
592592
* Error message keys: ``required``, ``invalid``
593593

594594
Has three optional arguments ``max_length``, ``min_length``, and
595-
``empty_value`` which work just as they do for :class:`CharField`.
595+
``empty_value`` which work just as they do for :class:`CharField`. The
596+
``max_length`` argument defaults to 320 (see :rfc:`3696#section-3`).
597+
598+
.. versionchanged:: 3.2.20
599+
600+
The default value for ``max_length`` was changed to 320 characters.
596601

597602
``FileField``
598603
-------------

docs/ref/validators.txt

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ to, or in lieu of custom ``field.clean()`` methods.
130130
:param code: If not ``None``, overrides :attr:`code`.
131131
:param allowlist: If not ``None``, overrides :attr:`allowlist`.
132132

133+
An :class:`EmailValidator` ensures that a value looks like an email, and
134+
raises a :exc:`~django.core.exceptions.ValidationError` with
135+
:attr:`message` and :attr:`code` if it doesn't. Values longer than 320
136+
characters are always considered invalid.
137+
133138
.. attribute:: message
134139

135140
The error message used by
@@ -158,13 +163,19 @@ to, or in lieu of custom ``field.clean()`` methods.
158163
The undocumented ``domain_whitelist`` attribute is deprecated. Use
159164
``domain_allowlist`` instead.
160165

166+
.. versionchanged:: 3.2.20
167+
168+
In older versions, values longer than 320 characters could be
169+
considered valid.
170+
161171
``URLValidator``
162172
----------------
163173

164174
.. class:: URLValidator(schemes=None, regex=None, message=None, code=None)
165175

166176
A :class:`RegexValidator` subclass that ensures a value looks like a URL,
167-
and raises an error code of ``'invalid'`` if it doesn't.
177+
and raises an error code of ``'invalid'`` if it doesn't. Values longer than
178+
:attr:`max_length` characters are always considered invalid.
168179

169180
Loopback addresses and reserved IP spaces are considered valid. Literal
170181
IPv6 addresses (:rfc:`3986#section-3.2.2`) and Unicode domains are both
@@ -181,6 +192,18 @@ to, or in lieu of custom ``field.clean()`` methods.
181192

182193
.. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
183194

195+
.. attribute:: max_length
196+
197+
.. versionadded:: 3.2.20
198+
199+
The maximum length of values that could be considered valid. Defaults
200+
to 2048 characters.
201+
202+
.. versionchanged:: 3.2.20
203+
204+
In older versions, values longer than 2048 characters could be
205+
considered valid.
206+
184207
``validate_email``
185208
------------------
186209

docs/releases/3.2.20.txt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,9 @@ Django 3.2.20 release notes
66

77
Django 3.2.20 fixes a security issue with severity "moderate" in 3.2.19.
88

9-
...
9+
CVE-2023-36053: Potential regular expression denial of service vulnerability in ``EmailValidator``/``URLValidator``
10+
===================================================================================================================
11+
12+
``EmailValidator`` and ``URLValidator`` were subject to potential regular
13+
expression denial of service attack via a very large number of domain name
14+
labels of emails and URLs.

tests/forms_tests/field_tests/test_emailfield.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
99

1010
def test_emailfield_1(self):
1111
f = EmailField()
12-
self.assertWidgetRendersTo(f, '<input type="email" name="f" id="id_f" required>')
12+
self.assertEqual(f.max_length, 320)
13+
self.assertWidgetRendersTo(
14+
f, '<input type="email" name="f" id="id_f" maxlength="320" required>'
15+
)
1316
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
1417
f.clean('')
1518
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):

tests/forms_tests/tests/test_forms.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -422,11 +422,18 @@ class SignupForm(Form):
422422
get_spam = BooleanField()
423423

424424
f = SignupForm(auto_id=False)
425-
self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" required>')
425+
self.assertHTMLEqual(
426+
str(f["email"]),
427+
'<input type="email" name="email" maxlength="320" required>',
428+
)
426429
self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>')
427430

428431
f = SignupForm({'email': '[email protected]', 'get_spam': True}, auto_id=False)
429-
self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="[email protected]" required>')
432+
self.assertHTMLEqual(
433+
str(f["email"]),
434+
'<input type="email" name="email" maxlength="320" value="[email protected]" '
435+
"required>",
436+
)
430437
self.assertHTMLEqual(
431438
str(f['get_spam']),
432439
'<input checked type="checkbox" name="get_spam" required>',
@@ -2824,7 +2831,7 @@ class Person(Form):
28242831
<option value="true">Yes</option>
28252832
<option value="false">No</option>
28262833
</select></li>
2827-
<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li>
2834+
<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" maxlength="320"></li>
28282835
<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
28292836
<label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>"""
28302837
)
@@ -2840,7 +2847,7 @@ class Person(Form):
28402847
<option value="true">Yes</option>
28412848
<option value="false">No</option>
28422849
</select></p>
2843-
<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p>
2850+
<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email" maxlength="320"></p>
28442851
<ul class="errorlist"><li>This field is required.</li></ul>
28452852
<p class="required error"><label class="required" for="id_age">Age:</label>
28462853
<input type="number" name="age" id="id_age" required></p>"""
@@ -2859,7 +2866,7 @@ class Person(Form):
28592866
<option value="false">No</option>
28602867
</select></td></tr>
28612868
<tr><th><label for="id_email">Email:</label></th><td>
2862-
<input type="email" name="email" id="id_email"></td></tr>
2869+
<input type="email" name="email" id="id_email" maxlength="320"></td></tr>
28632870
<tr class="required error"><th><label class="required" for="id_age">Age:</label></th>
28642871
<td><ul class="errorlist"><li>This field is required.</li></ul>
28652872
<input type="number" name="age" id="id_age" required></td></tr>"""
@@ -3489,7 +3496,7 @@ class CommentForm(Form):
34893496
f = CommentForm(data, auto_id=False, error_class=DivErrorList)
34903497
self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p>
34913498
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
3492-
<p>Email: <input type="email" name="email" value="invalid" required></p>
3499+
<p>Email: <input type="email" name="email" value="invalid" maxlength="320" required></p>
34933500
<div class="errorlist"><div class="error">This field is required.</div></div>
34943501
<p>Comment: <input type="text" name="comment" required></p>""")
34953502

tests/validators/tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959

6060
(validate_email, 'example@atm.%s' % ('a' * 64), ValidationError),
6161
(validate_email, 'example@%s.atm.%s' % ('b' * 64, 'a' * 63), ValidationError),
62+
(validate_email, "example@%scom" % (("a" * 63 + ".") * 100), ValidationError),
6263
(validate_email, None, ValidationError),
6364
(validate_email, '', ValidationError),
6465
(validate_email, 'abc', ValidationError),
@@ -246,6 +247,16 @@
246247
(URLValidator(), None, ValidationError),
247248
(URLValidator(), 56, ValidationError),
248249
(URLValidator(), 'no_scheme', ValidationError),
250+
(
251+
URLValidator(),
252+
"http://example." + ("a" * 63 + ".") * 1000 + "com",
253+
ValidationError,
254+
),
255+
(
256+
URLValidator(),
257+
"http://userid:password" + "d" * 2000 + "@example.aaaaaaaaaaaaa.com",
258+
None,
259+
),
249260
# Newlines and tabs are not accepted.
250261
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
251262
(URLValidator(), 'http://[::ffff:192.9.5.5]\n', ValidationError),

0 commit comments

Comments
 (0)