CVE-2024-56374
Description
An issue was discovered in Django 5.1 before 5.1.5, 5.0 before 5.0.11, and 4.2 before 4.2.18. Lack of upper-bound limit enforcement in strings passed when performing IPv6 validation could lead to a potential denial-of-service attack. The undocumented and private functions clean_ipv6_address and is_valid_ipv6_address are vulnerable, as is the django.forms.GenericIPAddressField form field. (The django.db.models.GenericIPAddressField model field is not affected.)
Affected packages
Versions sourced from the GitHub Security Advisory.
| Package | Affected versions | Patched versions |
|---|---|---|
DjangoPyPI | >= 5.1, < 5.1.5 | 5.1.5 |
DjangoPyPI | >= 5.0, < 5.0.11 | 5.0.11 |
DjangoPyPI | >= 4.2, < 4.2.18 | 4.2.18 |
djangoPyPI | >= 5.1, < 5.1.5 | 5.1.5 |
djangoPyPI | >= 5.0, < 5.0.11 | 5.0.11 |
djangoPyPI | >= 4.2, < 4.2.18 | 4.2.18 |
Affected products
1- Range: 4.2
Patches
4e8d4a2005955[5.0.x] Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation.
8 files changed · +119 −14
django/db/models/fields/__init__.py+3 −3 modified@@ -30,7 +30,7 @@ ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ @@ -2220,7 +2220,7 @@ def __init__( invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message - kwargs["max_length"] = 39 + kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): @@ -2247,7 +2247,7 @@ def deconstruct(self): kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol - if kwargs.get("max_length") == 39: + if kwargs.get("max_length") == self.max_length: del kwargs["max_length"] return name, path, args, kwargs
django/forms/fields.py+5 −2 modified@@ -46,7 +46,7 @@ from django.utils.dateparse import parse_datetime, parse_duration from django.utils.deprecation import RemovedInDjango60Warning from django.utils.duration import duration_string -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy @@ -1295,14 +1295,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 )[0] + kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH) super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: - return clean_ipv6_address(value, self.unpack_ipv4) + return clean_ipv6_address( + value, self.unpack_ipv4, max_length=self.max_length + ) return value
django/utils/ipv6.py+16 −3 modified@@ -3,9 +3,22 @@ from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ +MAX_IPV6_ADDRESS_LENGTH = 39 + + +def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH): + if len(ip_str) > max_length: + raise ValueError( + f"Unable to convert {ip_str} to an IPv6 address (value too long)." + ) + return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + def clean_ipv6_address( - ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.") + ip_str, + unpack_ipv4=False, + error_message=_("This is not a valid IPv6 address."), + max_length=MAX_IPV6_ADDRESS_LENGTH, ): """ Clean an IPv6 address string. @@ -24,7 +37,7 @@ def clean_ipv6_address( Return a compressed IPv6 address or the same value. """ try: - addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + addr = _ipv6_address_from_str(ip_str, max_length) except ValueError: raise ValidationError(error_message, code="invalid") @@ -41,7 +54,7 @@ def is_valid_ipv6_address(ip_str): Return whether or not the `ip_str` string is a valid IPv6 address. """ try: - ipaddress.IPv6Address(ip_str) + _ipv6_address_from_str(ip_str) except ValueError: return False return True
docs/ref/forms/fields.txt+11 −2 modified@@ -774,15 +774,15 @@ For each field, we describe the default widget used if you don't specify * Empty value: ``''`` (an empty string) * Normalizes to: A string. IPv6 addresses are normalized as described below. * Validates that the given value is a valid IP address. - * Error message keys: ``required``, ``invalid`` + * Error message keys: ``required``, ``invalid``, ``max_length`` The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters are converted to lowercase. - Takes two optional arguments: + Takes three optional arguments: .. attribute:: protocol @@ -797,6 +797,15 @@ For each field, we describe the default widget used if you don't specify ``192.0.2.1``. Default is disabled. Can only be used when ``protocol`` is set to ``'both'``. + .. attribute:: max_length + + Defaults to 39, and behaves the same way as it does for + :class:`CharField`. + + .. versionchanged:: 4.2.18 + + The default value for ``max_length`` was set to 39 characters. + ``ImageField`` --------------
docs/releases/4.2.18.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 4.2.18 release notes *January 14, 2025* Django 4.2.18 fixes a security issue with severity "moderate" in 4.2.17. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
docs/releases/5.0.11.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 5.0.11 release notes *January 14, 2025* Django 5.0.11 fixes a security issue with severity "moderate" in 5.0.10. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
tests/forms_tests/field_tests/test_genericipaddressfield.py+32 −1 modified@@ -1,6 +1,7 @@ from django.core.exceptions import ValidationError from django.forms import GenericIPAddressField from django.test import SimpleTestCase +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH class GenericIPAddressFieldTest(SimpleTestCase): @@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self): ): f.clean("1:2") + def test_generic_ipaddress_max_length_custom(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + f = GenericIPAddressField(max_length=len(addr)) + f.clean(addr) + + def test_generic_ipaddress_max_length_validation_error(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + + cases = [ + ({}, MAX_IPV6_ADDRESS_LENGTH), # Default value. + ({"max_length": len(addr) - 1}, len(addr) - 1), + ] + for kwargs, max_length in cases: + max_length_plus_one = max_length + 1 + msg = ( + f"Ensure this value has at most {max_length} characters (it has " + f"{max_length_plus_one}).'" + ) + with self.subTest(max_length=max_length): + f = GenericIPAddressField(**kwargs) + with self.assertRaisesMessage(ValidationError, msg): + f.clean("x" * max_length_plus_one) + with self.assertRaisesMessage( + ValidationError, "This is not a valid IPv6 address." + ): + f.clean(addr) + def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(""), "") @@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self): f.clean(" fe80::223:6cff:fe8a:2e8a "), "fe80::223:6cff:fe8a:2e8a" ) self.assertEqual( - f.clean(" 2a02::223:6cff:fe8a:2e8a "), "2a02::223:6cff:fe8a:2e8a" + f.clean(" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a "), + "2a02::223:6cff:fe8a:2e8a", ) with self.assertRaisesMessage( ValidationError, "'This is not a valid IPv6 address.'"
tests/utils_tests/test_ipv6.py+28 −3 modified@@ -1,9 +1,16 @@ -import unittest +import traceback +from io import StringIO -from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address +from django.core.exceptions import ValidationError +from django.test import SimpleTestCase +from django.utils.ipv6 import ( + MAX_IPV6_ADDRESS_LENGTH, + clean_ipv6_address, + is_valid_ipv6_address, +) -class TestUtilsIPv6(unittest.TestCase): +class TestUtilsIPv6(SimpleTestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) @@ -64,3 +71,21 @@ def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" ) + + def test_address_too_long(self): + addresses = [ + "0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address + "0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone + "fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1 + ] + msg = "This is the error message." + value_error_msg = "Unable to convert %s to an IPv6 address (value too long)." + for addr in addresses: + with self.subTest(addr=addr): + self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH) + self.assertEqual(is_valid_ipv6_address(addr), False) + with self.assertRaisesMessage(ValidationError, msg) as ctx: + clean_ipv6_address(addr, error_message=msg) + exception_traceback = StringIO() + traceback.print_exception(ctx.exception, file=exception_traceback) + self.assertIn(value_error_msg % addr, exception_traceback.getvalue())
ad866a1ca3e7[4.2.x] Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation.
7 files changed · +116 −14
django/db/models/fields/__init__.py+3 −3 modified@@ -25,7 +25,7 @@ ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ @@ -2160,7 +2160,7 @@ def __init__( invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message - kwargs["max_length"] = 39 + kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): @@ -2187,7 +2187,7 @@ def deconstruct(self): kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol - if kwargs.get("max_length") == 39: + if kwargs.get("max_length") == self.max_length: del kwargs["max_length"] return name, path, args, kwargs
django/forms/fields.py+5 −2 modified@@ -42,7 +42,7 @@ from django.utils import formats from django.utils.dateparse import parse_datetime, parse_duration from django.utils.duration import duration_string -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy @@ -1284,14 +1284,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 )[0] + kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH) super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: - return clean_ipv6_address(value, self.unpack_ipv4) + return clean_ipv6_address( + value, self.unpack_ipv4, max_length=self.max_length + ) return value
django/utils/ipv6.py+16 −3 modified@@ -3,9 +3,22 @@ from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ +MAX_IPV6_ADDRESS_LENGTH = 39 + + +def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH): + if len(ip_str) > max_length: + raise ValueError( + f"Unable to convert {ip_str} to an IPv6 address (value too long)." + ) + return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + def clean_ipv6_address( - ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.") + ip_str, + unpack_ipv4=False, + error_message=_("This is not a valid IPv6 address."), + max_length=MAX_IPV6_ADDRESS_LENGTH, ): """ Clean an IPv6 address string. @@ -24,7 +37,7 @@ def clean_ipv6_address( Return a compressed IPv6 address or the same value. """ try: - addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + addr = _ipv6_address_from_str(ip_str, max_length) except ValueError: raise ValidationError(error_message, code="invalid") @@ -41,7 +54,7 @@ def is_valid_ipv6_address(ip_str): Return whether or not the `ip_str` string is a valid IPv6 address. """ try: - ipaddress.IPv6Address(ip_str) + _ipv6_address_from_str(ip_str) except ValueError: return False return True
docs/ref/forms/fields.txt+11 −2 modified@@ -719,15 +719,15 @@ For each field, we describe the default widget used if you don't specify * Empty value: ``''`` (an empty string) * Normalizes to: A string. IPv6 addresses are normalized as described below. * Validates that the given value is a valid IP address. - * Error message keys: ``required``, ``invalid`` + * Error message keys: ``required``, ``invalid``, ``max_length`` The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters are converted to lowercase. - Takes two optional arguments: + Takes three optional arguments: .. attribute:: protocol @@ -742,6 +742,15 @@ For each field, we describe the default widget used if you don't specify ``192.0.2.1``. Default is disabled. Can only be used when ``protocol`` is set to ``'both'``. + .. attribute:: max_length + + Defaults to 39, and behaves the same way as it does for + :class:`CharField`. + + .. versionchanged:: 4.2.18 + + The default value for ``max_length`` was set to 39 characters. + ``ImageField`` --------------
docs/releases/4.2.18.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 4.2.18 release notes *January 14, 2025* Django 4.2.18 fixes a security issue with severity "moderate" in 4.2.17. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
tests/forms_tests/field_tests/test_genericipaddressfield.py+32 −1 modified@@ -1,6 +1,7 @@ from django.core.exceptions import ValidationError from django.forms import GenericIPAddressField from django.test import SimpleTestCase +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH class GenericIPAddressFieldTest(SimpleTestCase): @@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self): ): f.clean("1:2") + def test_generic_ipaddress_max_length_custom(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + f = GenericIPAddressField(max_length=len(addr)) + f.clean(addr) + + def test_generic_ipaddress_max_length_validation_error(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + + cases = [ + ({}, MAX_IPV6_ADDRESS_LENGTH), # Default value. + ({"max_length": len(addr) - 1}, len(addr) - 1), + ] + for kwargs, max_length in cases: + max_length_plus_one = max_length + 1 + msg = ( + f"Ensure this value has at most {max_length} characters (it has " + f"{max_length_plus_one}).'" + ) + with self.subTest(max_length=max_length): + f = GenericIPAddressField(**kwargs) + with self.assertRaisesMessage(ValidationError, msg): + f.clean("x" * max_length_plus_one) + with self.assertRaisesMessage( + ValidationError, "This is not a valid IPv6 address." + ): + f.clean(addr) + def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(""), "") @@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self): f.clean(" fe80::223:6cff:fe8a:2e8a "), "fe80::223:6cff:fe8a:2e8a" ) self.assertEqual( - f.clean(" 2a02::223:6cff:fe8a:2e8a "), "2a02::223:6cff:fe8a:2e8a" + f.clean(" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a "), + "2a02::223:6cff:fe8a:2e8a", ) with self.assertRaisesMessage( ValidationError, "'This is not a valid IPv6 address.'"
tests/utils_tests/test_ipv6.py+37 −3 modified@@ -1,9 +1,17 @@ -import unittest +import traceback +from io import StringIO -from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address +from django.core.exceptions import ValidationError +from django.test import SimpleTestCase +from django.utils.ipv6 import ( + MAX_IPV6_ADDRESS_LENGTH, + clean_ipv6_address, + is_valid_ipv6_address, +) +from django.utils.version import PY310 -class TestUtilsIPv6(unittest.TestCase): +class TestUtilsIPv6(SimpleTestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) @@ -64,3 +72,29 @@ def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" ) + + def test_address_too_long(self): + addresses = [ + "0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address + "0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone + "fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1 + ] + msg = "This is the error message." + value_error_msg = "Unable to convert %s to an IPv6 address (value too long)." + for addr in addresses: + with self.subTest(addr=addr): + self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH) + self.assertEqual(is_valid_ipv6_address(addr), False) + with self.assertRaisesMessage(ValidationError, msg) as ctx: + clean_ipv6_address(addr, error_message=msg) + exception_traceback = StringIO() + if PY310: + traceback.print_exception(ctx.exception, file=exception_traceback) + else: + traceback.print_exception( + type(ctx.exception), + value=ctx.exception, + tb=ctx.exception.__traceback__, + file=exception_traceback, + ) + self.assertIn(value_error_msg % addr, exception_traceback.getvalue())
ca2be7724e12Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation.
9 files changed · +131 −14
django/db/models/fields/__init__.py+3 −3 modified@@ -32,7 +32,7 @@ ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ @@ -2233,7 +2233,7 @@ def __init__( self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 ) - kwargs["max_length"] = 39 + kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): @@ -2260,7 +2260,7 @@ def deconstruct(self): kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol - if kwargs.get("max_length") == 39: + if kwargs.get("max_length") == self.max_length: del kwargs["max_length"] return name, path, args, kwargs
django/forms/fields.py+5 −2 modified@@ -46,7 +46,7 @@ from django.utils.dateparse import parse_datetime, parse_duration from django.utils.deprecation import RemovedInDjango60Warning from django.utils.duration import duration_string -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy @@ -1303,14 +1303,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 ) + kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH) super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: - return clean_ipv6_address(value, self.unpack_ipv4) + return clean_ipv6_address( + value, self.unpack_ipv4, max_length=self.max_length + ) return value
django/utils/ipv6.py+16 −3 modified@@ -3,9 +3,22 @@ from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ +MAX_IPV6_ADDRESS_LENGTH = 39 + + +def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH): + if len(ip_str) > max_length: + raise ValueError( + f"Unable to convert {ip_str} to an IPv6 address (value too long)." + ) + return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + def clean_ipv6_address( - ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.") + ip_str, + unpack_ipv4=False, + error_message=_("This is not a valid IPv6 address."), + max_length=MAX_IPV6_ADDRESS_LENGTH, ): """ Clean an IPv6 address string. @@ -24,7 +37,7 @@ def clean_ipv6_address( Return a compressed IPv6 address or the same value. """ try: - addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + addr = _ipv6_address_from_str(ip_str, max_length) except ValueError: raise ValidationError( error_message, code="invalid", params={"protocol": _("IPv6")} @@ -43,7 +56,7 @@ def is_valid_ipv6_address(ip_str): Return whether or not the `ip_str` string is a valid IPv6 address. """ try: - ipaddress.IPv6Address(ip_str) + _ipv6_address_from_str(ip_str) except ValueError: return False return True
docs/ref/forms/fields.txt+11 −2 modified@@ -761,15 +761,15 @@ For each field, we describe the default widget used if you don't specify * Empty value: ``''`` (an empty string) * Normalizes to: A string. IPv6 addresses are normalized as described below. * Validates that the given value is a valid IP address. - * Error message keys: ``required``, ``invalid`` + * Error message keys: ``required``, ``invalid``, ``max_length`` The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters are converted to lowercase. - Takes two optional arguments: + Takes three optional arguments: .. attribute:: protocol @@ -784,6 +784,15 @@ For each field, we describe the default widget used if you don't specify ``192.0.2.1``. Default is disabled. Can only be used when ``protocol`` is set to ``'both'``. + .. attribute:: max_length + + Defaults to 39, and behaves the same way as it does for + :class:`CharField`. + + .. versionchanged:: 4.2.18 + + The default value for ``max_length`` was set to 39 characters. + ``ImageField`` --------------
docs/releases/4.2.18.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 4.2.18 release notes *January 14, 2025* Django 4.2.18 fixes a security issue with severity "moderate" in 4.2.17. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
docs/releases/5.0.11.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 5.0.11 release notes *January 14, 2025* Django 5.0.11 fixes a security issue with severity "moderate" in 5.0.10. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
docs/releases/5.1.5.txt+12 −0 modified@@ -7,6 +7,18 @@ Django 5.1.5 release notes Django 5.1.5 fixes a security issue with severity "moderate" and one bug in 5.1.4. +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected. + Bugfixes ========
tests/forms_tests/field_tests/test_genericipaddressfield.py+32 −1 modified@@ -1,6 +1,7 @@ from django.core.exceptions import ValidationError from django.forms import GenericIPAddressField from django.test import SimpleTestCase +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH class GenericIPAddressFieldTest(SimpleTestCase): @@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self): ): f.clean("1:2") + def test_generic_ipaddress_max_length_custom(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + f = GenericIPAddressField(max_length=len(addr)) + f.clean(addr) + + def test_generic_ipaddress_max_length_validation_error(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + + cases = [ + ({}, MAX_IPV6_ADDRESS_LENGTH), # Default value. + ({"max_length": len(addr) - 1}, len(addr) - 1), + ] + for kwargs, max_length in cases: + max_length_plus_one = max_length + 1 + msg = ( + f"Ensure this value has at most {max_length} characters (it has " + f"{max_length_plus_one}).'" + ) + with self.subTest(max_length=max_length): + f = GenericIPAddressField(**kwargs) + with self.assertRaisesMessage(ValidationError, msg): + f.clean("x" * max_length_plus_one) + with self.assertRaisesMessage( + ValidationError, "This is not a valid IPv6 address." + ): + f.clean(addr) + def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(""), "") @@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self): f.clean(" fe80::223:6cff:fe8a:2e8a "), "fe80::223:6cff:fe8a:2e8a" ) self.assertEqual( - f.clean(" 2a02::223:6cff:fe8a:2e8a "), "2a02::223:6cff:fe8a:2e8a" + f.clean(" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a "), + "2a02::223:6cff:fe8a:2e8a", ) with self.assertRaisesMessage( ValidationError, "'This is not a valid IPv6 address.'"
tests/utils_tests/test_ipv6.py+28 −3 modified@@ -1,9 +1,16 @@ -import unittest +import traceback +from io import StringIO -from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address +from django.core.exceptions import ValidationError +from django.test import SimpleTestCase +from django.utils.ipv6 import ( + MAX_IPV6_ADDRESS_LENGTH, + clean_ipv6_address, + is_valid_ipv6_address, +) -class TestUtilsIPv6(unittest.TestCase): +class TestUtilsIPv6(SimpleTestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) @@ -64,3 +71,21 @@ def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" ) + + def test_address_too_long(self): + addresses = [ + "0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address + "0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone + "fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1 + ] + msg = "This is the error message." + value_error_msg = "Unable to convert %s to an IPv6 address (value too long)." + for addr in addresses: + with self.subTest(addr=addr): + self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH) + self.assertEqual(is_valid_ipv6_address(addr), False) + with self.assertRaisesMessage(ValidationError, msg) as ctx: + clean_ipv6_address(addr, error_message=msg) + exception_traceback = StringIO() + traceback.print_exception(ctx.exception, file=exception_traceback) + self.assertIn(value_error_msg % addr, exception_traceback.getvalue())
4806731e58f3[5.1.x] Fixed CVE-2024-56374 -- Mitigated potential DoS in IPv6 validation.
9 files changed · +131 −14
django/db/models/fields/__init__.py+3 −3 modified@@ -32,7 +32,7 @@ ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ @@ -2228,7 +2228,7 @@ def __init__( self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 ) - kwargs["max_length"] = 39 + kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): @@ -2255,7 +2255,7 @@ def deconstruct(self): kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol - if kwargs.get("max_length") == 39: + if kwargs.get("max_length") == self.max_length: del kwargs["max_length"] return name, path, args, kwargs
django/forms/fields.py+5 −2 modified@@ -46,7 +46,7 @@ from django.utils.dateparse import parse_datetime, parse_duration from django.utils.deprecation import RemovedInDjango60Warning from django.utils.duration import duration_string -from django.utils.ipv6 import clean_ipv6_address +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy @@ -1303,14 +1303,17 @@ def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 ) + kwargs.setdefault("max_length", MAX_IPV6_ADDRESS_LENGTH) super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: - return clean_ipv6_address(value, self.unpack_ipv4) + return clean_ipv6_address( + value, self.unpack_ipv4, max_length=self.max_length + ) return value
django/utils/ipv6.py+16 −3 modified@@ -3,9 +3,22 @@ from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ +MAX_IPV6_ADDRESS_LENGTH = 39 + + +def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH): + if len(ip_str) > max_length: + raise ValueError( + f"Unable to convert {ip_str} to an IPv6 address (value too long)." + ) + return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + def clean_ipv6_address( - ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.") + ip_str, + unpack_ipv4=False, + error_message=_("This is not a valid IPv6 address."), + max_length=MAX_IPV6_ADDRESS_LENGTH, ): """ Clean an IPv6 address string. @@ -24,7 +37,7 @@ def clean_ipv6_address( Return a compressed IPv6 address or the same value. """ try: - addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) + addr = _ipv6_address_from_str(ip_str, max_length) except ValueError: raise ValidationError( error_message, code="invalid", params={"protocol": _("IPv6")} @@ -43,7 +56,7 @@ def is_valid_ipv6_address(ip_str): Return whether or not the `ip_str` string is a valid IPv6 address. """ try: - ipaddress.IPv6Address(ip_str) + _ipv6_address_from_str(ip_str) except ValueError: return False return True
docs/ref/forms/fields.txt+11 −2 modified@@ -773,15 +773,15 @@ For each field, we describe the default widget used if you don't specify * Empty value: ``''`` (an empty string) * Normalizes to: A string. IPv6 addresses are normalized as described below. * Validates that the given value is a valid IP address. - * Error message keys: ``required``, ``invalid`` + * Error message keys: ``required``, ``invalid``, ``max_length`` The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, including using the IPv4 format suggested in paragraph 3 of that section, like ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters are converted to lowercase. - Takes two optional arguments: + Takes three optional arguments: .. attribute:: protocol @@ -796,6 +796,15 @@ For each field, we describe the default widget used if you don't specify ``192.0.2.1``. Default is disabled. Can only be used when ``protocol`` is set to ``'both'``. + .. attribute:: max_length + + Defaults to 39, and behaves the same way as it does for + :class:`CharField`. + + .. versionchanged:: 4.2.18 + + The default value for ``max_length`` was set to 39 characters. + ``ImageField`` --------------
docs/releases/4.2.18.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 4.2.18 release notes *January 14, 2025* Django 4.2.18 fixes a security issue with severity "moderate" in 4.2.17. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
docs/releases/5.0.11.txt+12 −0 modified@@ -5,3 +5,15 @@ Django 5.0.11 release notes *January 14, 2025* Django 5.0.11 fixes a security issue with severity "moderate" in 5.0.10. + +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected.
docs/releases/5.1.5.txt+12 −0 modified@@ -7,6 +7,18 @@ Django 5.1.5 release notes Django 5.1.5 fixes a security issue with severity "moderate" and one bug in 5.1.4. +CVE-2024-56374: Potential denial-of-service vulnerability in IPv6 validation +============================================================================ + +Lack of upper bound limit enforcement in strings passed when performing IPv6 +validation could lead to a potential denial-of-service attack. The undocumented +and private functions ``clean_ipv6_address`` and ``is_valid_ipv6_address`` were +vulnerable, as was the :class:`django.forms.GenericIPAddressField` form field, +which has now been updated to define a ``max_length`` of 39 characters. + +The :class:`django.db.models.GenericIPAddressField` model field was not +affected. + Bugfixes ========
tests/forms_tests/field_tests/test_genericipaddressfield.py+32 −1 modified@@ -1,6 +1,7 @@ from django.core.exceptions import ValidationError from django.forms import GenericIPAddressField from django.test import SimpleTestCase +from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH class GenericIPAddressFieldTest(SimpleTestCase): @@ -125,6 +126,35 @@ def test_generic_ipaddress_as_ipv6_only(self): ): f.clean("1:2") + def test_generic_ipaddress_max_length_custom(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + f = GenericIPAddressField(max_length=len(addr)) + f.clean(addr) + + def test_generic_ipaddress_max_length_validation_error(self): + # Valid IPv4-mapped IPv6 address, len 45. + addr = "0000:0000:0000:0000:0000:ffff:192.168.100.228" + + cases = [ + ({}, MAX_IPV6_ADDRESS_LENGTH), # Default value. + ({"max_length": len(addr) - 1}, len(addr) - 1), + ] + for kwargs, max_length in cases: + max_length_plus_one = max_length + 1 + msg = ( + f"Ensure this value has at most {max_length} characters (it has " + f"{max_length_plus_one}).'" + ) + with self.subTest(max_length=max_length): + f = GenericIPAddressField(**kwargs) + with self.assertRaisesMessage(ValidationError, msg): + f.clean("x" * max_length_plus_one) + with self.assertRaisesMessage( + ValidationError, "This is not a valid IPv6 address." + ): + f.clean(addr) + def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(""), "") @@ -150,7 +180,8 @@ def test_generic_ipaddress_as_generic_not_required(self): f.clean(" fe80::223:6cff:fe8a:2e8a "), "fe80::223:6cff:fe8a:2e8a" ) self.assertEqual( - f.clean(" 2a02::223:6cff:fe8a:2e8a "), "2a02::223:6cff:fe8a:2e8a" + f.clean(" " * MAX_IPV6_ADDRESS_LENGTH + " 2a02::223:6cff:fe8a:2e8a "), + "2a02::223:6cff:fe8a:2e8a", ) with self.assertRaisesMessage( ValidationError, "'This is not a valid IPv6 address.'"
tests/utils_tests/test_ipv6.py+28 −3 modified@@ -1,9 +1,16 @@ -import unittest +import traceback +from io import StringIO -from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address +from django.core.exceptions import ValidationError +from django.test import SimpleTestCase +from django.utils.ipv6 import ( + MAX_IPV6_ADDRESS_LENGTH, + clean_ipv6_address, + is_valid_ipv6_address, +) -class TestUtilsIPv6(unittest.TestCase): +class TestUtilsIPv6(SimpleTestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address("fe80::223:6cff:fe8a:2e8a")) self.assertTrue(is_valid_ipv6_address("2a02::223:6cff:fe8a:2e8a")) @@ -64,3 +71,21 @@ def test_unpacks_ipv4(self): self.assertEqual( clean_ipv6_address("::ffff:18.52.18.52", unpack_ipv4=True), "18.52.18.52" ) + + def test_address_too_long(self): + addresses = [ + "0000:0000:0000:0000:0000:ffff:192.168.100.228", # IPv4-mapped IPv6 address + "0000:0000:0000:0000:0000:ffff:192.168.100.228%123456", # % scope/zone + "fe80::223:6cff:fe8a:2e8a:1234:5678:00000", # MAX_IPV6_ADDRESS_LENGTH + 1 + ] + msg = "This is the error message." + value_error_msg = "Unable to convert %s to an IPv6 address (value too long)." + for addr in addresses: + with self.subTest(addr=addr): + self.assertGreater(len(addr), MAX_IPV6_ADDRESS_LENGTH) + self.assertEqual(is_valid_ipv6_address(addr), False) + with self.assertRaisesMessage(ValidationError, msg) as ctx: + clean_ipv6_address(addr, error_message=msg) + exception_traceback = StringIO() + traceback.print_exception(ctx.exception, file=exception_traceback) + self.assertIn(value_error_msg % addr, exception_traceback.getvalue())
Vulnerability mechanics
Generated by null/stub on May 9, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.
References
14- github.com/advisories/GHSA-qcgg-j2x8-h9g8ghsaADVISORY
- nvd.nist.gov/vuln/detail/CVE-2024-56374ghsaADVISORY
- www.openwall.com/lists/oss-security/2025/01/14/2ghsaWEB
- docs.djangoproject.com/en/dev/releases/securityghsaWEB
- github.com/django/django/commit/4806731e58f3e8700a3c802e77899d54ac6021feghsaWEB
- github.com/django/django/commit/ad866a1ca3e7d60da888d25d27e46a8adb2ed36eghsaWEB
- github.com/django/django/commit/ca2be7724e1244a4cb723de40a070f873c6e94bfghsaWEB
- github.com/django/django/commit/e8d4a2005955dcf962193600b53bf461b190b455ghsaWEB
- github.com/pypa/advisory-database/tree/main/vulns/django/PYSEC-2025-1.yamlghsaWEB
- groups.google.com/g/django-announceghsaWEB
- lists.debian.org/debian-lts-announce/2025/01/msg00024.htmlghsaWEB
- www.djangoproject.com/weblog/2025/jan/14/security-releasesghsaWEB
- docs.djangoproject.com/en/dev/releases/security/mitre
- www.djangoproject.com/weblog/2025/jan/14/security-releases/mitre
News mentions
0No linked articles in our index yet.