Skip to content

Commit

Permalink
🐛 fixed a bug parsing BSON strings #1320
Browse files Browse the repository at this point in the history
  • Loading branch information
nlohmann committed Oct 28, 2018
1 parent 24946f6 commit f0c1459
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion include/nlohmann/detail/input/binary_reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<typename NumberType>
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<NumberType>(1), result) and get() != std::char_traits<char>::eof();
}

Expand Down
6 changes: 6 additions & 0 deletions single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6532,6 +6532,12 @@ class binary_reader
template<typename NumberType>
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<NumberType>(1), result) and get() != std::char_traits<char>::eof();
}

Expand Down
14 changes: 14 additions & 0 deletions test/src/unit-bson.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint8_t> 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")
Expand Down

0 comments on commit f0c1459

Please sign in to comment.