Skip to content

Commit ed5f55e

Browse files
[3.12] gh-90949: expose Expat API to tune exponential expansion protections (GH-139368)
Expose the XML Expat 2.7.2 APIs to tune protections against "billion laughs" [1] attacks. The exposed APIs are available on Expat parsers, that is, parsers created by `xml.parsers.expat.ParserCreate()`, as: - `parser.SetBillionLaughsAttackProtectionActivationThreshold(threshold)`, and - `parser.SetBillionLaughsAttackProtectionMaximumAmplification(max_factor)`. This completes the work in f04bea4, and improves the existing related documentation. [1]: https://en.wikipedia.org/wiki/Billion_laughs_attack (cherry picked from commit 6661123) (cherry picked from commit 19bc391) Co-authored-by: Stan Ulbrych <stan@python.org> Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 7c999be commit ed5f55e

6 files changed

Lines changed: 364 additions & 13 deletions

File tree

Doc/library/pyexpat.rst

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -239,16 +239,71 @@ XMLParser Objects
239239
.. versionadded:: 3.12.3
240240

241241

242-
:class:`!xmlparser` objects have the following methods to mitigate some
243-
common XML vulnerabilities.
242+
:class:`!xmlparser` objects have the following methods to tune protections
243+
against some common XML vulnerabilities.
244+
245+
.. method:: xmlparser.SetBillionLaughsAttackProtectionActivationThreshold(threshold, /)
246+
247+
Sets the number of output bytes needed to activate protection against
248+
`billion laughs`_ attacks.
249+
250+
The number of output bytes includes amplification from entity expansion
251+
and reading DTD files.
252+
253+
Parser objects usually have a protection activation threshold of 8 MiB,
254+
but the actual default value depends on the underlying Expat library.
255+
256+
An :exc:`ExpatError` is raised if this method is called on a
257+
|xml-non-root-parser| parser.
258+
The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset`
259+
should not be used as they may have no special meaning.
260+
261+
.. note::
262+
263+
Activation thresholds below 4 MiB are known to break support for DITA 1.3
264+
payload and are hence not recommended.
265+
266+
.. versionadded:: next
267+
268+
.. method:: xmlparser.SetBillionLaughsAttackProtectionMaximumAmplification(max_factor, /)
269+
270+
Sets the maximum tolerated amplification factor for protection against
271+
`billion laughs`_ attacks.
272+
273+
The amplification factor is calculated as ``(direct + indirect) / direct``
274+
while parsing, where ``direct`` is the number of bytes read from
275+
the primary document in parsing and ``indirect`` is the number of
276+
bytes added by expanding entities and reading of external DTD files.
277+
278+
The *max_factor* value must be a non-NaN :class:`float` value greater than
279+
or equal to 1.0. Peak amplifications of factor 15,000 for the entire payload
280+
and of factor 30,000 in the middle of parsing have been observed with small
281+
benign files in practice. In particular, the activation threshold should be
282+
carefully chosen to avoid false positives.
283+
284+
Parser objects usually have a maximum amplification factor of 100,
285+
but the actual default value depends on the underlying Expat library.
286+
287+
An :exc:`ExpatError` is raised if this method is called on a
288+
|xml-non-root-parser| parser or if *max_factor* is outside the valid range.
289+
The corresponding :attr:`~ExpatError.lineno` and :attr:`~ExpatError.offset`
290+
should not be used as they may have no special meaning.
291+
292+
.. note::
293+
294+
The maximum amplification factor is only considered if the threshold
295+
that can be adjusted by :meth:`.SetBillionLaughsAttackProtectionActivationThreshold`
296+
is exceeded.
297+
298+
.. versionadded:: next
244299

245300
.. method:: xmlparser.SetAllocTrackerActivationThreshold(threshold, /)
246301

247302
Sets the number of allocated bytes of dynamic memory needed to activate
248303
protection against disproportionate use of RAM.
249304

250-
By default, parser objects have an allocation activation threshold of 64 MiB,
251-
or equivalently 67,108,864 bytes.
305+
Parser objects usually have an allocation activation threshold of 64 MiB,
306+
but the actual default value depends on the underlying Expat library.
252307

253308
An :exc:`ExpatError` is raised if this method is called on a
254309
|xml-non-root-parser| parser.
@@ -272,7 +327,8 @@ common XML vulnerabilities.
272327
near the start of parsing even with benign files in practice. In particular,
273328
the activation threshold should be carefully chosen to avoid false positives.
274329

275-
By default, parser objects have a maximum amplification factor of 100.0.
330+
Parser objects usually have a maximum amplification factor of 100,
331+
but the actual default value depends on the underlying Expat library.
276332

277333
An :exc:`ExpatError` is raised if this method is called on a
278334
|xml-non-root-parser| parser or if *max_factor* is outside the valid range.
@@ -1004,4 +1060,6 @@ The ``errors`` module has the following attributes:
10041060
not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
10051061
and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
10061062
1063+
1064+
.. _billion laughs: https://en.wikipedia.org/wiki/Billion_laughs_attack
10071065
.. |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
@@ -57,6 +57,11 @@ struct PyExpat_CAPI
5757
XML_Parser parser, unsigned long long activationThresholdBytes);
5858
XML_Bool (*SetAllocTrackerMaximumAmplification)(
5959
XML_Parser parser, float maxAmplificationFactor);
60+
/* might be NULL for expat < 2.4.0 */
61+
XML_Bool (*SetBillionLaughsAttackProtectionActivationThreshold)(
62+
XML_Parser parser, unsigned long long activationThresholdBytes);
63+
XML_Bool (*SetBillionLaughsAttackProtectionMaximumAmplification)(
64+
XML_Parser parser, float maxAmplificationFactor);
6065
/* always add new stuff to the end! */
6166
};
6267

Lib/test/test_pyexpat.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,64 @@ def test_set_maximum_amplification__fail_for_subparser(self):
985985
self.assert_root_parser_failure(setter, 123.45)
986986

987987

988+
@unittest.skipIf(expat.version_info < (2, 4, 0), "requires Expat >= 2.4.0")
989+
class ExpansionProtectionTest(AttackProtectionTestBase, unittest.TestCase):
990+
991+
def assert_rejected(self, func, /, *args, **kwargs):
992+
"""Check that func(*args, **kwargs) hits the allocation limit."""
993+
msg = (
994+
r"limit on input amplification factor \(from DTD and entities\) "
995+
r"breached: line \d+, column \d+"
996+
)
997+
self.assertRaisesRegex(expat.ExpatError, msg, func, *args, **kwargs)
998+
999+
def set_activation_threshold(self, parser, threshold):
1000+
return parser.SetBillionLaughsAttackProtectionActivationThreshold(threshold)
1001+
1002+
def set_maximum_amplification(self, parser, max_factor):
1003+
return parser.SetBillionLaughsAttackProtectionMaximumAmplification(max_factor)
1004+
1005+
def test_set_activation_threshold__threshold_reached(self):
1006+
parser = expat.ParserCreate()
1007+
# Choose a threshold expected to be always reached.
1008+
self.set_activation_threshold(parser, 3)
1009+
# Check that the threshold is reached by choosing a small factor
1010+
# and a payload whose peak amplification factor exceeds it.
1011+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1012+
payload = self.exponential_expansion_payload(ncols=10, nrows=4)
1013+
self.assert_rejected(parser.Parse, payload, True)
1014+
1015+
def test_set_activation_threshold__threshold_not_reached(self):
1016+
parser = expat.ParserCreate()
1017+
# Choose a threshold expected to be never reached.
1018+
self.set_activation_threshold(parser, pow(10, 5))
1019+
# Check that the threshold is reached by choosing a small factor
1020+
# and a payload whose peak amplification factor exceeds it.
1021+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1022+
payload = self.exponential_expansion_payload(ncols=10, nrows=4)
1023+
self.assertIsNotNone(parser.Parse(payload, True))
1024+
1025+
def test_set_maximum_amplification__amplification_exceeded(self):
1026+
parser = expat.ParserCreate()
1027+
# Unconditionally enable maximum activation factor.
1028+
self.set_activation_threshold(parser, 0)
1029+
# Choose a max amplification factor expected to always be exceeded.
1030+
self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1031+
# Craft a payload for which the peak amplification factor is > 1.0.
1032+
payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1033+
self.assert_rejected(parser.Parse, payload, True)
1034+
1035+
def test_set_maximum_amplification__amplification_not_exceeded(self):
1036+
parser = expat.ParserCreate()
1037+
# Unconditionally enable maximum activation factor.
1038+
self.set_activation_threshold(parser, 0)
1039+
# Choose a max amplification factor expected to never be exceeded.
1040+
self.assertIsNone(self.set_maximum_amplification(parser, 1e4))
1041+
# Craft a payload for which the peak amplification factor is < 1e4.
1042+
payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1043+
self.assertIsNotNone(parser.Parse(payload, True))
1044+
1045+
9881046
@unittest.skipIf(expat.version_info < (2, 7, 2), "requires Expat >= 2.7.2")
9891047
class MemoryProtectionTest(AttackProtectionTestBase, unittest.TestCase):
9901048

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Add
2+
:meth:`~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionActivationThreshold`
3+
and
4+
:meth:`~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionMaximumAmplification`
5+
to :ref:`xmlparser <xmlparser-objects>` objects to tune protections against
6+
`billion laughs <https://en.wikipedia.org/wiki/Billion_laughs_attack>`_ attacks.
7+
Patch by Bénédikt Tran.

Modules/clinic/pyexpat.c.h

Lines changed: 145 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)