Skip to content

Commit 6588ca5

Browse files
miss-islingtonByteFlowing1337picnixz
authored
[3.14] gh-148441: Avoid integer overflow in Expat's CharacterDataHandler (GH-148904) (#149638)
gh-148441: Avoid integer overflow in Expat's CharacterDataHandler (GH-148904) (cherry picked from commit bc1be4f) Co-authored-by: ByteFlow <fakeshadow1337@gmail.com> Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 141571b commit 6588ca5

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

Lib/test/test_pyexpat.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,20 @@ def test_change_size_2(self):
672672
parser.Parse(xml2, True)
673673
self.assertEqual(self.n, 4)
674674

675+
@support.requires_resource('cpu')
676+
@support.requires_resource('walltime')
677+
@support.bigmemtest(size=2**31, memuse=4, dry_run=False)
678+
def test_large_character_data_does_not_crash(self):
679+
# See https://github.com/python/cpython/issues/148441
680+
parser = expat.ParserCreate()
681+
parser.buffer_text = True
682+
parser.buffer_size = 2**31 - 1 # INT_MAX
683+
N = 2049 * (1 << 20) - 3 # Character data greater than INT_MAX
684+
self.assertGreater(N, parser.buffer_size)
685+
parser.CharacterDataHandler = lambda text: None
686+
xml_data = b"<r>" + b"A" * N + b"</r>"
687+
self.assertEqual(parser.Parse(xml_data, True), 1)
688+
675689
class ElementDeclHandlerTest(unittest.TestCase):
676690
def test_trigger_leak(self):
677691
# Unfixed, this test would leak the memory of the so-called
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:mod:`xml.parsers.expat`: prevent a crash in
2+
:meth:`~xml.parsers.expat.xmlparser.CharacterDataHandler`
3+
when the character data size exceeds the parser's
4+
:attr:`buffer size <xml.parsers.expat.xmlparser.buffer_size>`.

Modules/pyexpat.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
389389
if (self->buffer == NULL)
390390
call_character_handler(self, data, len);
391391
else {
392-
if ((self->buffer_used + len) > self->buffer_size) {
392+
if (len > (self->buffer_size - self->buffer_used)) {
393393
if (flush_character_buffer(self) < 0)
394394
return;
395395
/* handler might have changed; drop the rest on the floor

0 commit comments

Comments
 (0)