Skip to content

no overlap control in cJSON_SetValuestring #881

@tregua87

Description

@tregua87

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions