diff --git a/cJSON.c b/cJSON.c index cac1164b..27402d1f 100644 --- a/cJSON.c +++ b/cJSON.c @@ -403,6 +403,8 @@ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) { char *copy = NULL; + size_t v1_len; + size_t v2_len; /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) { @@ -413,8 +415,17 @@ CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) { return NULL; } - if (strlen(valuestring) <= strlen(object->valuestring)) + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } strcpy(object->valuestring, valuestring); return object->valuestring; } diff --git a/tests/misc_tests.c b/tests/misc_tests.c index ba3e003e..c558ac0d 100644 --- a/tests/misc_tests.c +++ b/tests/misc_tests.c @@ -456,6 +456,24 @@ static void cjson_functions_should_not_crash_with_null_pointers(void) cJSON_Delete(item); } +static void cjson_set_valuestring_should_return_null_if_strings_overlap(void) +{ + cJSON *obj; + char* str; + char* str2; + + obj = cJSON_Parse("\"foo0z\""); + + str = cJSON_SetValuestring(obj, "abcde"); + str += 1; + /* The string passed to strcpy overlap which is not allowed.*/ + str2 = cJSON_SetValuestring(obj, str); + /* If it overlaps, the string will be messed up.*/ + TEST_ASSERT_TRUE(strcmp(str, "bcde") == 0); + TEST_ASSERT_NULL(str2); + cJSON_Delete(obj); +} + static void *CJSON_CDECL failing_realloc(void *pointer, size_t size) { (void)size; @@ -749,6 +767,7 @@ int CJSON_CDECL main(void) RUN_TEST(cjson_replace_item_via_pointer_should_replace_items); RUN_TEST(cjson_replace_item_in_object_should_preserve_name); RUN_TEST(cjson_functions_should_not_crash_with_null_pointers); + RUN_TEST(cjson_set_valuestring_should_return_null_if_strings_overlap); RUN_TEST(ensure_should_fail_on_failed_realloc); RUN_TEST(skip_utf8_bom_should_skip_bom); RUN_TEST(skip_utf8_bom_should_not_skip_bom_if_not_at_beginning);