diff --git a/src/common/type/json.c b/src/common/type/json.c index d82cedc81..53b18b32e 100644 --- a/src/common/type/json.c +++ b/src/common/type/json.c @@ -11,8 +11,14 @@ Convert JSON to/from KeyValue #include "common/debug.h" #include "common/io/io.h" #include "common/log.h" +#include "common/macro.h" #include "common/type/json.h" +/*********************************************************************************************************************************** +Maximum depth of nested containers when reading +***********************************************************************************************************************************/ +#define JSON_READ_DEPTH_MAX 32 + /*********************************************************************************************************************************** Object types ***********************************************************************************************************************************/ @@ -322,7 +328,12 @@ jsonReadPush(JsonRead *const this, const JsonType type, const bool key) // Add container to the stack if (jsonTypeContainer(type)) + { + if (lstSize(this->stack) >= JSON_READ_DEPTH_MAX) + THROW_FMT(JsonFormatError, "maximum depth of " STRINGIFY(JSON_READ_DEPTH_MAX) " exceeded at: %s", this->json); + lstAdd(this->stack, &(JsonReadStack){.type = type}); + } FUNCTION_TEST_RETURN_VOID(); } diff --git a/test/src/module/common/type/jsonTest.c b/test/src/module/common/type/jsonTest.c index 9f1d65e54..1c07900cf 100644 --- a/test/src/module/common/type/jsonTest.c +++ b/test/src/module/common/type/jsonTest.c @@ -61,6 +61,21 @@ testRun(void) TEST_ERROR(jsonReadStr(jsonReadNew(STRDEF("\"\\u1111"))), JsonFormatError, "unable to decode at: \\u1111"); + // ------------------------------------------------------------------------------------------------------------------------- + TEST_TITLE("error on maximum depth"); + + String *const depthArray = strNew(); + String *const depthObject = strNew(); + + for (unsigned int depthIdx = 0; depthIdx < 32; depthIdx++) + { + strCatChr(depthArray, '['); + strCatZ(depthObject, "{\"a\":"); + } + + TEST_ERROR(jsonToVar(strNewFmt("%s{", strZ(depthArray))), JsonFormatError, "maximum depth of 32 exceeded at: {"); + TEST_ERROR(jsonValidate(strNewFmt("%s[", strZ(depthObject))), JsonFormatError, "maximum depth of 32 exceeded at: ["); + // ------------------------------------------------------------------------------------------------------------------------- TEST_TITLE("error on invalid escape");