Skip to content

Commit 954d61e

Browse files
committed
Fix DaveGamble#189, ensure returns an invalid pointer
If realloc returns NULL, ensure didn't abort but returned printbuffer.offset instead. If an attacker can control printbuffer.offset and also make realloc fail at just the right moment, this would make cJSON potentially write at an arbitrary memory address.
1 parent ecdff78 commit 954d61e

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

‎cJSON.c‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,14 @@ static unsigned char* ensure(printbuffer * const p, size_t needed)
377377
{
378378
/* reallocate with realloc if available */
379379
newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
380+
if (newbuffer == NULL)
381+
{
382+
p->hooks.deallocate(p->buffer);
383+
p->length = 0;
384+
p->buffer = NULL;
385+
386+
return NULL;
387+
}
380388
}
381389
else
382390
{

‎tests/misc_tests.c‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,22 @@ static void cjson_functions_shouldnt_crash_with_null_pointers(void)
410410
cJSON_Delete(item);
411411
}
412412

413+
static void *failing_realloc(void *pointer, size_t size)
414+
{
415+
(void)size;
416+
(void)pointer;
417+
return NULL;
418+
}
419+
420+
static void ensure_should_fail_on_failed_realloc(void)
421+
{
422+
printbuffer buffer = {NULL, 10, 0, 0, false, false, {&malloc, &free, &failing_realloc}};
423+
buffer.buffer = (unsigned char*)malloc(100);
424+
TEST_ASSERT_NOT_NULL(buffer.buffer);
425+
426+
TEST_ASSERT_NULL_MESSAGE(ensure(&buffer, 200), "Ensure didn't fail with failing realloc.");
427+
}
428+
413429
int main(void)
414430
{
415431
UNITY_BEGIN();
@@ -425,6 +441,6 @@ int main(void)
425441
RUN_TEST(cjson_replace_item_via_pointer_should_replace_items);
426442
RUN_TEST(cjson_replace_item_in_object_should_preserve_name);
427443
RUN_TEST(cjson_functions_shouldnt_crash_with_null_pointers);
428-
444+
RUN_TEST(ensure_should_fail_on_failed_realloc);
429445
return UNITY_END();
430446
}

0 commit comments

Comments
 (0)