Skip to content

Commit 640b6ce

Browse files
committed
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.
1 parent e3a7160 commit 640b6ce

4 files changed

Lines changed: 56 additions & 9 deletions

File tree

‎msgpack/_packer.pyx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,10 +143,11 @@ cdef class Packer:
143143
raise TypeError("default must be a callable.")
144144
self._default = default
145145

146+
# Clear the borrowed pointer first: converting a new value may fail
147+
# after the old _berrors has been released.
148+
self.unicode_errors = NULL
146149
self._berrors = unicode_errors
147-
if unicode_errors is None:
148-
self.unicode_errors = NULL
149-
else:
150+
if unicode_errors is not None:
150151
self.unicode_errors = self._berrors
151152

152153
# returns -2 when default should(o) be called

‎msgpack/_unpacker.pyx‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -344,15 +344,17 @@ cdef class Unpacker:
344344
Py_ssize_t max_map_len=-1,
345345
Py_ssize_t max_ext_len=-1):
346346
cdef const char *cerr=NULL
347+
cdef char *new_buf
347348

348349
if self._unpacking:
349350
raise RuntimeError("Unpacker.__init__() cannot be called while unpacking is in progress")
350351

351352
unpack_clear(&self.ctx)
352353
unpack_init(&self.ctx)
353-
if self.buf != NULL:
354-
PyMem_Free(self.buf)
355-
self.buf = NULL
354+
# The references below are replaced before init_ctx() runs, and the
355+
# arguments may still be rejected, so don't keep borrowed pointers.
356+
self.ctx.user.object_hook = self.ctx.user.list_hook = self.ctx.user.ext_hook = NULL
357+
self.ctx.user.unicode_errors = NULL
356358

357359
self.object_hook = object_hook
358360
self.object_pairs_hook = object_pairs_hook
@@ -383,11 +385,13 @@ cdef class Unpacker:
383385
if not read_size:
384386
read_size = min(max_buffer_size, 1024**2)
385387

388+
new_buf = <char*>PyMem_Malloc(read_size)
389+
if new_buf == NULL:
390+
raise MemoryError("Unable to allocate internal buffer.")
391+
PyMem_Free(self.buf)
392+
self.buf = new_buf
386393
self.max_buffer_size = max_buffer_size
387394
self.read_size = read_size
388-
self.buf = <char*>PyMem_Malloc(read_size)
389-
if self.buf == NULL:
390-
raise MemoryError("Unable to allocate internal buffer.")
391395
self.buf_size = read_size
392396
self.buf_head = 0
393397
self.buf_tail = 0

‎test/test_pack.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,18 @@ def testIgnoreErrorsPack():
9797
assert re == "abcdef"
9898

9999

100+
@pytest.mark.skipif(
101+
Packer.__module__ == "msgpack.fallback", reason="specific to C extension reinit"
102+
)
103+
def testFailedReinitDropsUnicodeErrors():
104+
packer = Packer(unicode_errors="".join(["ign", "ore"]))
105+
assert packer.pack("abc\udc80") == b"\xa3abc"
106+
with pytest.raises(TypeError):
107+
packer.__init__(unicode_errors=1)
108+
with pytest.raises(UnicodeEncodeError):
109+
packer.pack("abc\udc80")
110+
111+
100112
def testDecodeBinary():
101113
re = unpackb(packb(b"abc"), use_list=1)
102114
assert re == b"abc"

‎test/test_unpack.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,36 @@ def hook(code, data):
151151
assert unpacker.unpack() == {"a": 1}
152152

153153

154+
@mark.skipif(
155+
Unpacker.__module__ == "msgpack.fallback",
156+
reason="specific to C extension reinit",
157+
)
158+
def test_unpacker_failed_reinit_drops_hooks():
159+
class Hook:
160+
def __call__(self, obj):
161+
return obj
162+
163+
hook = Hook()
164+
hook_ref = weakref.ref(hook)
165+
unpacker = Unpacker(object_hook=hook)
166+
del hook
167+
168+
# Both are rejected partway through __init__, after the old hook is dropped.
169+
with raises(TypeError):
170+
unpacker.__init__(unicode_errors=1)
171+
with raises(ValueError):
172+
unpacker.__init__(read_size=10, max_buffer_size=5)
173+
gc.collect()
174+
assert hook_ref() is None
175+
176+
unpacker.feed(b"\x80")
177+
assert unpacker.unpack() == {}
178+
179+
unpacker.__init__()
180+
unpacker.feed(packb({"a": 1}))
181+
assert unpacker.unpack() == {"a": 1}
182+
183+
154184
@mark.skipif(
155185
Unpacker.__module__ == "msgpack.fallback",
156186
reason="reentrant guard is implemented in C extension only",

0 commit comments

Comments
 (0)