Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
c1c23fb
Expose XML Expat 2.7.2 mitigation APIs
picnixz Sep 22, 2025
12bef9c
add tests
picnixz Sep 22, 2025
1d7e599
docs
picnixz Sep 22, 2025
3dcd9bd
NEWS
picnixz Sep 22, 2025
192fe08
Merge branch 'main' into feat/xml/mitigation-api-90949
picnixz Sep 22, 2025
0ecbd55
fix docs
picnixz Sep 22, 2025
07445ad
fix tests
picnixz Sep 22, 2025
9c7371f
regen SBOM
picnixz Sep 22, 2025
1085584
remove unused include
picnixz Sep 22, 2025
c10fe91
fix possible error handling
picnixz Sep 22, 2025
18d175f
undef macro after usage
picnixz Sep 22, 2025
911b2b7
Update Lib/test/test_pyexpat.py
picnixz Sep 22, 2025
d636685
update comments
picnixz Sep 22, 2025
b951065
use better test names
picnixz Sep 22, 2025
e11bf14
simplify roles usage
picnixz Sep 22, 2025
3e45613
prevent reparse deferral of Expat to blow up
picnixz Sep 22, 2025
fb83fb5
test better numeric values
picnixz Sep 22, 2025
7f91f2e
update docs
picnixz Sep 22, 2025
64af05c
avoid deprecated `XML_GetError{Line,Column}Number`
picnixz Sep 22, 2025
b01e53d
raise `NotImplementedError` for unavailable mitigation APIs
picnixz Sep 22, 2025
cd040bf
improve various wordings
picnixz Sep 23, 2025
a09cd15
avoid SBOM alteration
picnixz Sep 23, 2025
a3fc3b3
regen files
picnixz Sep 23, 2025
5afe1ad
improve test assertions
picnixz Sep 23, 2025
b6949dd
improve test genericity
picnixz Sep 23, 2025
bdbd382
split tests even if they could end up duplicated
picnixz Sep 23, 2025
0c03735
raise AttributeError when method is not available and reorder interface
picnixz Sep 23, 2025
220f3e2
reoder docs
picnixz Sep 23, 2025
9d538e4
address review
picnixz Sep 24, 2025
209f300
update capsule API
picnixz Sep 24, 2025
8407cfc
amend docs
picnixz Sep 24, 2025
e898811
use "NOTE:"
picnixz Sep 24, 2025
ce8cb48
address final comments
picnixz Sep 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions Lib/test/test_pyexpat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
# handler, are obscure and unhelpful.

import os
import re
import sys
import sysconfig
import unittest
import textwrap
import traceback
from io import BytesIO
from test import support
Expand Down Expand Up @@ -821,5 +823,92 @@ def start_element(name, _):
self.assertEqual(started, ['doc'])


class AttackProtectionTest(unittest.TestCase):

def billion_laughs(self, ncols, nrows, text='.'):
"""Create a billion laugh payload.

Be careful: the number of total items is pow(n, k), thereby
requiring at least pow(ncols, nrows) * sizeof(base) memory!
"""
body = textwrap.indent('\n'.join(
f'<!ENTITY row{i + 1} "{f"&row{i};" * ncols}">'
for i in range(nrows)
), ' ')
return f"""\
<?xml version="1.0"?>
<!DOCTYPE doc [
<!ENTITY row0 "{text}">
<!ELEMENT doc (#PCDATA)>
{body}
]>
<doc>&row{nrows};</doc>
"""

def test_set_alloc_tracker_maximum_amplification(self):
payload = self.billion_laughs(10, 4)

p = expat.ParserCreate()
# Unconditionally enable maximum amplification factor.
p.SetAllocTrackerActivationThreshold(0)
# At runtime, the peak amplification factor is 101.71,
# which is above the default threshold (100.0).
msg = re.escape("out of memory: line 3, column 15")
self.assertRaisesRegex(expat.ExpatError, msg, p.Parse, payload)

# # Re-create a parser as the current parser is now in an error state.
p = expat.ParserCreate()
# Unconditionally enable maximum amplification factor.
p.SetAllocTrackerActivationThreshold(0)
# Use a max amplification factor a bit above the actual one.
self.assertIsNone(p.SetAllocTrackerMaximumAmplification(101.72))
self.assertIsNotNone(p.Parse(payload))

def test_set_alloc_tracker_maximum_amplification_invalid_args(self):
parser = expat.ParserCreate()
f = parser.SetAllocTrackerMaximumAmplification

msg = re.escape("'max_factor' must be at least 1.0")
self.assertRaisesRegex(expat.ExpatError, msg, f, float('nan'))
self.assertRaisesRegex(expat.ExpatError, msg, f, 0.99)

subparser = parser.ExternalEntityParserCreate(None)
fsub = subparser.SetAllocTrackerMaximumAmplification
msg = re.escape("parser must be a root parser")
self.assertRaisesRegex(expat.ExpatError, msg, fsub, 1.0)

def test_set_alloc_tracker_activation_threshold(self):
# Run the test with EXPAT_MALLOC_DEBUG=2 to detect those constants.
MAX_ALLOC = 17333
MIN_ALLOC = 1096

payload = self.billion_laughs(10, 4)

p = expat.ParserCreate()
p.SetAllocTrackerActivationThreshold(MAX_ALLOC + 1)
self.assertIsNone(p.SetAllocTrackerMaximumAmplification(1.0))
# Check that we never reach the activation threshold.
self.assertIsNotNone(p.Parse(payload))

p = expat.ParserCreate()
p.SetAllocTrackerActivationThreshold(MIN_ALLOC - 1)
# Check that we always reach the activation threshold.
self.assertIsNone(p.SetAllocTrackerMaximumAmplification(1.0))
msg = re.escape("out of memory: line 3, column 10")
self.assertRaisesRegex(expat.ExpatError, msg, p.Parse, payload)

def test_set_alloc_tracker_activation_threshold_invalid_args(self):
parser = expat.ParserCreate()
f = parser.SetAllocTrackerActivationThreshold

ULONG_LONG_MAX = 2 * sys.maxsize + 1
self.assertRaises(OverflowError, f, ULONG_LONG_MAX + 1)

subparser = parser.ExternalEntityParserCreate(None)
fsub = subparser.SetAllocTrackerActivationThreshold
msg = re.escape("parser must be a root parser")
self.assertRaisesRegex(expat.ExpatError, msg, fsub, 12345)


if __name__ == "__main__":
unittest.main()