Skip to content

Fix use-after-free when json_encode() re-enters an ArrayObject - #22921

Open
iliaal wants to merge 1 commit into
php:PHP-8.4from
iliaal:fix/json-arrayobject-reentrant-uaf
Open

Fix use-after-free when json_encode() re-enters an ArrayObject#22921
iliaal wants to merge 1 commit into
php:PHP-8.4from
iliaal:fix/json-arrayobject-reentrant-uaf

Conversation

@iliaal

@iliaal iliaal commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

json_encode() borrows an ArrayObject's storage table for the length of the encode and then runs userland through JsonSerializable::jsonSerialize() and property hooks. spl_array_get_hash_table_ptr() hands that same table back to the write paths, so an insert from the callback grows it and frees the buckets the encoder is iterating; valgrind reports invalid reads in php_json_encode_array() for the array-backed ArrayObject, ArrayIterator and self-backed cases in the test. The object-backed branch of that function already separates when the table is borrowed, so this gives the other two branches the same treatment. Encoding cost is unchanged: the separation only fires while a borrow is outstanding, and the refcount is 1 the rest of the time.

#20725 proposes the same SEPARATE_ARRAY call at the write sites instead. That placement leaves the by-reference auto-vivify path through spl_array_get_dimension_ptr() unprotected, which valgrind still reports as an invalid read, and it does not reach the self-backed case.

@iliaal
iliaal requested a review from Girgias as a code owner July 29, 2026 12:56
spl_array_get_hash_table_ptr() hands out a pointer into the ArrayObject
storage without checking whether anything else holds a reference to it.
json_encode() takes such a reference for the length of the encode and
then runs userland through JsonSerializable::jsonSerialize() and
property hooks, so an insert from there grows the table and frees the
buckets the encoder is iterating. Separate the array-backed and
self-backed cases the way the object-backed case in the same function
already does.

Closes phpGH-22921
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant