Skip to content
Merged
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
[3.14] gh-143003: Fix possible shared buffer overflow in bytearray.ex…
…tend() (GH-143086)

When __length_hint__() returns 0 for non-empty iterator, the data can be
written past the shared 0-terminated buffer, corrupting it.
(cherry picked from commit 5225635)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
  • Loading branch information
serhiy-storchaka authored and StanFromIreland committed Jan 5, 2026
commit 64675884a32925047d2f8c4d8ace4f3a0d81c101
17 changes: 17 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2013,6 +2013,23 @@ def make_case():
with self.assertRaises(BufferError):
ba.rsplit(evil)

def test_extend_empty_buffer_overflow(self):
# gh-143003
class EvilIter:
def __iter__(self):
return self
def __next__(self):
return next(source)
def __length_hint__(self):
return 0

# Use ASCII digits so float() takes the fast path that expects a NUL terminator.
source = iter(b'42')
ba = bytearray()
ba.extend(EvilIter())

self.assertRaises(ValueError, float, bytearray())

def test_hex_use_after_free(self):
# Prevent UAF in bytearray.hex(sep) with re-entrant sep.__len__.
# Regression test for https://github.com/python/cpython/issues/143195.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix an overflow of the shared empty buffer in :meth:`bytearray.extend` when
``__length_hint__()`` returns 0 for non-empty iterator.
4 changes: 2 additions & 2 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2182,7 +2182,6 @@ bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints)
Py_DECREF(bytearray_obj);
return NULL;
}
buf[len++] = value;
Py_DECREF(item);

if (len >= buf_size) {
Expand All @@ -2192,7 +2191,7 @@ bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints)
Py_DECREF(bytearray_obj);
return PyErr_NoMemory();
}
addition = len >> 1;
addition = len ? len >> 1 : 1;
if (addition > PY_SSIZE_T_MAX - len - 1)
buf_size = PY_SSIZE_T_MAX;
else
Expand All @@ -2206,6 +2205,7 @@ bytearray_extend_impl(PyByteArrayObject *self, PyObject *iterable_of_ints)
have invalidated it. */
buf = PyByteArray_AS_STRING(bytearray_obj);
}
buf[len++] = value;
}
Py_DECREF(it);

Expand Down
Loading