Skip to content

Commit f145c7d

Browse files
authored
PYTHON-5756 - Fix BSON Binary type length bug (#2790)
1 parent b6bac45 commit f145c7d

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

bson/_cbsonmodule.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2281,7 +2281,7 @@ static PyObject* get_value(PyObject* self, PyObject* name, const char* buffer,
22812281
}
22822282
memcpy(&length, buffer + *position, 4);
22832283
length = BSON_UINT32_FROM_LE(length);
2284-
if (max < length) {
2284+
if (max - 5 < length) { // Account for 5-byte header. max >= 5 guaranteed above
22852285
goto invalid;
22862286
}
22872287

test/test_bson.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,22 @@ def __repr__(self):
12691269
encode(doc)
12701270
self.assertEqual(cm.exception.document, doc)
12711271

1272+
def test_binary_length_accounts_for_header(self):
1273+
size = 20
1274+
binary_length = 12 # 5 more than the actual 7 bytes
1275+
1276+
payload = b""
1277+
payload += struct.pack("<i", size) # document size
1278+
payload += b"\x05" # type = Binary
1279+
payload += b"a\x00" # key "a"
1280+
payload += struct.pack("<I", binary_length) # Binary length (inflated)
1281+
payload += b"\x00" # subtype 0
1282+
payload += b"\x41" * 7 # value
1283+
payload += b"\x00" # EOO
1284+
1285+
with self.assertRaises(InvalidBSON):
1286+
decode(payload)
1287+
12721288

12731289
class TestCodecOptions(unittest.TestCase):
12741290
def test_document_class(self):

0 commit comments

Comments
 (0)