]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-97616: list_resize() checks for integer overflow (GH-97617)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 28 Sep 2022 22:28:38 +0000 (15:28 -0700)
committerPablo Galindo <pablogsal@gmail.com>
Mon, 24 Oct 2022 15:45:40 +0000 (16:45 +0100)
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 <vstinner@python.org>
Lib/test/test_list.py
Misc/NEWS.d/next/Security/2022-09-28-17-09-37.gh-issue-97616.K1e3Xs.rst [new file with mode: 0644]
Objects/listobject.c

index d3da05ba84ac0ffc22d7adddf8a622760fdc8ac1..9aa6dd1095668b7abaedfe853062c8265434ebe6 100644 (file)
@@ -96,6 +96,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 (file)
index 0000000..721427f
--- /dev/null
@@ -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.
index 8e3d02ab17ea9a82a6cdf69d9cd7b983ec0a75d9..19009133c8275971a0b0db875b3d1d381dc6b9e5 100644 (file)
@@ -76,8 +76,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;