Skip to content

Commit e861f75

Browse files
fix: use-after-free in get_data_from_buffer (#677)
1 parent 975a2a4 commit e861f75

3 files changed

Lines changed: 16 additions & 5 deletions

File tree

msgpack/_unpacker.pyx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,9 @@ cdef inline int get_data_from_buffer(object obj,
129129
PyBuffer_Release(view)
130130
# create a contiguous copy and get buffer
131131
contiguous = PyMemoryView_GetContiguous(obj, PyBUF_READ, b'C')
132-
PyObject_GetBuffer(contiguous, view, PyBUF_SIMPLE)
133-
# view must hold the only reference to contiguous,
134-
# so memory is freed when view is released
135-
Py_DECREF(contiguous)
132+
if PyObject_GetBuffer(contiguous, view, PyBUF_SIMPLE) == -1:
133+
raise
134+
136135
buffer_len[0] = view.len
137136
buf[0] = <char*> view.buf
138137
return 1

msgpack/fallback.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ def feed(self, next_bytes):
328328
self._buf_checkpoint = 0
329329

330330
# Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython
331-
self._buffer.extend(view)
331+
self._buffer.extend(view if view.contiguous else view.tobytes())
332332
view.release()
333333

334334
def _consume(self):

test/test_memoryview.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,15 @@ def test_multidim_memoryview():
9797
data = view.cast(view.format, (3, 2))
9898
packed = packb(data)
9999
assert packed == b"\xc4\x06\x00\x00\x00\x00\x00\x00"
100+
101+
102+
def test_unpack_noncontiguous_memoryview():
103+
# Use a multi-byte value so the padded stride-2 view is non-contiguous.
104+
packed = packb(2**32)
105+
padded = bytearray()
106+
for byte in packed:
107+
padded.append(byte)
108+
padded.append(0)
109+
noncont = memoryview(bytes(padded))[::2]
110+
assert not noncont.c_contiguous
111+
assert unpackb(noncont) == 2**32

0 commit comments

Comments
 (0)