Skip to content

replace_item_in_object: fix use-after-free when key aliases item name - #1083

Open
iliasabk wants to merge 1 commit into
DaveGamble:masterfrom
iliasabk:fix/replace-item-uaf
Open

iliasabk wants to merge 1 commit into
DaveGamble:masterfrom
iliasabk:fix/replace-item-uaf

Conversation

@iliasabk

Copy link
Copy Markdown

Fixes #1081 — heap-use-after-free in cJSON_ReplaceItemInObject() reported with full PoC + ASan trace (CWE-416).

Root cause

replace_item_in_object() freed replacement->string before duplicating the string argument. When the caller passes the item's own name as the key — e.g. moving an item between objects under the same name — cJSON_strdup() read the just-freed buffer. Without ASan it silently fails the replace (ok=0, object unchanged); under ASan it's a clean heap-UAF read in strlencJSON_strdup.

cJSON *item = cJSON_DetachItemFromObject(src, "timeout");
cJSON_ReplaceItemInObject(dst, item->string, item);  /* item->string dangles mid-call */

Fix

Duplicate the key into new_key first, then release the old name and assign — the same ordering fix that 22a7d04 applied to add_item_to_object() for #248. new_key is also used for the object lookup, since the original string pointer may dangle after the free.

Side effect: a failed strdup no longer leaves replacement->string clobbered to NULL — the item keeps its old name on OOM.

Verification

  • Reproduced the exact issue trace under -fsanitize=address on master: heap-use-after-free … cJSON_strdup cJSON.c:198 ← replace_item_in_object cJSON.c:2439
  • Patched build: ok=1 dst={"timeout":30}, zero ASan reports
  • ctest: 19/19 pass under ASan

cJSON_ReplaceItemInObject() freed replacement->string before
duplicating the string argument. When the caller passes the
item's own name as the key (e.g. moving an item between objects
under the same name), cJSON_strdup() read the freed buffer.

Duplicate the key into new_key first, then release the old name —
same ordering fix as 22a7d04 applied to add_item_to_object().
Also use new_key for the object lookup, since the original
pointer may dangle after the free.

Fixes DaveGamble#1081
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 this pull request may close these issues.

Use-after-free in cJSON_ReplaceItemInObject when the key is the item's own name

1 participant