armink / struct2json

A fast convert library between the JSON and C structure. Implement structure serialization and deserialization for C. | C 结构体与 JSON 快速互转库,快速实现 C 结构体的序列化及反序列化
MIT License
680 stars 293 forks source link

An unsafe operation is found in the S2J_STRUCT_GET_string_ELEMENT function #13

Closed marckwei closed 3 years ago

marckwei commented 3 years ago

struct2json

Vulnerability Analysis

An unsafe operation is found in the S2J_STRUCT_GET_string_ELEMENTfunction. The strcpy function is used to copy JSON->value to the struct, which may cause overflow when JSON->value is longer than structure defined array size.

img

POC

#include "s2j.h" 
#include <stdint.h> 
#include <stdio.h> 

typedef struct { 
  char name[8]; 
} Hometown; 

static void *json_to_struct(cJSON* json_obj) { 
  /* create Hometown structure object */ 
  s2j_create_struct_obj(struct_hometown, Hometown); 

  /* deserialize data to Hometown structure object. */ 
  s2j_struct_get_basic_element(struct_hometown, json_obj,string, name); 
  return struct_hometown; 
} 

int main(void) { 
  cJSON * json=NULL; 

  json=cJSON_CreateObject(); 

  cJSON_AddStringToObject(json, "name", "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"); 

  Hometown * test=json_to_struct(json); 

  printf("that\'s fine!%zu",sizeof(test)); 

  return 0; 
}

Run:

img

Suggestion

Use strncpy instead of strcpy to control the length of JSON->value

#define S2J_STRUCT_GET_string_ELEMENT(to_struct, from_json, _element) \ 
  json_temp = cJSON_GetObjectItem(from_json, #_element); \ 
  if (json_temp) strncpy((to_struct)->_element, json_temp->valuestring,sizeof((to_struct)->_element));

After modification:

img

libradoge commented 3 years ago

字符串的话,是否要修改成:sizeof是否要-1:

#define S2J_STRUCT_GET_string_ELEMENT(to_struct, from_json, _element) \ 
  json_temp = cJSON_GetObjectItem(from_json, #_element); \ 
  if (json_temp) strncpy((to_struct)->_element, json_temp->valuestring,sizeof((to_struct)->_element) -1 );
abergmann commented 3 years ago

CVE-2020-29203 was assigned to this issue.

armink commented 3 years ago

Thanks for your feedback, can you submit a PR for it?

libradoge commented 3 years ago

Thanks for your feedback, can you submit a PR for it?

It's my first time to submit a PR, so please check my work carefully...And thank you for giving me this chance!

armink commented 3 years ago

Thanks for your feedback, can you submit a PR for it?

It's my first time to submit a PR, so please check my work carefully...And thank you for giving me this chance!

Good job.

Thank you for your contribution, PR has been merged