From 9d57825fe02f71b7df6c0d922d3f32ee7430929c Mon Sep 17 00:00:00 2001 From: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> Date: Tue, 10 Mar 2026 16:57:34 +0000 Subject: [PATCH] Fix integer overflow for formats "s" and "p" in the struct module (GH-145750) (cherry picked from commit 4d0dce0c8ddc4d0321bd590a1a33990edc2e1b08) Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> --- Lib/test/test_struct.py | 6 ++++++ .../2026-03-10-14-13-12.gh-issue-145750.iQsTeX.rst | 3 +++ Modules/_struct.c | 8 +++++++- 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-03-10-14-13-12.gh-issue-145750.iQsTeX.rst diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index 9fe1313724f9c3..598f10b1862317 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -555,6 +555,12 @@ def test_count_overflow(self): hugecount3 = '{}i{}q'.format(sys.maxsize // 4, sys.maxsize // 8) self.assertRaises(struct.error, struct.calcsize, hugecount3) + hugecount4 = '{}?s'.format(sys.maxsize) + self.assertRaises(struct.error, struct.calcsize, hugecount4) + + hugecount5 = '{}?p'.format(sys.maxsize) + self.assertRaises(struct.error, struct.calcsize, hugecount5) + def test_trailing_counter(self): store = array.array('b', b' '*100) diff --git a/Misc/NEWS.d/next/Library/2026-03-10-14-13-12.gh-issue-145750.iQsTeX.rst b/Misc/NEWS.d/next/Library/2026-03-10-14-13-12.gh-issue-145750.iQsTeX.rst new file mode 100644 index 00000000000000..a909bea2caffe9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-03-10-14-13-12.gh-issue-145750.iQsTeX.rst @@ -0,0 +1,3 @@ +Avoid undefined behaviour from signed integer overflow when parsing format +strings in the :mod:`struct` module. Found by OSS Fuzz in +:oss-fuzz:`488466741`. diff --git a/Modules/_struct.c b/Modules/_struct.c index 106bcd9b495da4..fe8c689b629ee3 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -1676,7 +1676,13 @@ prepare_s(PyStructObject *self, PyObject *format) switch (c) { case 's': _Py_FALLTHROUGH; - case 'p': len++; ncodes++; break; + case 'p': + if (len == PY_SSIZE_T_MAX) { + goto overflow; + } + len++; + ncodes++; + break; case 'x': break; default: if (num > PY_SSIZE_T_MAX - len) {