Skip to content

Commit 0014ca9

Browse files
authored
Reject negative array and map header sizes (#742)
1 parent 7a63920 commit 0014ca9

3 files changed

Lines changed: 18 additions & 0 deletions

File tree

msgpack/_packer.pyx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,8 @@ cdef class Packer:
300300
@cython.critical_section
301301
def pack_array_header(self, long long size):
302302
self._check_exports()
303+
if size < 0:
304+
raise ValueError("array size must be non-negative")
303305
if size > ITEM_LIMIT:
304306
raise ValueError("array too large")
305307
msgpack_pack_array(&self.pk, size)
@@ -311,6 +313,8 @@ cdef class Packer:
311313
@cython.critical_section
312314
def pack_map_header(self, long long size):
313315
self._check_exports()
316+
if size < 0:
317+
raise ValueError("map size must be non-negative")
314318
if size > ITEM_LIMIT:
315319
raise ValueError("map too learge")
316320
msgpack_pack_map(&self.pk, size)

msgpack/fallback.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,8 @@ def pack_map_pairs(self, pairs):
837837
return ret
838838

839839
def pack_array_header(self, n):
840+
if n < 0:
841+
raise ValueError("array size must be non-negative")
840842
if n >= 2**32:
841843
raise ValueError
842844
self._pack_array_header(n)
@@ -846,6 +848,8 @@ def pack_array_header(self, n):
846848
return ret
847849

848850
def pack_map_header(self, n):
851+
if n < 0:
852+
raise ValueError("map size must be non-negative")
849853
if n >= 2**32:
850854
raise ValueError
851855
self._pack_map_header(n)

test/test_limits.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ def test_map_header():
5252
packer.pack_array_header(2**32)
5353

5454

55+
@pytest.mark.parametrize("method", ["pack_array_header", "pack_map_header"])
56+
@pytest.mark.parametrize("size", [-1, -(2**32)])
57+
def test_negative_header_size(method, size):
58+
packer = Packer(autoreset=False)
59+
packer.pack("existing")
60+
with pytest.raises(PackValueError, match="size must be non-negative"):
61+
getattr(packer, method)(size)
62+
assert packer.bytes() == packb("existing")
63+
64+
5565
def test_max_str_len():
5666
d = "x" * 3
5767
packed = packb(d)

0 commit comments

Comments
 (0)