From c4bb07552e642f8e3b3a766935e94934ab136310 Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+nielsdos@users.noreply.github.com> Date: Thu, 3 Oct 2024 20:16:01 +0200 Subject: [PATCH] Fix GH-16184: UBSan address overflowed in ext/pcre/php_pcre.c libpcre2 can return the special value -1 for a non-match. In this case we get pointer overflow, although it doesn't matter in practice because the pointer will be in bounds and the copy length will be 0. Still, we should fix the UBSAN warning. Closes GH-16205. --- NEWS | 4 +++- ext/pcre/php_pcre.c | 8 +++++--- ext/pcre/tests/gh16184.phpt | 13 +++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 ext/pcre/tests/gh16184.phpt diff --git a/NEWS b/NEWS index 1fa196547d7..19b6642ca1a 100644 --- a/NEWS +++ b/NEWS @@ -38,7 +38,9 @@ PHP NEWS . Fixed stub for openssl_csr_new. (Jakub Zelenka) - PCRE: - . Fixed GH-16189 (underflow on offset argument). (David Carlier) + . Fixed bug GH-16189 (underflow on offset argument). (David Carlier) + . Fixed bug GH-16184 (UBSan address overflowed in ext/pcre/php_pcre.c). + (nielsdos) - PHPDBG: . Fixed bug GH-15901 (phpdbg: Assertion failure on i funcs). (cmb) diff --git a/ext/pcre/php_pcre.c b/ext/pcre/php_pcre.c index 4511d611d7a..4c1d8db47c1 100644 --- a/ext/pcre/php_pcre.c +++ b/ext/pcre/php_pcre.c @@ -1747,9 +1747,11 @@ matched: } if (preg_get_backref(&walk, &backref)) { if (backref < count) { - match_len = offsets[(backref<<1)+1] - offsets[backref<<1]; - memcpy(walkbuf, subject + offsets[backref<<1], match_len); - walkbuf += match_len; + if (offsets[backref<<1] < SIZE_MAX) { + match_len = offsets[(backref<<1)+1] - offsets[backref<<1]; + memcpy(walkbuf, subject + offsets[backref<<1], match_len); + walkbuf += match_len; + } } continue; } diff --git a/ext/pcre/tests/gh16184.phpt b/ext/pcre/tests/gh16184.phpt new file mode 100644 index 00000000000..ba915d19af7 --- /dev/null +++ b/ext/pcre/tests/gh16184.phpt @@ -0,0 +1,13 @@ +--TEST-- +GH-16184 (UBSan address overflowed in ext/pcre/php_pcre.c) +--CREDITS-- +YuanchengJiang +--FILE-- + +--EXPECT-- +This test a string. It contains numbers * to 0* to 9* test well test parentheses and some other things*