From 029343dd8512fceaf24670e331ac91d76390d9e3 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Mon, 4 May 2026 16:47:37 -0400 Subject: [PATCH 1/4] PYTHON-5756 - Fix BSON Binary type length bug --- bson/_cbsonmodule.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bson/_cbsonmodule.c b/bson/_cbsonmodule.c index 034490f558..38c01238ac 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 < length + 5) { // Account for 5 byte header goto invalid; } From 1e2526b6ce938e28943edc4c0250e04109e512a0 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Mon, 4 May 2026 17:09:35 -0400 Subject: [PATCH 2/4] Add test --- test/test_bson.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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(" Date: Tue, 5 May 2026 09:39:21 -0400 Subject: [PATCH 3/4] Remove overflow chance --- bson/_cbsonmodule.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bson/_cbsonmodule.c b/bson/_cbsonmodule.c index 38c01238ac..c4848af32f 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 + 5) { // Account for 5 byte header + if (length > max - 5) { // Account for 5-byte header. max >= 5 guaranteed above goto invalid; } From 22854544d60410770d0a43bc2ccdf36c93fbf3a9 Mon Sep 17 00:00:00 2001 From: Noah Stapp Date: Thu, 7 May 2026 11:03:59 -0400 Subject: [PATCH 4/4] Reduce code churn --- bson/_cbsonmodule.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bson/_cbsonmodule.c b/bson/_cbsonmodule.c index c4848af32f..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 (length > max - 5) { // Account for 5-byte header. max >= 5 guaranteed above + if (max - 5 < length) { // Account for 5-byte header. max >= 5 guaranteed above goto invalid; }