Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no overlap control in cJSON_SetValuestring #881

Closed
tregua87 opened this issue Aug 9, 2024 · 0 comments · Fixed by #885
Closed

no overlap control in cJSON_SetValuestring #881

tregua87 opened this issue Aug 9, 2024 · 0 comments · Fixed by #885

Comments

@tregua87
Copy link

tregua87 commented Aug 9, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant