Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ad866a1

Browse files
committed
[4.2.x] Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation.
Thanks Saravana Kumar for the report, and Sarah Boyce and Mariusz Felisiak for the reviews. Co-authored-by: Natalia <[email protected]>
1 parent b0d309c commit ad866a1

File tree

7 files changed

+116
-14
lines changed

7 files changed

+116
-14
lines changed

django/db/models/fields/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
)
2626
from django.utils.duration import duration_microseconds, duration_string
2727
from django.utils.functional import Promise, cached_property
28-
from django.utils.ipv6 import clean_ipv6_address
28+
from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address
2929
from django.utils.itercompat import is_iterable
3030
from django.utils.text import capfirst
3131
from django.utils.translation import gettext_lazy as _
@@ -2160,7 +2160,7 @@ def __init__(
21602160
invalid_error_message,
21612161
) = validators.ip_address_validators(protocol, unpack_ipv4)
21622162
self.default_error_messages["invalid"] = invalid_error_message
2163-
kwargs["max_length"] = 39
2163+
kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH
21642164
super().__init__(verbose_name, name, *args, **kwargs)
21652165

21662166
def check(self, **kwargs):
@@ -2187,7 +2187,7 @@ def deconstruct(self):
21872187
kwargs["unpack_ipv4"] = self.unpack_ipv4
21882188
if self.protocol != "both":
21892189
kwargs["protocol"] = self.protocol
2190-
if kwargs.get("max_length") == 39:
2190+
if kwargs.get("max_length") == self.max_length:
21912191
del kwargs["max_length"]
21922192
return name, path, args, kwargs
21932193

django/forms/fields.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
from django.utils import formats
4343
from django.utils.dateparse import parse_datetime, parse_duration
4444
from django.utils.duration import duration_string
45-
from django.utils.ipv6 import clean_ipv6_address
45+
from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address
4646
from django.utils.regex_helper import _lazy_re_compile
4747
from django.utils.translation import gettext_lazy as _
4848
from django.utils.translation import ngettext_lazy
@@ -1284,14 +1284,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs):
12841284
self.default_validators = validators.ip_address_validators(
12851285
protocol, unpack_ipv4
12861286
)[0]
1287+
kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH)
12871288
super().__init__(**kwargs)
12881289

12891290
def to_python(self, value):
12901291
if value in self.empty_values:
12911292
return ""
12921293
value = value.strip()
12931294
if value and ":" in value:
1294-
return clean_ipv6_address(value, self.unpack_ipv4)
1295+
return clean_ipv6_address(
1296+
value, self.unpack_ipv4, max_length=self.max_length
1297+
)
12951298
return value
12961299

12971300

django/utils/ipv6.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,22 @@
33
from django.core.exceptions import ValidationError
44
from django.utils.translation import gettext_lazy as _
55

6+
MAX_IPV6_ADDRESS_LENGTH = 39
7+
8+
9+
def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH):
10+
if len(ip_str) > max_length:
11+
raise ValueError(
12+
f"Unable to convert {ip_str} to an IPv6 address (value too long)."
13+
)
14+
return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
15+
616

717
def clean_ipv6_address(
8-
ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")
18+
ip_str,
19+
unpack_ipv4=False,
20+
error_message=_("This is not a valid IPv6 address."),
21+
max_length=MAX_IPV6_ADDRESS_LENGTH,
922
):
1023
"""
1124
Clean an IPv6 address string.
@@ -24,7 +37,7 @@ def clean_ipv6_address(
2437
Return a compressed IPv6 address or the same value.
2538
"""
2639
try:
27-
addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
40+
addr = _ipv6_address_from_str(ip_str, max_length)
2841
except ValueError:
2942
raise ValidationError(error_message, code="invalid")
3043

@@ -41,7 +54,7 @@ def is_valid_ipv6_address(ip_str):
4154
Return whether or not the `ip_str` string is a valid IPv6 address.
4255
"""
4356
try:
44-
ipaddress.IPv6Address(ip_str)
57+
_ipv6_address_from_str(ip_str)
4558
except ValueError:
4659
return False
4760
return True

docs/ref/forms/fields.txt

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -719,15 +719,15 @@ For each field, we describe the default widget used if you don't specify
719719
* Empty value: ``''`` (an empty string)
720720
* Normalizes to: A string. IPv6 addresses are normalized as described below.
721721
* Validates that the given value is a valid IP address.
722-
* Error message keys: ``required``, ``invalid``
722+
* Error message keys: ``required``, ``invalid``, ``max_length``
723723

724724
The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
725725
including using the IPv4 format suggested in paragraph 3 of that section, like
726726
``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
727727
``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
728728
are converted to lowercase.
729729

730-
Takes two optional arguments:
730+
Takes three optional arguments:
731731

732732
.. attribute:: protocol
733733

@@ -742,6 +742,15 @@ For each field, we describe the default widget used if you don't specify
742742
``192.0.2.1``. Default is disabled. Can only be used
743743
when ``protocol`` is set to ``'both'``.
744744

745+
.. attribute:: max_length
746+
747+
Defaults to 39, and behaves the same way as it does for
748+
:class:`CharField`.
749+
750+
.. versionchanged:: 4.2.18
751+
752+
The default value for ``max_length`` was set to 39 characters.
753+
745754
``ImageField``
746755
--------------
747756

docs/releases/4.2.18.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,15 @@ Django 4.2.18 release notes
55
*January 14, 2025*
66

77
Django 4.2.18 fixes a security issue with severity "moderate" in 4.2.17.
8+
9+
CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation
10+
============================================================================
11+
12+
Lack of upper bound limit enforcement in strings passed when performing IPv6
13+
validation could lead to a potential denial-of-service attack. The undocumented
14+
and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were
15+
vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field,
16+
which has now been updated to define a ``max_length`` of 39 characters.
17+
18+
The :class:`django.db.models.GenericIPAddressField` model field was not
19+
affected.

tests/forms_tests/field_tests/test_genericipaddressfield.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from django.core.exceptions import ValidationError
22
from django.forms import GenericIPAddressField
33
from django.test import SimpleTestCase
4+
from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH
45

56

67
class GenericIPAddressFieldTest(SimpleTestCase):
@@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self):
125126
):
126127
f.clean("1:2")
127128

129+
def test_generic_ipaddress_max_length_custom(self):
130+
# Valid IPv4-mapped IPv6 address, len 45.
131+
addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228"
132+
f = GenericIPAddressField(max_length=len(addr))
133+
f.clean(addr)
134+
135+
def test_generic_ipaddress_max_length_validation_error(self):
136+
# Valid IPv4-mapped IPv6 address, len 45.
137+
addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228"
138+
139+
cases = [
140+
({}, MAX_IPV6_ADDRESS_LENGTH), # Default value.
141+
({"max_length": len(addr) - 1}, len(addr) - 1),
142+
]
143+
for kwargs, max_length in cases:
144+
max_length_plus_one = max_length + 1
145+
msg = (
146+
f"Ensure this value has at most {max_length} characters (it has "
147+
f"{max_length_plus_one}).'"
148+
)
149+
with self.subTest(max_length=max_length):
150+
f = GenericIPAddressField(**kwargs)
151+
with self.assertRaisesMessage(ValidationError, msg):
152+
f.clean("x" * max_length_plus_one)
153+
with self.assertRaisesMessage(
154+
ValidationError, "This is not a valid IPv6 address."
155+
):
156+
f.clean(addr)
157+
128158
def test_generic_ipaddress_as_generic_not_required(self):
129159
f = GenericIPAddressField(required=False)
130160
self.assertEqual(f.clean(""), "")
@@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self):
150180
f.clean(" fe80::223:6cff:fe8a:2e8a "), "fe80::223:6cff:fe8a:2e8a"
151181
)
152182
self.assertEqual(
153-
f.clean(" 2a02::223:6cff:fe8a:2e8a "), "2a02::223:6cff:fe8a:2e8a"
183+
f.clean(" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a "),
184+
"2a02::223:6cff:fe8a:2e8a",
154185
)
155186
with self.assertRaisesMessage(
156187
ValidationError, "'This is not a valid IPv6 address.'"

tests/utils_tests/test_ipv6.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
1-
import unittest
1+
import traceback
2+
from io import StringIO
23

3-
from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address
4+
from django.core.exceptions import ValidationError
5+
from django.test import SimpleTestCase
6+
from django.utils.ipv6 import (
7+
MAX_IPV6_ADDRESS_LENGTH,
8+
clean_ipv6_address,
9+
is_valid_ipv6_address,
10+
)
11+
from django.utils.version import PY310
412

513

6-
class TestUtilsIPv6(unittest.TestCase):
14+
class TestUtilsIPv6(SimpleTestCase):
715
def test_validates_correct_plain_address(self):
816
self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a"))
917
self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a"))
@@ -64,3 +72,29 @@ def test_unpacks_ipv4(self):
6472
self.assertEqual(
6573
clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52"
6674
)
75+
76+
def test_address_too_long(self):
77+
addresses = [
78+
"0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address
79+
"0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone
80+
"fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1
81+
]
82+
msg = "This is the error message."
83+
value_error_msg = "Unable to convert %s to an IPv6 address (value too long)."
84+
for addr in addresses:
85+
with self.subTest(addr=addr):
86+
self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH)
87+
self.assertEqual(is_valid_ipv6_address(addr), False)
88+
with self.assertRaisesMessage(ValidationError, msg) as ctx:
89+
clean_ipv6_address(addr, error_message=msg)
90+
exception_traceback = StringIO()
91+
if PY310:
92+
traceback.print_exception(ctx.exception, file=exception_traceback)
93+
else:
94+
traceback.print_exception(
95+
type(ctx.exception),
96+
value=ctx.exception,
97+
tb=ctx.exception.__traceback__,
98+
file=exception_traceback,
99+
)
100+
self.assertIn(value_error_msg % addr, exception_traceback.getvalue())

0 commit comments

Comments
 (0)