PYTHON-5756 - Fix BSON Binary type length bug (#2790)

This commit is contained in:
Noah Stapp 2026-05-07 15:23:00 -04:00 committed by GitHub
parent b6bac45c7e
commit f145c7db94
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 1 deletions

View File

@ -2281,7 +2281,7 @@ static PyObject* get_value(PyObject* self, PyObject* name, const char* buffer,
}
memcpy(&length, buffer + *position, 4);
length = BSON_UINT32_FROM_LE(length);
if (max < length) {
if (max - 5 < length) { // Account for 5-byte header. max >= 5 guaranteed above
goto invalid;
}

View File

@ -1269,6 +1269,22 @@ class TestBSON(unittest.TestCase):
encode(doc)
self.assertEqual(cm.exception.document, doc)
def test_binary_length_accounts_for_header(self):
size = 20
binary_length = 12 # 5 more than the actual 7 bytes
payload = b""
payload += struct.pack("<i", size) # document size
payload += b"\x05" # type = Binary
payload += b"a\x00" # key "a"
payload += struct.pack("<I", binary_length) # Binary length (inflated)
payload += b"\x00" # subtype 0
payload += b"\x41" * 7 # value
payload += b"\x00" # EOO
with self.assertRaises(InvalidBSON):
decode(payload)
class TestCodecOptions(unittest.TestCase):
def test_document_class(self):