From 00c76717b4315381a1878cca2f10d08544634bf2 Mon Sep 17 00:00:00 2001 From: Alanscut Date: Mon, 29 Apr 2024 13:29:12 +0800 Subject: [PATCH] CVE-2024-31755 Fix NULL valuestring problem in cJSON_SetValuestring. This fixes #839 and CVE-2024-31755 Related issue #845 --- cJSON.c | 7 +++++++ tests/misc_tests.c | 1 + 2 files changed, 8 insertions(+) diff --git a/cJSON.c b/cJSON.c index 7543078..349ebbd 100644 --- a/cJSON.c +++ b/cJSON.c @@ -410,6 +410,13 @@ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) { return NULL; } + /* NULL valuestring causes error with strlen and should be treated separately */ + if (valuestring == NULL) + { + cJSON_free(object->valuestring); + object->valuestring = NULL; + return NULL; + } if (strlen(valuestring) <= strlen(object->valuestring)) { strcpy(object->valuestring, valuestring); diff --git a/tests/misc_tests.c b/tests/misc_tests.c index 8031c0d..c11a823 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -445,6 +445,7 @@ static void cjson_functions_should_not_crash_with_null_pointers(void) TEST_ASSERT_FALSE(cJSON_Compare(NULL, item, false)); TEST_ASSERT_NULL(cJSON_SetValuestring(NULL, "test")); TEST_ASSERT_NULL(cJSON_SetValuestring(corruptedString, "test")); + TEST_ASSERT_NULL(cJSON_SetValuestring(item, NULL)); cJSON_Minify(NULL); /* skipped because it is only used via a macro that checks for NULL */ /* cJSON_SetNumberHelper(NULL, 0); */ -- 2.27.0