From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Tue, 4 Oct 2022 17:08:24 +0000 (-0700) Subject: [3.8] gh-97616: list_resize() checks for integer overflow (GH-97617) (GH-97628) X-Git-Tag: v3.8.15~5 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=f9ce9d4684cc293f40171af8fde253e4762baf9d;p=thirdparty%2FPython%2Fcpython.git [3.8] gh-97616: list_resize() checks for integer overflow (GH-97617) (GH-97628) gh-97616: list_resize() checks for integer overflow (GH-97617) Fix multiplying a list by an integer (list *= int): detect the integer overflow when the new allocated length is close to the maximum size. Issue reported by Jordan Limor. list_resize() now checks for integer overflow before multiplying the new allocated length by the list item size (sizeof(PyObject*)). (cherry picked from commit a5f092f3c469b674b8d9ccbd4e4377230c9ac7cf) Co-authored-by: Victor Stinner --- diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py index 105ef650eee9..75ecc70b0b0d 100644 --- a/Lib/test/test_list.py +++ b/Lib/test/test_list.py @@ -68,6 +68,19 @@ class ListTest(list_tests.CommonTest): self.assertRaises((MemoryError, OverflowError), mul, lst, n) self.assertRaises((MemoryError, OverflowError), imul, lst, n) + def test_list_resize_overflow(self): + # gh-97616: test new_allocated * sizeof(PyObject*) overflow + # check in list_resize() + lst = [0] * 65 + del lst[1:] + self.assertEqual(len(lst), 1) + + size = ((2 ** (tuple.__itemsize__ * 8) - 1) // 2) + with self.assertRaises((MemoryError, OverflowError)): + lst * size + with self.assertRaises((MemoryError, OverflowError)): + lst *= size + def test_repr_large(self): # Check the repr of large list objects def check(n): diff --git a/Misc/NEWS.d/next/Security/2022-09-28-17-09-37.gh-issue-97616.K1e3Xs.rst b/Misc/NEWS.d/next/Security/2022-09-28-17-09-37.gh-issue-97616.K1e3Xs.rst new file mode 100644 index 000000000000..721427fe6465 --- /dev/null +++ b/Misc/NEWS.d/next/Security/2022-09-28-17-09-37.gh-issue-97616.K1e3Xs.rst @@ -0,0 +1,3 @@ +Fix multiplying a list by an integer (``list *= int``): detect the integer +overflow when the new allocated length is close to the maximum size. Issue +reported by Jordan Limor. Patch by Victor Stinner. diff --git a/Objects/listobject.c b/Objects/listobject.c index 30444089ffaf..473de9d2dda5 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -66,8 +66,14 @@ list_resize(PyListObject *self, Py_ssize_t newsize) if (newsize == 0) new_allocated = 0; - num_allocated_bytes = new_allocated * sizeof(PyObject *); - items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes); + if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) { + num_allocated_bytes = new_allocated * sizeof(PyObject *); + items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes); + } + else { + // integer overflow + items = NULL; + } if (items == NULL) { PyErr_NoMemory(); return -1;