-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Closed
Description
I discovered that the function cJSON_SetValuestring does not perform any control for string overlapping.
The problem is here :
if (strlen(valuestring) <= strlen(object->valuestring))
{
strcpy(object->valuestring, valuestring);
return object->valuestring;
}strcpy requires that the two strings do not overlap .
In the following case, the second cJSON_SetValuestring tries to strcpy on the same string.
#include <cjson/cJSON.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char** argv) {
cJSON *obj;
cJSON *obj_dup;
char* str;
obj = cJSON_Parse("\"fooz\"");
obj_dup = cJSON_Duplicate(obj, 1);
if (obj_dup == 0) return 0;
str = cJSON_SetValuestring(obj_dup, "beeez");
cJSON_SetValuestring(obj_dup, str); // ASan raises error here
return 0;
}A simple solution to this error is to add an overlapping check on the pointers, something like:
v1_len = strlen(valuestring);
v2_len = strlen(object->valuestring);
/* [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */
if (v1_len <= v2_len && ( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring ))
/* if (strlen(valuestring) <= strlen(object->valuestring)) */
{
strcpy(object->valuestring, valuestring);
return object->valuestring;
}Let me know if you agree with the problem and the solution. I can quickly prepare a PR.
Metadata
Metadata
Assignees
Labels
No labels