From 0b3fcd7b1bd075d9d4c58b4e24dc1ef46bce0d3e Mon Sep 17 00:00:00 2001 From: Jorg Sowa Date: Thu, 26 Nov 2026 15:32:57 +0100 Subject: [PATCH] Fix integer overflow in mb_convert_variables() string count Counting the strings to detect among multiple encodings used an unsigned int. The same array counted once per appearance (the recursion guard is cleared per array) could push the count to 2^32, wrapping it to 0 and under-allocating the buffers the collection pass writes into, causing a heap out-of-bounds write. Count in uint64_t so the total cannot wrap, and reject a count that would overflow the buffer allocation before allocating, matching the array_merge() element-count fix. --- NEWS | 2 ++ ext/mbstring/mbstring.c | 15 ++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/NEWS b/NEWS index 495a49d6aa1a..5895e477d7af 100644 --- a/NEWS +++ b/NEWS @@ -115,6 +115,8 @@ PHP NEWS deeply nested arrays. (Eyüp Can Akman) . Fixed the JIT freeing the string returned by mb_encode_mimeheader() or mb_output_handler() while it is still in use. (Ilia Alshanetsky) + . Fixed integer overflow in the string count of mb_convert_variables() + leading to a heap out-of-bounds write. (Jorg Sowa) - Opcache: . Fixed bug GH-24801 (JIT: SIGFPE in ir_fold MUL_OV constant folding). diff --git a/ext/mbstring/mbstring.c b/ext/mbstring/mbstring.c index 3df3367de07c..604939672a02 100644 --- a/ext/mbstring/mbstring.c +++ b/ext/mbstring/mbstring.c @@ -3761,9 +3761,9 @@ PHP_FUNCTION(mb_convert_kana) RETVAL_STR(jp_kana_convert(str, enc, opt)); } -static unsigned int mb_recursive_count_strings(zval *var) +static uint64_t mb_recursive_count_strings(zval *var) { - unsigned int count = 0; + uint64_t count = 0; ZVAL_DEREF(var); if (mb_check_stack_limit()) { @@ -3796,7 +3796,7 @@ static unsigned int mb_recursive_count_strings(zval *var) return count; } -static bool mb_recursive_find_strings(zval *var, const unsigned char **val_list, size_t *len_list, unsigned int *count) +static bool mb_recursive_find_strings(zval *var, const unsigned char **val_list, size_t *len_list, size_t *count) { ZVAL_DEREF(var); @@ -3968,14 +3968,19 @@ PHP_FUNCTION(mb_convert_variables) from_encoding = *elist; } else { /* auto detect */ - unsigned int num = 0; + uint64_t num = 0; for (size_t n = 0; n < argc; n++) { zval *zv = &args[n]; num += mb_recursive_count_strings(zv); } + if (UNEXPECTED(num > SIZE_MAX / sizeof(char *))) { + efree(ZEND_VOIDP(elist)); + php_error_docref(NULL, E_WARNING, "Input contains too many strings"); + RETURN_FALSE; + } const unsigned char **val_list = (const unsigned char**)ecalloc(num, sizeof(char *)); size_t *len_list = (size_t*)ecalloc(num, sizeof(size_t)); - unsigned int i = 0; + size_t i = 0; for (size_t n = 0; n < argc; n++) { zval *zv = &args[n]; if (mb_recursive_find_strings(zv, val_list, len_list, &i)) {