From 640b6ce51015d38176f9e6851345701aed73b145 Mon Sep 17 00:00:00 2001 From: Alhuda Khan Date: Tue, 17 Nov 2026 17:20:34 +0530 Subject: [PATCH] Avoid use-after-free when Unpacker or Packer __init__ fails Both C extension __init__ methods released old state before every argument was validated. A rejected re-init left Unpacker.ctx.user pointing at the released hooks and unicode_errors, Unpacker.buf NULL with a stale buf_size, and Packer.unicode_errors pointing into the released _berrors string. Clear the borrowed pointers before their owners are replaced, and free the old Unpacker buffer only once the new one is allocated. --- msgpack/_packer.pyx | 7 ++++--- msgpack/_unpacker.pyx | 16 ++++++++++------ test/test_pack.py | 12 ++++++++++++ test/test_unpack.py | 30 ++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 9 deletions(-) diff --git a/msgpack/_packer.pyx b/msgpack/_packer.pyx index c44c6366..0c6e2c10 100644 --- a/msgpack/_packer.pyx +++ b/msgpack/_packer.pyx @@ -143,10 +143,11 @@ cdef class Packer: raise TypeError("default must be a callable.") self._default = default + # Clear the borrowed pointer first: converting a new value may fail + # after the old _berrors has been released. + self.unicode_errors = NULL self._berrors = unicode_errors - if unicode_errors is None: - self.unicode_errors = NULL - else: + if unicode_errors is not None: self.unicode_errors = self._berrors # returns -2 when default should(o) be called diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx index 44f83f09..cfa7b4fe 100644 --- a/msgpack/_unpacker.pyx +++ b/msgpack/_unpacker.pyx @@ -344,15 +344,17 @@ cdef class Unpacker: Py_ssize_t max_map_len=-1, Py_ssize_t max_ext_len=-1): cdef const char *cerr=NULL + cdef char *new_buf if self._unpacking: raise RuntimeError("Unpacker.__init__() cannot be called while unpacking is in progress") unpack_clear(&self.ctx) unpack_init(&self.ctx) - if self.buf != NULL: - PyMem_Free(self.buf) - self.buf = NULL + # The references below are replaced before init_ctx() runs, and the + # arguments may still be rejected, so don't keep borrowed pointers. + self.ctx.user.object_hook = self.ctx.user.list_hook = self.ctx.user.ext_hook = NULL + self.ctx.user.unicode_errors = NULL self.object_hook = object_hook self.object_pairs_hook = object_pairs_hook @@ -383,11 +385,13 @@ cdef class Unpacker: if not read_size: read_size = min(max_buffer_size, 1024**2) + new_buf = PyMem_Malloc(read_size) + if new_buf == NULL: + raise MemoryError("Unable to allocate internal buffer.") + PyMem_Free(self.buf) + self.buf = new_buf self.max_buffer_size = max_buffer_size self.read_size = read_size - self.buf = PyMem_Malloc(read_size) - if self.buf == NULL: - raise MemoryError("Unable to allocate internal buffer.") self.buf_size = read_size self.buf_head = 0 self.buf_tail = 0 diff --git a/test/test_pack.py b/test/test_pack.py index 9ca6e182..08474eaf 100644 --- a/test/test_pack.py +++ b/test/test_pack.py @@ -97,6 +97,18 @@ def testIgnoreErrorsPack(): assert re == "abcdef" +@pytest.mark.skipif( + Packer.__module__ == "msgpack.fallback", reason="specific to C extension reinit" +) +def testFailedReinitDropsUnicodeErrors(): + packer = Packer(unicode_errors="".join(["ign", "ore"])) + assert packer.pack("abc\udc80") == b"\xa3abc" + with pytest.raises(TypeError): + packer.__init__(unicode_errors=1) + with pytest.raises(UnicodeEncodeError): + packer.pack("abc\udc80") + + def testDecodeBinary(): re = unpackb(packb(b"abc"), use_list=1) assert re == b"abc" diff --git a/test/test_unpack.py b/test/test_unpack.py index 03e49ca3..2eff9b7b 100644 --- a/test/test_unpack.py +++ b/test/test_unpack.py @@ -151,6 +151,36 @@ def hook(code, data): assert unpacker.unpack() == {"a": 1} +@mark.skipif( + Unpacker.__module__ == "msgpack.fallback", + reason="specific to C extension reinit", +) +def test_unpacker_failed_reinit_drops_hooks(): + class Hook: + def __call__(self, obj): + return obj + + hook = Hook() + hook_ref = weakref.ref(hook) + unpacker = Unpacker(object_hook=hook) + del hook + + # Both are rejected partway through __init__, after the old hook is dropped. + with raises(TypeError): + unpacker.__init__(unicode_errors=1) + with raises(ValueError): + unpacker.__init__(read_size=10, max_buffer_size=5) + gc.collect() + assert hook_ref() is None + + unpacker.feed(b"\x80") + assert unpacker.unpack() == {} + + unpacker.__init__() + unpacker.feed(packb({"a": 1})) + assert unpacker.unpack() == {"a": 1} + + @mark.skipif( Unpacker.__module__ == "msgpack.fallback", reason="reentrant guard is implemented in C extension only",