Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
gh-142557: fix UAF in bytearray.__mod__ via re-entrant argument's `…
…__repr__`
  • Loading branch information
picnixz committed Dec 27, 2025
commit 9baf9c00fc9a18806aa9285235d8b0664f4c9448
13 changes: 13 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,19 @@ def test_bytearray_api(self):
except OSError:
pass

def test_mod_use_after_free(self):
Comment thread
picnixz marked this conversation as resolved.
Outdated
# Prevent UAF in bytearray % (a1, a2) with re-entrant a[12].__repr__.
Comment thread
picnixz marked this conversation as resolved.
Outdated
# Regression test for https://github.com/python/cpython/issues/142557.
fmt = bytearray(b"%a %a")

class S:
def __repr__(self):
fmt.clear()
return "E"

args = (S(), S())
Comment thread
picnixz marked this conversation as resolved.
Outdated
self.assertRaises(BufferError, fmt.__mod__, args)

def test_reverse(self):
b = bytearray(b'hello')
self.assertEqual(b.reverse(), None)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a use-after-free crash in :meth:`bytearray.__mod__` when the
Comment thread
picnixz marked this conversation as resolved.
Outdated
:meth:`~object.__repr__` method of one of the arguments to format mutates
the :class:`bytearray`. Patch by Bénédikt Tran.
10 changes: 9 additions & 1 deletion Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2837,7 +2837,15 @@ bytearray_mod_lock_held(PyObject *v, PyObject *w)
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(v);
if (!PyByteArray_Check(v))
Py_RETURN_NOTIMPLEMENTED;
return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1);

PyByteArrayObject *self = _PyByteArray_CAST(v);
/* Increase exports to prevent bytearray storage from changing during op. */
self->ob_exports++;
PyObject *res = _PyBytes_FormatEx(
PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1
);
self->ob_exports--;
return res;
}

static PyObject *
Expand Down
Loading