diff --git a/bson/_cbsonmodule.c b/bson/_cbsonmodule.c index 034490f558..a87407851b 100644 --- a/bson/_cbsonmodule.c +++ b/bson/_cbsonmodule.c @@ -2155,7 +2155,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; } diff --git a/test/test_bson.py b/test/test_bson.py index ffc02965fb..ae1807e5fc 100644 --- a/test/test_bson.py +++ b/test/test_bson.py @@ -1269,6 +1269,22 @@ def __repr__(self): 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("