8000 Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation. · gtossou/django@ca2be77 · GitHub
[go: up one dir, main page]

Skip to content

Commit ca2be77

Browse files
manfrenessita
andcommitted
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 <124304+nessita@users.noreply.github.com>
1 parent 9a2dd97 commit ca2be77

File tree

9 files changed

+131
-14
lines changed

9 files changed

+131
-14
lines changed

django/db/models/fields/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
)
3333
from django.utils.duration import duration_microseconds, duration_string
3434
from django.utils.functional import Promise, cached_property
35-
from django.utils.ipv6 import clean_ipv6_address
35+
from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address
3636
from django.utils.text import capfirst
3737
from django.utils.translation import gettext_lazy as _
3838

@@ -2233,7 +2233,7 @@ def __init__(
22332233
self.default_validators = validators.ip_address_validators(
22342234
protocol, unpack_ipv4
22352235
)
2236-
kwargs["max_length"] = 39
2236+
kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH
22372237
super().__init__(verbose_name, name, *args, **kwargs)
22382238

22392239
def check(self, **kwargs):
@@ -2260,7 +2260,7 @@ def deconstruct(self):
22602260
kwargs["unpack_ipv4"] = self.unpack_ipv4
22612261
if self.protocol != "both":
22622262
kwargs["protocol"] = self.protocol
2263-
if kwargs.get("max_length") == 39:
2263+
if kwargs.get("max_length") == self.max_length:
22642264
del kwargs["max_length"]
22652265
return name, path, args, kwargs
22662266

django/forms/fields.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
from django.utils.dateparse import parse_datetime, parse_duration
4747
from django.utils.deprecation import RemovedInDjango60Warning
4848
from django.utils.duration import duration_string
49-
from django.utils.ipv6 import clean_ipv6_address
49+
from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address
5050
from django.utils.regex_helper import _lazy_re_compile
5151
from django.utils.translation import gettext_lazy as _
5252
from django.utils.translation import ngettext_lazy
@@ -1303,14 +1303,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs):
13031303
self.default_validators = validators.ip_address_validators(
13041304
protocol, unpack_ipv4
13051305
)
1306+
kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH)
13061307
super().__init__(**kwargs)
13071308

13081309
def to_python(self, value):
13091310
if value in self.empty_values:
13101311
return ""
13111312
value = value.strip()
13121313
if value and ":" in value:
1313-
return clean_ipv6_address(value, self.unpack_ipv4)
1314+
return clean_ipv6_address(
1315+
value, self.unpack_ipv4, max_length=self.max_length
1316+
)
13141317
return value
13151318

13161319

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(
3043
error_message, code="invalid", params={"protocol": _("IPv6")}
@@ -43,7 +56,7 @@ def is_valid_ipv6_address(ip_str):
4356
Return whether or not the `ip_str` string is a valid IPv6 address.
4457
"""
4558
try:
46-
ipaddress.IPv6Address(ip_str)
59+
_ipv6_address_from_str(ip_str)
4760
except ValueError:
4861
return False
4962
return True

docs/ref/forms/fields.txt

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

766766
The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,
767767
including using the IPv4 format suggested in paragraph 3 of that section, like
768768
``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to
769769
``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters
770770
are converted to lowercase.
771771

772-
Takes two optional arguments:
772+
Takes three optional arguments:
773773

774774
.. attribute:: protocol
775775

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

787+
.. attribute:: max_length
788+
789+
Defaults to 39, and behaves the same way as it does for
790+
:class:`CharField`.
791+
792+
.. versionchanged:: 4.2.18
793+
794+
The default value for ``max_length`` was set to 39 characters.
795+
787796
``ImageField``
788797
--------------
789798

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.

docs/releases/5.0.11.txt

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

77
Django 5.0.11 fixes a security issue with severity "moderate" in 5.0.10.
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.

docs/releases/5.1.5.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@ Django 5.1.5 release notes
77
Django 5.1.5 fixes a security issue with severity "moderate" and one bug in
88
5.1.4.
99

10+
CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation
11+
============================================================================
12+
13+
Lack of upper bound limit enforcement in strings passed when performing IPv6
14+
validation could lead to a potential denial-of-service attack. The undocumented
15+
and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were
16+
vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field,
17+
which has now been updated to define a ``max_length`` of 39 characters.
18+
19+
The :class:`django.db.models.GenericIPAddressField` model field was not
20+
affected.
21+
1022
Bugfixes
1123
========
1224

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: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
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+
)
411

512

6-
class TestUtilsIPv6(unittest.TestCase):
13+
class TestUtilsIPv6(SimpleTestCase):
714
def test_validates_correct_plain_address(self):
815
self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a"))
916
self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a"))
@@ -64,3 +71,21 @@ def test_unpacks_ipv4(self):
6471
self.assertEqual(
6572
clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52"
6673
)
74+
75+
def test_address_too_long(self):
76+
addresses = [
77+
"0000:0000:0000:0000:0000:f 86D4 fff:192.168.100.228", # IPv4-mapped IPv6 address
78+
"0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone
79+
"fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1
80+
]
81+
msg = "This is the error message."
82+
value_error_msg = "Unable to convert %s to an IPv6 address (value too long)."
83+
for addr in addresses:
84+
with self.subTest(addr=addr):
85+
self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH)
86+
self.assertEqual(is_valid_ipv6_address(addr), False)
87+
with self.assertRaisesMessage(ValidationError, msg) as ctx:
88+
clean_ipv6_address(addr, error_message=msg)
89+
exception_traceback = StringIO()
90+
traceback.print_exception(ctx.exception, file=exception_traceback)
91+
self.assertIn(value_error_msg % addr, exception_traceback.getvalue())

0 commit comments

Comments
 (0)
0