Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1637,6 +1637,35 @@ def test_take_bytes_optimization(self):
bytes_header_size = sys.getsizeof(b'')
self.assertEqual(ba.__alloc__(), 499 + bytes_header_size)

def test_take_bytes_reentrant_resize(self):
# gh-153570: n.__index__() can resize the bytearray, so take_bytes()
# must re-read the size afterwards. It cached the size before the
# call and used it for the bounds check and the buffer reads, so a
# reentrant clear() returned freed memory (a use-after-free read).
def take(target, resize, n):
class Evil:
def __index__(self):
resize(target)
return n
return target.take_bytes(Evil())

# clear() during __index__: nothing is left to take.
ba = bytearray(b'abcdefgh')
with self.assertRaises(IndexError):
take(ba, lambda b: b.clear(), 8)
self.assertEqual(ba, b'')

# shrink during __index__: n past the new size is out of range.
ba = bytearray(b'abcdefgh')
with self.assertRaises(IndexError):
take(ba, lambda b: b.__delitem__(slice(4, None)), 8)
self.assertEqual(ba, b'abcd')

# grow during __index__: the take runs against the new, larger size.
ba = bytearray(b'abcd')
self.assertEqual(take(ba, lambda b: b.extend(b'efgh'), 8), b'abcdefgh')
self.assertEqual(ba, b'')

def test_setitem(self):
def setitem_as_mapping(b, i, val):
b[i] = val
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a use-after-free in :meth:`bytearray.take_bytes` when the argument's
:meth:`~object.__index__` method resizes the bytearray. Patch by tonghuaroot.
2 changes: 2 additions & 0 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,8 @@ bytearray_take_bytes_impl(PyByteArrayObject *self, PyObject *n)
if (to_take == -1 && PyErr_Occurred()) {
return NULL;
}
// n.__index__() may have resized self; use the current size.
size = Py_SIZE(self);
if (to_take < 0) {
to_take += size;
}
Expand Down
Loading