Skip to content

Commit a912fc5

Browse files
committed
gh-142664: fix UAF in memoryview.__hash__ via re-entrant data's __hash__
1 parent 57d5699 commit a912fc5

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

Lib/test/test_memoryview.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
are in test_buffer.
55
"""
66

7+
import array
78
import unittest
89
import test.support
910
import sys
@@ -387,6 +388,20 @@ def test_hash_writable(self):
387388
m = self._view(b)
388389
self.assertRaises(ValueError, hash, m)
389390

391+
def test_hash_use_after_free(self):
392+
# Prevent crash in memoryview(v).__hash__ with re-entrant v.__hash__.
393+
# Regression test for https://github.com/python/cpython/issues/142664.
394+
class E(array.array):
395+
def __hash__(self):
396+
mv.release()
397+
self.clear()
398+
return 123
399+
400+
v = E('B', b'A' * 4096)
401+
mv = memoryview(v).toreadonly() # must be read-only for hash()
402+
self.assertRaises(BufferError, hash, mv)
403+
self.assertRaises(BufferError, mv.__hash__)
404+
390405
def test_weakref(self):
391406
# Check memoryviews are weakrefable
392407
for tp in self._types:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a use-after-free crash in :meth:`memoryview.__hash__ <object.__hash__>`
2+
when the ``__hash__`` method of the referenced object mutates that object or
3+
the view. Patch by Bénédikt Tran.

Objects/memoryobject.c

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3225,9 +3225,16 @@ memory_hash(PyObject *_self)
32253225
"memoryview: hashing is restricted to formats 'B', 'b' or 'c'");
32263226
return -1;
32273227
}
3228-
if (view->obj != NULL && PyObject_Hash(view->obj) == -1) {
3229-
/* Keep the original error message */
3230-
return -1;
3228+
if (view->obj != NULL) {
3229+
// Prevent 'self' from being freed when computing the item's hash.
3230+
// See https://github.com/python/cpython/issues/142664.
3231+
self->exports++;
3232+
int rc = PyObject_Hash(view->obj);
3233+
self->exports--;
3234+
if (rc == -1) {
3235+
/* Keep the original error message */
3236+
return -1;
3237+
}
32313238
}
32323239

32333240
if (!MV_C_CONTIGUOUS(self->flags)) {

0 commit comments

Comments
 (0)