Skip to content

Commit 712fc54

Browse files
committed
Fix #74604: Out of bounds in php_pcre_replace_impl
Trying to allocate a `zend_string` with a length only slighty smaller than `SIZE_MAX` causes an integer overflow; we make sure that this doesn't happen by catering to the maximal overhead of a `zend_string`. Closes GH-7597.
1 parent 31749aa commit 712fc54

File tree

3 files changed

+8
-4
lines changed

3 files changed

+8
-4
lines changed

NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ PHP NEWS
1616
- OpenSSL:
1717
. Fixed bug #75725 (./configure: detecting RAND_egd). (Dilyan Palauzov)
1818

19+
- PCRE:
20+
. Fixed bug #74604 (Out of bounds in php_pcre_replace_impl). (cmb, Dmitry)
21+
1922
- Standard:
2023
. Fixed bug #81618 (dns_get_record fails on FreeBSD for missing type).
2124
(fsbruva)

Zend/zend_string.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ END_EXTERN_C()
7575

7676
#define _ZSTR_STRUCT_SIZE(len) (_ZSTR_HEADER_SIZE + len + 1)
7777

78-
#define ZSTR_MAX_LEN (SIZE_MAX - ZEND_MM_ALIGNED_SIZE(_ZSTR_HEADER_SIZE + 1))
78+
#define ZSTR_MAX_OVERHEAD (ZEND_MM_ALIGNED_SIZE(_ZSTR_HEADER_SIZE + 1))
79+
#define ZSTR_MAX_LEN (SIZE_MAX - ZSTR_MAX_OVERHEAD)
7980

8081
#define ZSTR_ALLOCA_ALLOC(str, _len, use_heap) do { \
8182
(str) = (zend_string *)do_alloca(ZEND_MM_ALIGNED_SIZE_EX(_ZSTR_STRUCT_SIZE(_len), 8), (use_heap)); \

ext/pcre/php_pcre.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1725,7 +1725,7 @@ PHPAPI zend_string *php_pcre_replace_impl(pcre_cache_entry *pce, zend_string *su
17251725
}
17261726

17271727
if (new_len >= alloc_len) {
1728-
alloc_len = zend_safe_address_guarded(2, new_len, 0);
1728+
alloc_len = zend_safe_address_guarded(2, new_len, ZSTR_MAX_OVERHEAD) - ZSTR_MAX_OVERHEAD;
17291729
if (result == NULL) {
17301730
result = zend_string_alloc(alloc_len, 0);
17311731
} else {
@@ -1961,9 +1961,9 @@ static zend_string *php_pcre_replace_func_impl(pcre_cache_entry *pce, zend_strin
19611961
pcre2_get_mark(match_data), flags);
19621962

19631963
ZEND_ASSERT(eval_result);
1964-
new_len = zend_safe_address_guarded(1, ZSTR_LEN(eval_result), new_len);
1964+
new_len = zend_safe_address_guarded(1, ZSTR_LEN(eval_result) + ZSTR_MAX_OVERHEAD, new_len) -ZSTR_MAX_OVERHEAD;
19651965
if (new_len >= alloc_len) {
1966-
alloc_len = zend_safe_address_guarded(2, new_len, 0);
1966+
alloc_len = zend_safe_address_guarded(2, new_len, ZSTR_MAX_OVERHEAD) - ZSTR_MAX_OVERHEAD;
19671967
if (result == NULL) {
19681968
result = zend_string_alloc(alloc_len, 0);
19691969
} else {

0 commit comments

Comments
 (0)