Skip to content

Commit

Permalink
PYTHON-4323 Add regression test for out-of-bounds read when decoding …
Browse files Browse the repository at this point in the history
…invalid bson (#1695)
  • Loading branch information
ShaneHarvey authored Jun 20, 2024
1 parent 255d190 commit ed7a586
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions test/test_bson.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import os
import pickle
import re
import struct
import sys
import tempfile
import uuid
Expand Down Expand Up @@ -489,6 +490,33 @@ def test_basic_encode(self):
b"\x00",
)

def test_bad_code(self):
# Assert that decoding invalid Code with scope does not include a field name.
def generate_payload(length: int) -> bytes:
string_size = length - 0x1E

return bytes.fromhex(
struct.pack("<I", length).hex() # payload size
+ "0f" # type "code with scope"
+ "3100" # key (cstring)
+ "0a000000" # c_w_s_size
+ "04000000" # code_size
+ "41004200" # code (cstring)
+ "feffffff" # scope_size
+ "02" # type "string"
+ "3200" # key (cstring)
+ struct.pack("<I", string_size).hex() # string size
+ "00" * string_size # value (cstring)
# next bytes is a field name for type \x00
# type \x00 is invalid so bson throws an exception
)

for i in range(100):
payload = generate_payload(0x54F + i)
with self.assertRaisesRegex(InvalidBSON, "invalid") as ctx:
bson.decode(payload)
self.assertNotIn("fieldname", str(ctx.exception))

def test_unknown_type(self):
# Repr value differs with major python version
part = "type {!r} for fieldname 'foo'".format(b"\x14")
Expand Down

0 comments on commit ed7a586

Please sign in to comment.