diff --git a/include/nlohmann/detail/input/binary_reader.hpp b/include/nlohmann/detail/input/binary_reader.hpp index ed2d66fd..403a4d01 100644 --- a/include/nlohmann/detail/input/binary_reader.hpp +++ b/include/nlohmann/detail/input/binary_reader.hpp @@ -186,12 +186,18 @@ class binary_reader @param[in, out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len - @pre len > 0 + @pre len >= 1 @return `true` if the string was successfully parsed */ template bool get_bson_string(const NumberType len, string_t& result) { + if (JSON_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"))); + } + return get_string(input_format_t::bson, len - static_cast(1), result) and get() != std::char_traits::eof(); } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 058cc093..e758206c 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -6532,6 +6532,12 @@ class binary_reader template bool get_bson_string(const NumberType len, string_t& result) { + if (JSON_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"))); + } + return get_string(input_format_t::bson, len - static_cast(1), result) and get() != std::char_traits::eof(); } diff --git a/test/src/unit-bson.cpp b/test/src/unit-bson.cpp index d88a03e2..36dacb46 100644 --- a/test/src/unit-bson.cpp +++ b/test/src/unit-bson.cpp @@ -100,6 +100,20 @@ TEST_CASE("BSON") CHECK_THROWS_WITH(json::to_bson(j), "[json.exception.out_of_range.409] BSON key cannot contain code point U+0000 (at byte 2)"); } + SECTION("string length must be at least 1") + { + // from https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=11175 + std::vector v = + { + 0x20, 0x20, 0x20, 0x20, + 0x02, + 0x00, + 0x00, 0x00, 0x00, 0x80 + }; + CHECK_THROWS_AS(json::from_bson(v), json::parse_error&); + CHECK_THROWS_WITH(json::from_bson(v), "[json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648"); + } + SECTION("objects") { SECTION("empty object")