]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-142664: fix UAF in `memoryview.__hash__` via re-entrant data's `__hash__...
authorBénédikt Tran <10796600+picnixz@users.noreply.github.com>
Sat, 27 Dec 2025 13:43:11 +0000 (13:43 +0000)
committerGitHub <noreply@github.com>
Sat, 27 Dec 2025 13:43:11 +0000 (13:43 +0000)
(cherry picked from commit 00e24b80e092e7d36dc189fd260b2a4e730a6e7f)

Lib/test/test_memoryview.py
Misc/NEWS.d/next/Core and Builtins/2025-12-27-13-18-12.gh-issue-142664.peeEDV.rst [new file with mode: 0644]
Objects/memoryobject.c

index 91ae688978b0143f1a30d13b2c7505a614b9c1ab..f8dd1231bb80098715649408c42287c77a50dbcb 100644 (file)
@@ -344,6 +344,20 @@ class AbstractMemoryTests:
         m = self._view(b)
         self.assertRaises(ValueError, hash, m)
 
+    def test_hash_use_after_free(self):
+        # Prevent crash in memoryview(v).__hash__ with re-entrant v.__hash__.
+        # Regression test for https://github.com/python/cpython/issues/142664.
+        class E(array.array):
+            def __hash__(self):
+                mv.release()
+                self.clear()
+                return 123
+
+        v = E('B', b'A' * 4096)
+        mv = memoryview(v).toreadonly()   # must be read-only for hash()
+        self.assertRaises(BufferError, hash, mv)
+        self.assertRaises(BufferError, mv.__hash__)
+
     def test_weakref(self):
         # Check memoryviews are weakrefable
         for tp in self._types:
diff --git a/Misc/NEWS.d/next/Core and Builtins/2025-12-27-13-18-12.gh-issue-142664.peeEDV.rst b/Misc/NEWS.d/next/Core and Builtins/2025-12-27-13-18-12.gh-issue-142664.peeEDV.rst
new file mode 100644 (file)
index 0000000..39c2183
--- /dev/null
@@ -0,0 +1,3 @@
+Fix a use-after-free crash in :meth:`memoryview.__hash__ <object.__hash__>`
+when the ``__hash__`` method of the referenced object mutates that object or
+the view. Patch by Bénédikt Tran.
index 9773bc2cc1c98b4e9441a632410160425044580c..f71ac6fde17dcda4f0d27400faa4dc6da2959b20 100644 (file)
@@ -3074,9 +3074,16 @@ memory_hash(PyObject *_self)
                 "memoryview: hashing is restricted to formats 'B', 'b' or 'c'");
             return -1;
         }
-        if (view->obj != NULL && PyObject_Hash(view->obj) == -1) {
-            /* Keep the original error message */
-            return -1;
+        if (view->obj != NULL) {
+            // Prevent 'self' from being freed when computing the item's hash.
+            // See https://github.com/python/cpython/issues/142664.
+            self->exports++;
+            int rc = PyObject_Hash(view->obj);
+            self->exports--;
+            if (rc == -1) {
+                /* Keep the original error message */
+                return -1;
+            }
         }
 
         if (!MV_C_CONTIGUOUS(self->flags)) {