Skip to content

Commit 3a3d7ba

Browse files
cosmo0920edsiper
authored andcommitted
json: guard mutable JSON render recursion depth
Signed-off-by: Hiroshi Hatake <hiroshi@chronosphere.io>
1 parent bd7fd94 commit 3a3d7ba

1 file changed

Lines changed: 25 additions & 4 deletions

File tree

src/flb_json.c

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -505,14 +505,25 @@ static yyjson_mut_val *msgpack_to_yyjson_mut(yyjson_mut_doc *document,
505505
}
506506
}
507507

508-
static yyjson_mut_val *mutable_to_yyjson_mut(yyjson_mut_doc *document,
509-
struct flb_json_mut_val *value)
508+
/*
509+
* This limit prevents stack overflows in case mutable documents contain
510+
* unexpectedly deep nesting or structural cycles.
511+
*/
512+
#define FLB_JSON_MUT_RENDER_MAX_DEPTH 1024
513+
514+
static yyjson_mut_val *mutable_to_yyjson_mut_internal(yyjson_mut_doc *document,
515+
struct flb_json_mut_val *value,
516+
size_t depth)
510517
{
511518
struct flb_json_mut_kv *kv_entry;
512519
struct flb_json_mut_entry *array_entry;
513520
yyjson_mut_val *result;
514521
yyjson_mut_val *item;
515522

523+
if (depth > FLB_JSON_MUT_RENDER_MAX_DEPTH) {
524+
return NULL;
525+
}
526+
516527
switch (value->type) {
517528
case FLB_JSON_MUT_OBJECT:
518529
result = yyjson_mut_obj(document);
@@ -523,7 +534,9 @@ static yyjson_mut_val *mutable_to_yyjson_mut(yyjson_mut_doc *document,
523534
for (kv_entry = value->data.object.head;
524535
kv_entry != NULL;
525536
kv_entry = kv_entry->next) {
526-
item = mutable_to_yyjson_mut(document, kv_entry->value);
537+
item = mutable_to_yyjson_mut_internal(document,
538+
kv_entry->value,
539+
depth + 1);
527540
if (item == NULL) {
528541
return NULL;
529542
}
@@ -545,7 +558,9 @@ static yyjson_mut_val *mutable_to_yyjson_mut(yyjson_mut_doc *document,
545558
for (array_entry = value->data.array.head;
546559
array_entry != NULL;
547560
array_entry = array_entry->next) {
548-
item = mutable_to_yyjson_mut(document, array_entry->value);
561+
item = mutable_to_yyjson_mut_internal(document,
562+
array_entry->value,
563+
depth + 1);
549564
if (item == NULL || !yyjson_mut_arr_add_val(result, item)) {
550565
return NULL;
551566
}
@@ -569,6 +584,12 @@ static yyjson_mut_val *mutable_to_yyjson_mut(yyjson_mut_doc *document,
569584
}
570585
}
571586

587+
static yyjson_mut_val *mutable_to_yyjson_mut(yyjson_mut_doc *document,
588+
struct flb_json_mut_val *value)
589+
{
590+
return mutable_to_yyjson_mut_internal(document, value, 0);
591+
}
592+
572593
static char *render_msgpack_document_yyjson(struct flb_json_doc *document,
573594
size_t *length,
574595
int pretty)

0 commit comments

Comments
 (0)