Skip to content

Commit

Permalink
Merge pull request #326 from neumannt/json-crash
Browse files Browse the repository at this point in the history
defend against excessive recursion in json::load
  • Loading branch information
The-EDev authored Jan 29, 2022
2 parents 2807953 + 9689688 commit 9f64a7b
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions include/crow/json.h
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,9 @@ namespace crow

inline rvalue load_nocopy_internal(char* data, size_t size)
{
// Defend against excessive recursion
static constexpr unsigned max_depth = 10000;

//static const char* escaped = "\"\\/\b\f\n\r\t";
struct Parser
{
Expand Down Expand Up @@ -902,10 +905,10 @@ namespace crow
return {};
}

rvalue decode_list()
rvalue decode_list(unsigned depth)
{
rvalue ret(type::List);
if (crow_json_unlikely(!consume('[')))
if (crow_json_unlikely(!consume('[')) || crow_json_unlikely(depth > max_depth))
{
ret.set_error();
return ret;
Expand All @@ -919,7 +922,7 @@ namespace crow

while (1)
{
auto v = decode_value();
auto v = decode_value(depth + 1);
if (crow_json_unlikely(!v))
{
ret.set_error();
Expand Down Expand Up @@ -1068,14 +1071,15 @@ namespace crow
return {};
}

rvalue decode_value()

rvalue decode_value(unsigned depth)
{
switch (*data)
{
case '[':
return decode_list();
return decode_list(depth + 1);
case '{':
return decode_object();
return decode_object(depth + 1);
case '"':
return decode_string();
case 't':
Expand Down Expand Up @@ -1122,10 +1126,10 @@ namespace crow
return {};
}

rvalue decode_object()
rvalue decode_object(unsigned depth)
{
rvalue ret(type::Object);
if (crow_json_unlikely(!consume('{')))
if (crow_json_unlikely(!consume('{')) || crow_json_unlikely(depth > max_depth))
{
ret.set_error();
return ret;
Expand Down Expand Up @@ -1160,7 +1164,7 @@ namespace crow
auto key = t.s();

ws_skip();
auto v = decode_value();
auto v = decode_value(depth + 1);
if (crow_json_unlikely(!v))
{
ret.set_error();
Expand Down Expand Up @@ -1188,7 +1192,7 @@ namespace crow
rvalue parse()
{
ws_skip();
auto ret = decode_value(); // or decode object?
auto ret = decode_value(0); // or decode object?
ws_skip();
if (ret && *data != '\0')
ret.set_error();
Expand Down

0 comments on commit 9f64a7b

Please sign in to comment.