Skip to content

Commit b2890c8

Browse files
fix: prevent NULL pointer dereference in cJSON_SetNumberHelper (#991)
Add NULL check at the beginning of cJSON_SetNumberHelper to prevent segmentation fault when called with NULL object pointer. The function now returns NAN (Not-a-Number) when object is NULL, consistent with error handling patterns in other cJSON functions. This fixes a Denial of Service vulnerability (CWE-476) where an attacker could crash applications using the cJSON library by triggering this function with a NULL pointer. Changes: - cJSON.c: Add NULL check in cJSON_SetNumberHelper - tests/misc_tests.c: Add test case and math.h include Security: Fixes NULL pointer dereference vulnerability
1 parent a3f3d6c commit b2890c8

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

cJSON.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,11 @@ static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_bu
410410
/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
411411
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
412412
{
413+
if (object == NULL)
414+
{
415+
return (double)NAN;
416+
}
417+
413418
if (number >= INT_MAX)
414419
{
415420
object->valueint = INT_MAX;

tests/misc_tests.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#include <stdio.h>
2424
#include <stdlib.h>
2525
#include <string.h>
26+
#include <math.h>
2627

2728
#include "unity/examples/unity_config.h"
2829
#include "unity/src/unity.h"
@@ -478,8 +479,8 @@ static void cjson_functions_should_not_crash_with_null_pointers(void)
478479
TEST_ASSERT_NULL(cJSON_SetValuestring(corruptedString, "test"));
479480
TEST_ASSERT_NULL(cJSON_SetValuestring(item, NULL));
480481
cJSON_Minify(NULL);
481-
/* skipped because it is only used via a macro that checks for NULL */
482-
/* cJSON_SetNumberHelper(NULL, 0); */
482+
/* cJSON_SetNumberHelper should handle NULL gracefully */
483+
TEST_ASSERT_TRUE(isnan(cJSON_SetNumberHelper(NULL, 0)));
483484

484485
/* restore corrupted item2 to delete it */
485486
item2->prev = originalPrev;

0 commit comments

Comments
 (0)