Skip to content

Commit 77087dd

Browse files
authored
PYTHON-4323 Add regression test for out-of-bounds read when decoding invalid bson (mongodb#1693)
1 parent 25cbc7e commit 77087dd

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

test/test_bson.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import os
2424
import pickle
2525
import re
26+
import struct
2627
import sys
2728
import tempfile
2829
import uuid
@@ -489,6 +490,33 @@ def test_basic_encode(self):
489490
b"\x00",
490491
)
491492

493+
def test_bad_code(self):
494+
# Assert that decoding invalid Code with scope does not include a field name.
495+
def generate_payload(length: int) -> bytes:
496+
string_size = length - 0x1E
497+
498+
return bytes.fromhex(
499+
struct.pack("<I", length).hex() # payload size
500+
+ "0f" # type "code with scope"
501+
+ "3100" # key (cstring)
502+
+ "0a000000" # c_w_s_size
503+
+ "04000000" # code_size
504+
+ "41004200" # code (cstring)
505+
+ "feffffff" # scope_size
506+
+ "02" # type "string"
507+
+ "3200" # key (cstring)
508+
+ struct.pack("<I", string_size).hex() # string size
509+
+ "00" * string_size # value (cstring)
510+
# next bytes is a field name for type \x00
511+
# type \x00 is invalid so bson throws an exception
512+
)
513+
514+
for i in range(100):
515+
payload = generate_payload(0x54F + i)
516+
with self.assertRaisesRegex(InvalidBSON, "invalid") as ctx:
517+
bson.decode(payload)
518+
self.assertNotIn("fieldname", str(ctx.exception))
519+
492520
def test_unknown_type(self):
493521
# Repr value differs with major python version
494522
part = "type {!r} for fieldname 'foo'".format(b"\x14")

0 commit comments

Comments
 (0)