Skip to content

Commit aeefb63

Browse files
picnixzhartwork
authored andcommitted
[3.12] pythongh-90949: add Expat API to prevent XML deadly allocations (CVE-2025-59375) (pythonGH-139234)
Expose the XML Expat 2.7.2 mitigation APIs to disallow use of disproportional amounts of dynamic memory from within an Expat parser (see CVE-2025-59375 for instance). The exposed APIs are available on Expat parsers, that is, parsers created by `xml.parsers.expat.ParserCreate()`, as: - `parser.SetAllocTrackerActivationThreshold(threshold)`, and - `parser.SetAllocTrackerMaximumAmplification(max_factor)`. (cherry picked from commit f04bea4) Co-authored-by: Bénédikt Tran <[email protected]>
1 parent ade85bc commit aeefb63

File tree

7 files changed

+567
-29
lines changed

7 files changed

+567
-29
lines changed

Doc/library/pyexpat.rst

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,13 @@ The :mod:`xml.parsers.expat` module contains two functions:
7373
*encoding* [1]_ is given it will override the implicit or explicit encoding of the
7474
document.
7575

76+
.. _xmlparser-non-root:
77+
78+
Parsers created through :func:`!ParserCreate` are called "root" parsers,
79+
in the sense that they do not have any parent parser attached. Non-root
80+
parsers are created by :meth:`parser.ExternalEntityParserCreate
81+
<xmlparser.ExternalEntityParserCreate>`.
82+
7683
Expat can optionally do XML namespace processing for you, enabled by providing a
7784
value for *namespace_separator*. The value must be a one-character string; a
7885
:exc:`ValueError` will be raised if the string has an illegal length (``None``
@@ -232,6 +239,55 @@ XMLParser Objects
232239
.. versionadded:: 3.12.3
233240

234241

242+
:class:`!xmlparser` objects have the following methods to mitigate some
243+
common XML vulnerabilities.
244+
245+
.. method:: xmlparser.SetAllocTrackerActivationThreshold(threshold, /)
246+
247+
Sets the number of allocated bytes of dynamic memory needed to activate
248+
protection against disproportionate use of RAM.
249+
250+
By default, parser objects have an allocation activation threshold of 64 MiB,
251+
or equivalently 67,108,864 bytes.
252+
253+
An :exc:`ExpatError` is raised if this method is called on a
254+
|xml-non-root-parser| parser.
255+
The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset`
256+
should not be used as they may have no special meaning.
257+
258+
.. versionadded:: next
259+
260+
.. method:: xmlparser.SetAllocTrackerMaximumAmplification(max_factor, /)
261+
262+
Sets the maximum amplification factor between direct input and bytes
263+
of dynamic memory allocated.
264+
265+
The amplification factor is calculated as ``allocated / direct``
266+
while parsing, where ``direct`` is the number of bytes read from
267+
the primary document in parsing and ``allocated`` is the number
268+
of bytes of dynamic memory allocated in the parser hierarchy.
269+
270+
The *max_factor* value must be a non-NaN :class:`float` value greater than
271+
or equal to 1.0. Amplification factors greater than 100.0 can be observed
272+
near the start of parsing even with benign files in practice. In particular,
273+
the activation threshold should be carefully chosen to avoid false positives.
274+
275+
By default, parser objects have a maximum amplification factor of 100.0.
276+
277+
An :exc:`ExpatError` is raised if this method is called on a
278+
|xml-non-root-parser| parser or if *max_factor* is outside the valid range.
279+
The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset`
280+
should not be used as they may have no special meaning.
281+
282+
.. note::
283+
284+
The maximum amplification factor is only considered if the threshold
285+
that can be adjusted :meth:`.SetAllocTrackerActivationThreshold` is
286+
exceeded.
287+
288+
.. versionadded:: next
289+
290+
235291
:class:`xmlparser` objects have the following attributes:
236292

237293

@@ -948,3 +1004,4 @@ The ``errors`` module has the following attributes:
9481004
not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
9491005
and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
9501006
1007+
.. |xml-non-root-parser| replace:: :ref:`non-root <xmlparser-non-root>`

Include/pyexpat.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ struct PyExpat_CAPI
5252
int (*SetHashSalt)(XML_Parser parser, unsigned long hash_salt);
5353
/* might be NULL for expat < 2.6.0 */
5454
XML_Bool (*SetReparseDeferralEnabled)(XML_Parser parser, XML_Bool enabled);
55+
/* might be NULL for expat < 2.7.2 */
56+
XML_Bool (*SetAllocTrackerActivationThreshold)(
57+
XML_Parser parser, unsigned long long activationThresholdBytes);
58+
XML_Bool (*SetAllocTrackerMaximumAmplification)(
59+
XML_Parser parser, float maxAmplificationFactor);
5560
/* always add new stuff to the end! */
5661
};
5762

Lib/test/test_pyexpat.py

Lines changed: 199 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
# XXX TypeErrors on calling handlers, or on bad return values from a
22
# handler, are obscure and unhelpful.
33

4+
import abc
5+
import functools
46
import os
57
import platform
8+
import re
69
import sys
710
import sysconfig
11+
import textwrap
812
import unittest
913
import traceback
1014
from io import BytesIO
1115
from test import support
12-
from test.support import os_helper
16+
from test.support import import_helper, os_helper
1317

1418
from xml.parsers import expat
1519
from xml.parsers.expat import errors
@@ -812,5 +816,199 @@ def start_element(name, _):
812816
self.assertEqual(started, ['doc'])
813817

814818

819+
class AttackProtectionTestBase(abc.ABC):
820+
"""
821+
Base class for testing protections against XML payloads with
822+
disproportionate amplification.
823+
824+
The protections being tested should detect and prevent attacks
825+
that leverage disproportionate amplification from small inputs.
826+
"""
827+
828+
@staticmethod
829+
def exponential_expansion_payload(*, nrows, ncols, text='.'):
830+
"""Create a billion laughs attack payload.
831+
832+
Be careful: the number of total items is pow(n, k), thereby
833+
requiring at least pow(ncols, nrows) * sizeof(text) memory!
834+
"""
835+
template = textwrap.dedent(f"""\
836+
<?xml version="1.0"?>
837+
<!DOCTYPE doc [
838+
<!ENTITY row0 "{text}">
839+
<!ELEMENT doc (#PCDATA)>
840+
{{body}}
841+
]>
842+
<doc>&row{nrows};</doc>
843+
""").rstrip()
844+
845+
body = '\n'.join(
846+
f'<!ENTITY row{i + 1} "{f"&row{i};" * ncols}">'
847+
for i in range(nrows)
848+
)
849+
body = textwrap.indent(body, ' ' * 4)
850+
return template.format(body=body)
851+
852+
def test_payload_generation(self):
853+
# self-test for exponential_expansion_payload()
854+
payload = self.exponential_expansion_payload(nrows=2, ncols=3)
855+
self.assertEqual(payload, textwrap.dedent("""\
856+
<?xml version="1.0"?>
857+
<!DOCTYPE doc [
858+
<!ENTITY row0 ".">
859+
<!ELEMENT doc (#PCDATA)>
860+
<!ENTITY row1 "&row0;&row0;&row0;">
861+
<!ENTITY row2 "&row1;&row1;&row1;">
862+
]>
863+
<doc>&row2;</doc>
864+
""").rstrip())
865+
866+
def assert_root_parser_failure(self, func, /, *args, **kwargs):
867+
"""Check that func(*args, **kwargs) is invalid for a sub-parser."""
868+
msg = "parser must be a root parser"
869+
self.assertRaisesRegex(expat.ExpatError, msg, func, *args, **kwargs)
870+
871+
@abc.abstractmethod
872+
def assert_rejected(self, func, /, *args, **kwargs):
873+
"""Assert that func(*args, **kwargs) triggers the attack protection.
874+
875+
Note: this method must ensure that the attack protection being tested
876+
is the one that is actually triggered at runtime, e.g., by matching
877+
the exact error message.
878+
"""
879+
880+
@abc.abstractmethod
881+
def set_activation_threshold(self, parser, threshold):
882+
"""Set the activation threshold for the tested protection."""
883+
884+
@abc.abstractmethod
885+
def set_maximum_amplification(self, parser, max_factor):
886+
"""Set the maximum amplification factor for the tested protection."""
887+
888+
@abc.abstractmethod
889+
def test_set_activation_threshold__threshold_reached(self):
890+
"""Test when the activation threshold is exceeded."""
891+
892+
@abc.abstractmethod
893+
def test_set_activation_threshold__threshold_not_reached(self):
894+
"""Test when the activation threshold is not exceeded."""
895+
896+
def test_set_activation_threshold__invalid_threshold_type(self):
897+
parser = expat.ParserCreate()
898+
setter = functools.partial(self.set_activation_threshold, parser)
899+
900+
self.assertRaises(TypeError, setter, 1.0)
901+
self.assertRaises(TypeError, setter, -1.5)
902+
self.assertRaises(ValueError, setter, -5)
903+
904+
def test_set_activation_threshold__invalid_threshold_range(self):
905+
_testcapi = import_helper.import_module("_testcapi")
906+
parser = expat.ParserCreate()
907+
setter = functools.partial(self.set_activation_threshold, parser)
908+
909+
self.assertRaises(OverflowError, setter, _testcapi.ULLONG_MAX + 1)
910+
911+
def test_set_activation_threshold__fail_for_subparser(self):
912+
parser = expat.ParserCreate()
913+
subparser = parser.ExternalEntityParserCreate(None)
914+
setter = functools.partial(self.set_activation_threshold, subparser)
915+
self.assert_root_parser_failure(setter, 12345)
916+
917+
@abc.abstractmethod
918+
def test_set_maximum_amplification__amplification_exceeded(self):
919+
"""Test when the amplification factor is exceeded."""
920+
921+
@abc.abstractmethod
922+
def test_set_maximum_amplification__amplification_not_exceeded(self):
923+
"""Test when the amplification factor is not exceeded."""
924+
925+
def test_set_maximum_amplification__infinity(self):
926+
inf = float('inf') # an 'inf' threshold is allowed by Expat
927+
parser = expat.ParserCreate()
928+
self.assertIsNone(self.set_maximum_amplification(parser, inf))
929+
930+
def test_set_maximum_amplification__invalid_max_factor_type(self):
931+
parser = expat.ParserCreate()
932+
setter = functools.partial(self.set_maximum_amplification, parser)
933+
934+
self.assertRaises(TypeError, setter, None)
935+
self.assertRaises(TypeError, setter, 'abc')
936+
937+
def test_set_maximum_amplification__invalid_max_factor_range(self):
938+
parser = expat.ParserCreate()
939+
setter = functools.partial(self.set_maximum_amplification, parser)
940+
941+
msg = re.escape("'max_factor' must be at least 1.0")
942+
self.assertRaisesRegex(expat.ExpatError, msg, setter, float('nan'))
943+
self.assertRaisesRegex(expat.ExpatError, msg, setter, 0.99)
944+
945+
def test_set_maximum_amplification__fail_for_subparser(self):
946+
parser = expat.ParserCreate()
947+
subparser = parser.ExternalEntityParserCreate(None)
948+
setter = functools.partial(self.set_maximum_amplification, subparser)
949+
self.assert_root_parser_failure(setter, 123.45)
950+
951+
952+
@unittest.skipIf(expat.version_info < (2, 7, 2), "requires Expat >= 2.7.2")
953+
class MemoryProtectionTest(AttackProtectionTestBase, unittest.TestCase):
954+
955+
# NOTE: with the default Expat configuration, the billion laughs protection
956+
# may hit before the allocation limiter if exponential_expansion_payload()
957+
# is not carefully parametrized. As such, the payloads should be chosen so
958+
# that either the allocation limiter is hit before other protections are
959+
# triggered or no protection at all is triggered.
960+
961+
def assert_rejected(self, func, /, *args, **kwargs):
962+
"""Check that func(*args, **kwargs) hits the allocation limit."""
963+
msg = r"out of memory: line \d+, column \d+"
964+
self.assertRaisesRegex(expat.ExpatError, msg, func, *args, **kwargs)
965+
966+
def set_activation_threshold(self, parser, threshold):
967+
return parser.SetAllocTrackerActivationThreshold(threshold)
968+
969+
def set_maximum_amplification(self, parser, max_factor):
970+
return parser.SetAllocTrackerMaximumAmplification(max_factor)
971+
972+
def test_set_activation_threshold__threshold_reached(self):
973+
parser = expat.ParserCreate()
974+
# Choose a threshold expected to be always reached.
975+
self.set_activation_threshold(parser, 3)
976+
# Check that the threshold is reached by choosing a small factor
977+
# and a payload whose peak amplification factor exceeds it.
978+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
979+
payload = self.exponential_expansion_payload(ncols=10, nrows=4)
980+
self.assert_rejected(parser.Parse, payload, True)
981+
982+
def test_set_activation_threshold__threshold_not_reached(self):
983+
parser = expat.ParserCreate()
984+
# Choose a threshold expected to be never reached.
985+
self.set_activation_threshold(parser, pow(10, 5))
986+
# Check that the threshold is reached by choosing a small factor
987+
# and a payload whose peak amplification factor exceeds it.
988+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
989+
payload = self.exponential_expansion_payload(ncols=10, nrows=4)
990+
self.assertIsNotNone(parser.Parse(payload, True))
991+
992+
def test_set_maximum_amplification__amplification_exceeded(self):
993+
parser = expat.ParserCreate()
994+
# Unconditionally enable maximum activation factor.
995+
self.set_activation_threshold(parser, 0)
996+
# Choose a max amplification factor expected to always be exceeded.
997+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
998+
# Craft a payload for which the peak amplification factor is > 1.0.
999+
payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1000+
self.assert_rejected(parser.Parse, payload, True)
1001+
1002+
def test_set_maximum_amplification__amplification_not_exceeded(self):
1003+
parser = expat.ParserCreate()
1004+
# Unconditionally enable maximum activation factor.
1005+
self.set_activation_threshold(parser, 0)
1006+
# Choose a max amplification factor expected to never be exceeded.
1007+
self.assertIsNone(self.set_maximum_amplification(parser, 1e4))
1008+
# Craft a payload for which the peak amplification factor is < 1e4.
1009+
payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1010+
self.assertIsNotNone(parser.Parse(payload, True))
1011+
1012+
8151013
if __name__ == "__main__":
8161014
unittest.main()
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Add :func:`~xml.parsers.expat.xmlparser.SetAllocTrackerActivationThreshold`
2+
and :func:`~xml.parsers.expat.xmlparser.SetAllocTrackerMaximumAmplification`
3+
to :ref:`xmlparser <xmlparser-objects>` objects to prevent use of
4+
disproportional amounts of dynamic memory from within an Expat parser.
5+
Patch by Bénédikt Tran.

0 commit comments

Comments
 (0)