From 6a3b03fd9f15298e7a6b803391f03b65a0d99c49 Mon Sep 17 00:00:00 2001 From: Christoph Date: Fri, 20 Nov 2026 18:47:37 +0100 Subject: [PATCH] Add security patches for PHP 7.4.33. Raw patches from omega8cc/boa (5.x-dev, aegir/patches/php-sec): php-7.4.33-cve-2026-109618-109619.patch php-7.4.33-sury-31.patch php-7.4.33-xlts-1.patch php-7.4.33-xlts-2.patch php-7.4.33-sury-31-re2c-generated.patch (own patch) applies the pdo_sql_parser.re and url_scanner_ex.re hunks of sury-31 to the generated *.c files, so the fixes are built without re2c. (ext/date/lib/parse_iso_intervals.c already contains the fix of the parse_iso_intervals.re hunk.) Co-Authored-By: Claude Opus 5.5 --- php-7.4.33-cve-2026-109618-109619.patch | 942 ++ php-7.4.33-sury-31-re2c-generated.patch | 45 + php-7.4.33-sury-31.patch | 16992 ++++++++++++++++++++++ php-7.4.33-xlts-1.patch | 100 + php-7.4.33-xlts-2.patch | 1754 +++ 5 files changed, 19833 insertions(+) create mode 100644 php-7.4.33-cve-2026-109618-109619.patch create mode 100644 php-7.4.33-sury-31-re2c-generated.patch create mode 100644 php-7.4.33-sury-31.patch create mode 100644 php-7.4.33-xlts-1.patch create mode 100644 php-7.4.33-xlts-2.patch diff --git a/php-7.4.33-cve-2026-109618-109619.patch b/php-7.4.33-cve-2026-109618-109619.patch new file mode 100644 index 0000000..b611421 --- /dev/null +++ b/php-7.4.33-cve-2026-109618-109619.patch @@ -0,0 +1,942 @@ +diff --git a/Zend/zend_API.h b/Zend/zend_API.h +index 2a3b582902..26f7726bd8 100644 +--- a/Zend/zend_API.h ++++ b/Zend/zend_API.h +@@ -380,6 +380,7 @@ ZEND_API char *zend_get_type_by_const(int type); + + #define array_init(arg) ZVAL_ARR((arg), zend_new_array(0)) + #define array_init_size(arg, size) ZVAL_ARR((arg), zend_new_array(size)) ++#define array_init_singleton(arg) ZVAL_ARR((arg), zend_new_array_singleton()) + ZEND_API int object_init(zval *arg); + ZEND_API int object_init_ex(zval *arg, zend_class_entry *ce); + ZEND_API int object_and_properties_init(zval *arg, zend_class_entry *ce, HashTable *properties); +diff --git a/Zend/zend_alloc.c b/Zend/zend_alloc.c +index 3a33e5441c..be9b975426 100644 +--- a/Zend/zend_alloc.c ++++ b/Zend/zend_alloc.c +@@ -57,6 +57,7 @@ + #include "zend_operators.h" + #include "zend_multiply.h" + #include "zend_bitset.h" ++#include "zend_execute.h" + #include + + #ifdef HAVE_UNISTD_H +@@ -363,7 +364,42 @@ static ZEND_COLD ZEND_NORETURN void zend_mm_panic(const char *message) + #if ZEND_DEBUG && defined(HAVE_KILL) && defined(HAVE_GETPID) + kill(getpid(), SIGSEGV); + #endif +- exit(1); ++ _exit(1); ++} ++ ++ZEND_API ZEND_COLD ZEND_NORETURN void zend_mm_safe_error_ex(const char *format, ...) ++{ ++ zend_string *script_filename = NULL; ++ uint32_t script_lineno = 0; ++ ++ if (zend_is_executing()) { ++ script_filename = zend_get_executed_filename_ex(); ++ script_lineno = zend_get_executed_lineno(); ++ } else if (zend_is_compiling()) { ++ script_filename = zend_get_compiled_filename(); ++ script_lineno = zend_get_compiled_lineno(); ++ } ++ ++ va_list args; ++ va_start(args, format); ++ ++ char buf[1024]; ++ vsnprintf(buf, sizeof(buf), format, args); ++ ++ va_end(args); ++ ++ fprintf(stderr, ++ "\nFatal error: %s in %s on line %d\n", ++ buf, ++ script_filename ? ZSTR_VAL(script_filename) : "Unknown", ++ script_lineno); ++ ++ /* See http://support.microsoft.com/kb/190351 */ ++# ifdef ZEND_WIN32 ++ fflush(stderr); ++# endif ++ ++ _exit(1); + } + + static ZEND_COLD ZEND_NORETURN void zend_mm_safe_error(zend_mm_heap *heap, +@@ -375,22 +411,14 @@ static ZEND_COLD ZEND_NORETURN void zend_mm_safe_error(zend_mm_heap *heap, + #endif + size_t size) + { ++ (void) heap; + +- heap->overflow = 1; +- zend_try { +- zend_error_noreturn(E_ERROR, +- format, +- limit, ++ zend_mm_safe_error_ex(format, limit, + #if ZEND_DEBUG +- filename, +- lineno, ++ filename, ++ lineno, + #endif +- size); +- } zend_catch { +- } zend_end_try(); +- heap->overflow = 0; +- zend_bailout(); +- exit(1); ++ size); + } + + #ifdef _WIN32 +@@ -1318,7 +1346,7 @@ static zend_always_inline void *zend_mm_alloc_heap(zend_mm_heap *heap, size_t si + size = MAX(size, 1); + size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)); + if (UNEXPECTED(size < real_size)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu + %zu)", ZEND_MM_ALIGNED_SIZE(real_size), ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%zu + %zu)", ZEND_MM_ALIGNED_SIZE(real_size), ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); + return NULL; + } + #endif +@@ -1762,7 +1790,7 @@ static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_D + void *ptr; + + if (UNEXPECTED(new_size < size)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu + %zu)", size, alignment); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%zu + %zu)", size, alignment); + } + + #if ZEND_MM_LIMIT +@@ -2617,7 +2645,7 @@ ZEND_API char* ZEND_FASTCALL _estrdup(const char *s ZEND_FILE_LINE_DC ZEND_FILE_ + + length = strlen(s); + if (UNEXPECTED(length + 1 == 0)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (1 * %zu + 1)", length); + } + p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); + memcpy(p, s, length+1); +@@ -2629,7 +2657,7 @@ ZEND_API char* ZEND_FASTCALL _estrndup(const char *s, size_t length ZEND_FILE_LI + char *p; + + if (UNEXPECTED(length + 1 == 0)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (1 * %zu + 1)", length); + } + p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); + memcpy(p, s, length); +@@ -2643,7 +2671,7 @@ ZEND_API char* ZEND_FASTCALL zend_strndup(const char *s, size_t length) + char *p; + + if (UNEXPECTED(length + 1 == 0)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (1 * %zu + 1)", length); + } + p = (char *) malloc(length + 1); + if (UNEXPECTED(p == NULL)) { +@@ -2974,7 +3002,7 @@ ZEND_API zend_mm_heap *zend_mm_startup_ex(const zend_mm_handlers *handlers, void + static ZEND_COLD ZEND_NORETURN void zend_out_of_memory(void) + { + fprintf(stderr, "Out of memory\n"); +- exit(1); ++ _exit(1); + } + + ZEND_API void * __zend_malloc(size_t len) +diff --git a/Zend/zend_alloc.h b/Zend/zend_alloc.h +index 8bb854328d..2ed2ed8b3a 100644 +--- a/Zend/zend_alloc.h ++++ b/Zend/zend_alloc.h +@@ -402,6 +402,8 @@ static void apc_init_heap(void) + size_t zend_mm_globals_size(void); + #endif + ++ZEND_API ZEND_COLD ZEND_NORETURN void zend_mm_safe_error_ex(const char *format, ...); ++ + END_EXTERN_C() + + #endif +diff --git a/Zend/zend_execute_API.c b/Zend/zend_execute_API.c +index f4f0fa14f1..724b6e5cc4 100644 +--- a/Zend/zend_execute_API.c ++++ b/Zend/zend_execute_API.c +@@ -337,10 +337,21 @@ void shutdown_executor(void) /* {{{ */ + gc_collect_cycles(); + } + #endif ++ } else { ++ /* may be used by zend_error_zstr_at before init_executor */ ++ ZVAL_UNDEF(&EG(user_error_handler)); ++ ZVAL_UNDEF(&EG(user_exception_handler)); ++ memset(&EG(user_error_handlers_error_reporting), 0, sizeof(EG(user_error_handlers_error_reporting))); ++ memset(&EG(user_error_handlers), 0, sizeof(EG(user_error_handlers))); ++ memset(&EG(user_exception_handlers), 0, sizeof(EG(user_exception_handlers))); + } + + zend_objects_store_free_object_storage(&EG(objects_store), fast_shutdown); + ++ /* may be used by zend_error_zstr_at before init_executor */ ++ EG(error_handling) = EH_NORMAL; ++ EG(exception) = NULL; ++ + zend_weakrefs_shutdown(); + + zend_try { +@@ -357,6 +368,8 @@ void shutdown_executor(void) /* {{{ */ + zend_hash_discard(EG(function_table), EG(persistent_functions_count)); + zend_hash_discard(EG(class_table), EG(persistent_classes_count)); + zend_cleanup_internal_classes(); ++ EG(objects_store).object_buckets = NULL; ++ EG(objects_store).top = 1; + } else { + zend_vm_stack_destroy(); + +diff --git a/Zend/zend_hash.c b/Zend/zend_hash.c +index da150bd798..ef3d301db1 100644 +--- a/Zend/zend_hash.c ++++ b/Zend/zend_hash.c +@@ -97,7 +97,7 @@ static zend_always_inline uint32_t zend_hash_check_size(uint32_t nSize) + if (nSize <= HT_MIN_SIZE) { + return HT_MIN_SIZE; + } else if (UNEXPECTED(nSize >= HT_MAX_SIZE)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%u * %zu + %zu)", nSize, sizeof(Bucket), sizeof(Bucket)); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%u * %zu + %zu)", nSize, sizeof(Bucket), sizeof(Bucket)); + } + + #if defined(ZEND_WIN32) +@@ -251,6 +251,13 @@ ZEND_API HashTable* ZEND_FASTCALL _zend_new_array_0(void) + return ht; + } + ++ZEND_API HashTable* ZEND_FASTCALL zend_new_array_singleton(void) ++{ ++ HashTable *ht = _zend_new_array_0(); ++ ht->nTableSize = 1; ++ return ht; ++} ++ + ZEND_API HashTable* ZEND_FASTCALL _zend_new_array(uint32_t nSize) + { + HashTable *ht = emalloc(sizeof(HashTable)); +@@ -282,7 +289,7 @@ static void ZEND_FASTCALL zend_hash_packed_grow(HashTable *ht) + { + HT_ASSERT_RC1(ht); + if (ht->nTableSize >= HT_MAX_SIZE) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%u * %zu + %zu)", ht->nTableSize * 2, sizeof(Bucket), sizeof(Bucket)); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%u * %zu + %zu)", ht->nTableSize * 2, sizeof(Bucket), sizeof(Bucket)); + } + ht->nTableSize += ht->nTableSize; + HT_SET_DATA_ADDR(ht, perealloc2(HT_GET_DATA_ADDR(ht), HT_SIZE_EX(ht->nTableSize, HT_MIN_MASK), HT_USED_SIZE(ht), GC_FLAGS(ht) & IS_ARRAY_PERSISTENT)); +@@ -1164,7 +1171,7 @@ static void ZEND_FASTCALL zend_hash_do_resize(HashTable *ht) + pefree(old_data, GC_FLAGS(ht) & IS_ARRAY_PERSISTENT); + zend_hash_rehash(ht); + } else { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%u * %zu + %zu)", ht->nTableSize * 2, sizeof(Bucket) + sizeof(uint32_t), sizeof(Bucket)); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%u * %zu + %zu)", ht->nTableSize * 2, sizeof(Bucket) + sizeof(uint32_t), sizeof(Bucket)); + } + } + +diff --git a/Zend/zend_hash.h b/Zend/zend_hash.h +index f1e2d34685..b833479eaa 100644 +--- a/Zend/zend_hash.h ++++ b/Zend/zend_hash.h +@@ -296,6 +296,7 @@ ZEND_API int ZEND_FASTCALL zend_hash_rehash(HashTable *ht); + #endif + + ZEND_API HashTable* ZEND_FASTCALL _zend_new_array_0(void); ++ZEND_API HashTable* ZEND_FASTCALL zend_new_array_singleton(void); + ZEND_API HashTable* ZEND_FASTCALL _zend_new_array(uint32_t size); + ZEND_API HashTable* ZEND_FASTCALL zend_new_pair(zval *val1, zval *val2); + ZEND_API uint32_t zend_array_count(HashTable *ht); +diff --git a/Zend/zend_llist.c b/Zend/zend_llist.c +index 4a2c22e632..0955e953aa 100644 +--- a/Zend/zend_llist.c ++++ b/Zend/zend_llist.c +@@ -112,6 +112,8 @@ ZEND_API void zend_llist_destroy(zend_llist *l) + current = next; + } + ++ l->head = NULL; ++ l->tail = NULL; + l->count = 0; + } + +diff --git a/Zend/zend_multiply.h b/Zend/zend_multiply.h +index a3827d25d1..a9bbda5538 100644 +--- a/Zend/zend_multiply.h ++++ b/Zend/zend_multiply.h +@@ -321,7 +321,7 @@ static zend_always_inline size_t zend_safe_address_guarded(size_t nmemb, size_t + size_t ret = zend_safe_address(nmemb, size, offset, &overflow); + + if (UNEXPECTED(overflow)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", nmemb, size, offset); ++ zend_mm_safe_error_ex("Possible integer overflow in memory allocation (%zu * %zu + %zu)", nmemb, size, offset); + return 0; + } + return ret; +@@ -334,7 +334,7 @@ static zend_always_inline size_t zend_safe_addmult(size_t nmemb, size_t size, si + size_t ret = zend_safe_address(nmemb, size, offset, &overflow); + + if (UNEXPECTED(overflow)) { +- zend_error_noreturn(E_ERROR, "Possible integer overflow in %s (%zu * %zu + %zu)", message, nmemb, size, offset); ++ zend_mm_safe_error_ex("Possible integer overflow in %s (%zu * %zu + %zu)", message, nmemb, size, offset); + return 0; + } + return ret; +diff --git a/Zend/zend_strtod.c b/Zend/zend_strtod.c +index 2228e2262c..ad8df201af 100644 +--- a/Zend/zend_strtod.c ++++ b/Zend/zend_strtod.c +@@ -603,7 +603,7 @@ Balloc + rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong)); + if (!rv) { + FREE_DTOA_LOCK(0); +- zend_error_noreturn(E_ERROR, "Balloc() failed to allocate memory"); ++ zend_mm_safe_error_ex("Balloc() failed to allocate memory"); + } + #else + len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) +@@ -616,7 +616,7 @@ Balloc + rv = (Bigint*)MALLOC(len*sizeof(double)); + if (!rv) { + FREE_DTOA_LOCK(0); +- zend_error_noreturn(E_ERROR, "Balloc() failed to allocate memory"); ++ zend_mm_safe_error_ex("Balloc() failed to allocate memory"); + } + #endif + rv->k = k; +diff --git a/Zend/zend_types.h b/Zend/zend_types.h +index 7b8c079c45..f7828eb6d3 100644 +--- a/Zend/zend_types.h ++++ b/Zend/zend_types.h +@@ -330,17 +330,21 @@ struct _zend_array { + # define HT_HASH_RESET(ht) do { \ + char *p = (char*)&HT_HASH(ht, (ht)->nTableMask); \ + size_t size = HT_HASH_SIZE((ht)->nTableMask); \ +- __m128i xmm0 = _mm_setzero_si128(); \ +- xmm0 = _mm_cmpeq_epi8(xmm0, xmm0); \ +- ZEND_ASSERT(size >= 64 && ((size & 0x3f) == 0)); \ +- do { \ +- _mm_storeu_si128((__m128i*)p, xmm0); \ +- _mm_storeu_si128((__m128i*)(p+16), xmm0); \ +- _mm_storeu_si128((__m128i*)(p+32), xmm0); \ +- _mm_storeu_si128((__m128i*)(p+48), xmm0); \ +- p += 64; \ +- size -= 64; \ +- } while (size != 0); \ ++ if (UNEXPECTED(size < 64)) { \ ++ memset(p, HT_INVALID_IDX, size); \ ++ } else { \ ++ __m128i xmm0 = _mm_setzero_si128(); \ ++ xmm0 = _mm_cmpeq_epi8(xmm0, xmm0); \ ++ ZEND_ASSERT(size >= 64 && ((size & 0x3f) == 0)); \ ++ do { \ ++ _mm_storeu_si128((__m128i*)p, xmm0); \ ++ _mm_storeu_si128((__m128i*)(p+16), xmm0); \ ++ _mm_storeu_si128((__m128i*)(p+32), xmm0); \ ++ _mm_storeu_si128((__m128i*)(p+48), xmm0); \ ++ p += 64; \ ++ size -= 64; \ ++ } while (size != 0); \ ++ } \ + } while (0) + #else + # define HT_HASH_RESET(ht) \ +diff --git a/Zend/zend_vm_def.h b/Zend/zend_vm_def.h +index d362b01643..3af90d705b 100644 +--- a/Zend/zend_vm_def.h ++++ b/Zend/zend_vm_def.h +@@ -417,7 +417,7 @@ ZEND_VM_HANDLER(8, ZEND_CONCAT, CONST|TMPVAR|CV, CONST|TMPVAR|CV, SPEC(NO_CONST_ + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -426,6 +426,9 @@ ZEND_VM_HANDLER(8, ZEND_CONCAT, CONST|TMPVAR|CV, CONST|TMPVAR|CV, SPEC(NO_CONST_ + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -3210,6 +3213,9 @@ ZEND_VM_COLD_CONSTCONST_HANDLER(53, ZEND_FAST_CONCAT, CONST|TMPVAR|CV, CONST|TMP + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -3217,6 +3223,9 @@ ZEND_VM_COLD_CONSTCONST_HANDLER(53, ZEND_FAST_CONCAT, CONST|TMPVAR|CV, CONST|TMP + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +diff --git a/Zend/zend_vm_execute.h b/Zend/zend_vm_execute.h +index 2875fd3740..8701e77ea8 100644 +--- a/Zend/zend_vm_execute.h ++++ b/Zend/zend_vm_execute.h +@@ -5631,6 +5631,9 @@ static ZEND_VM_COLD ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_ + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -5638,6 +5641,9 @@ static ZEND_VM_COLD ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_ + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -7491,6 +7497,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CONST_TMPVAR_HANDL + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -7498,6 +7507,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CONST_TMPVAR_HANDL + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -7900,7 +7912,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CONST_TMPVAR_ + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -7909,6 +7921,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CONST_TMPVAR_ + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -9952,6 +9967,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CONST_CV_HANDLER(Z + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -9959,6 +9977,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CONST_CV_HANDLER(Z + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -10361,7 +10382,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CONST_CV_HAND + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -10370,6 +10391,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CONST_CV_HAND + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -13928,6 +13952,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_CONST_HANDL + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -13935,6 +13962,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_CONST_HANDL + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -14681,7 +14711,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_CONST_ + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -14690,6 +14720,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_CONST_ + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -15353,7 +15386,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_TMPVAR_HAND + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -15362,6 +15395,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_TMPVAR_HAND + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -16107,6 +16143,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_TMPVAR + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -16114,6 +16153,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_TMPVAR + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -17040,7 +17082,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_CV_HANDLER( + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -17049,6 +17091,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_TMPVAR_CV_HANDLER( + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -17401,6 +17446,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_CV_HAN + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -17408,6 +17456,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_TMPVAR_CV_HAN + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -38348,7 +38399,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_CONST_HANDLER(Z + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -38357,6 +38408,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_CONST_HANDLER(Z + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -40727,7 +40781,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_CONST_HAND + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -40736,6 +40790,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_CONST_HAND + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -41849,6 +41906,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_TMPVAR_HANDLER( + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -41856,6 +41916,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_TMPVAR_HANDLER( + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -44132,6 +44195,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_TMPVAR_HAN + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -44139,6 +44205,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_TMPVAR_HAN + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -46857,7 +46926,7 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_CV_HANDLER(ZEND + size_t len = ZSTR_LEN(op1_str); + + if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { +- zend_error_noreturn(E_ERROR, "Integer overflow in memory allocation"); ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); + } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -46866,6 +46935,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_CONCAT_SPEC_CV_CV_HANDLER(ZEND + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +@@ -49268,6 +49340,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_CV_HANDLER + !ZSTR_IS_INTERNED(op1_str) && GC_REFCOUNT(op1_str) == 1) { + size_t len = ZSTR_LEN(op1_str); + ++ if (UNEXPECTED(len > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_extend(op1_str, len + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str) + len, ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); + ZVAL_NEW_STR(EX_VAR(opline->result.var), str); +@@ -49275,6 +49350,9 @@ static ZEND_OPCODE_HANDLER_RET ZEND_FASTCALL ZEND_FAST_CONCAT_SPEC_CV_CV_HANDLER + zend_string_release_ex(op2_str, 0); + } + } else { ++ if (UNEXPECTED(ZSTR_LEN(op1_str) > ZSTR_MAX_LEN - ZSTR_LEN(op2_str))) { ++ zend_mm_safe_error_ex("Integer overflow in memory allocation"); ++ } + str = zend_string_alloc(ZSTR_LEN(op1_str) + ZSTR_LEN(op2_str), 0); + memcpy(ZSTR_VAL(str), ZSTR_VAL(op1_str), ZSTR_LEN(op1_str)); + memcpy(ZSTR_VAL(str) + ZSTR_LEN(op1_str), ZSTR_VAL(op2_str), ZSTR_LEN(op2_str)+1); +diff --git a/ext/session/session.c b/ext/session/session.c +index 8fb6dd2cd5..89a7400a9c 100644 +--- a/ext/session/session.c ++++ b/ext/session/session.c +@@ -3174,7 +3174,7 @@ static int php_session_rfc1867_callback(unsigned int event, void *event_data, vo + if (php_session_rfc1867_orig_callback) { + retval = php_session_rfc1867_orig_callback(event, event_data, extra); + } +- if (!PS(rfc1867_enabled)) { ++ if (!PS(rfc1867_enabled) || true) { + return retval; + } + +diff --git a/main/SAPI.c b/main/SAPI.c +index a5a68f8c68..1c320f6e3f 100644 +--- a/main/SAPI.c ++++ b/main/SAPI.c +@@ -509,18 +509,23 @@ SAPI_API void sapi_deactivate(void) + } + if (SG(request_info).auth_user) { + efree(SG(request_info).auth_user); ++ SG(request_info).auth_user = NULL; + } + if (SG(request_info).auth_password) { + efree(SG(request_info).auth_password); ++ SG(request_info).auth_password = NULL; + } + if (SG(request_info).auth_digest) { + efree(SG(request_info).auth_digest); ++ SG(request_info).auth_digest = NULL; + } + if (SG(request_info).content_type_dup) { + efree(SG(request_info).content_type_dup); ++ SG(request_info).content_type_dup = NULL; + } + if (SG(request_info).current_user) { + efree(SG(request_info).current_user); ++ SG(request_info).current_user = NULL; + } + if (sapi_module.deactivate) { + sapi_module.deactivate(); +diff --git a/main/main.c b/main/main.c +index 0b33b2b56c..bb8501f973 100644 +--- a/main/main.c ++++ b/main/main.c +@@ -836,6 +836,7 @@ PHP_INI_BEGIN() + PHP_INI_ENTRY("disable_functions", "", PHP_INI_SYSTEM, NULL) + PHP_INI_ENTRY("disable_classes", "", PHP_INI_SYSTEM, NULL) + PHP_INI_ENTRY("max_file_uploads", "20", PHP_INI_SYSTEM|PHP_INI_PERDIR, NULL) ++ PHP_INI_ENTRY("max_multipart_body_parts", "-1", PHP_INI_SYSTEM|PHP_INI_PERDIR, NULL) + + STD_PHP_INI_BOOLEAN("allow_url_fopen", "1", PHP_INI_SYSTEM, OnUpdateBool, allow_url_fopen, php_core_globals, core_globals) + STD_PHP_INI_BOOLEAN("allow_url_include", "0", PHP_INI_SYSTEM, OnUpdateBool, allow_url_include, php_core_globals, core_globals) +@@ -1960,6 +1961,8 @@ void php_request_shutdown(void *dummy) + + for (i=0; i 0) { +@@ -451,7 +451,7 @@ + } + smart_str_appendl(&ctx->tag, start, YYCURSOR - start); + for (i = 0; i < ZSTR_LEN(ctx->tag.s); i++) +- ZSTR_VAL(ctx->tag.s)[i] = tolower((int)(unsigned char)ZSTR_VAL(ctx->tag.s)[i]); ++ ZSTR_VAL(ctx->tag.s)[i] = tolower((unsigned char)ZSTR_VAL(ctx->tag.s)[i]); + /* intentionally using str_find here, in case the hash value is set, but the string val is changed later */ + if ((ctx->lookup_data = zend_hash_str_find_ptr(ctx->tags, ZSTR_VAL(ctx->tag.s), ZSTR_LEN(ctx->tag.s))) != NULL) { + ok = 1; diff --git a/php-7.4.33-sury-31.patch b/php-7.4.33-sury-31.patch new file mode 100644 index 0000000..3d569ae --- /dev/null +++ b/php-7.4.33-sury-31.patch @@ -0,0 +1,16992 @@ +diff --git a/NEWS b/NEWS +index 8a8c0c9..dd722c0 100644 +--- a/NEWS ++++ b/NEWS +@@ -1,5 +1,235 @@ + PHP NEWS + ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ++ ++Backported from 8.2.34 ++ ++- Filter: ++ . Fixed GHSA-ch8v-r6jh-4vvr (FILTER_SANITIZE_ENCODED does not encode 0xFF). ++ (Ilia Alshanetsky) ++ ++- FPM: ++ . Fixed GHSA-62xp-839h-2637 (IPv6 ACL bypass in FastCGI listen.allowed_clients ++ due to partial address comparison). (CVE-2026-91768) (Alexandre Daubois) ++ ++- MySQLnd: ++ . Fixed GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd wire ++ protocol). (CVE-2025-1218) (Jakub Zelenka, Nora Dossche) ++ ++- OpenSSL: ++ . Fixed GHSA-vvx9-73fr-5jjx (TLS hostname verification falls back to CN after ++ SAN mismatch). (CVE-2026-91769) (Jakub Zelenka) ++ . Fixed GHSA-xr7j-rvgx-xq5p (Heap buffer overflow in ++ php_openssl_matches_wildcard_name() on crafted server certificate wildcard ++ CN). (CVE-2026-91767) (Jakub Zelenka) ++ ++- Phar: ++ . Fixed GHSA-j3wh-g957-2m85 (Integer overflow in phar_tar_number() allowing ++ TAR archive entry injection). (CVE-2026-6103) (Jakub Zelenka) ++ ++- SOAP: ++ . Fixed GHSA-rgrp-mwpx-f6rm (Unbounded recursion in server-side ++ cleanup_xml_node()). (CVE-2026-91765) (Alexandre Daubois) ++ . Fixed GHSA-cj93-vc83-wgqv (Integer overflow to buffer overflow in SOAP HTTP ++ parsing). (CVE-2025-14181) (Nora Dossche, Jakub Zelenka) ++ ++- Standard: ++ . Fixed GHSA-88hq-2827-7pg6 (Out-of-bounds read in convert.* stream filters ++ when line-break-chars contains NUL). (CVE-2026-92842) (geeknik) ++ . Fixed GHSA-fpwc-w8rq-cr92 (Cross-origin credential leak in HTTP stream ++ wrapper redirects). (CVE-2026-91766) (Alexandre Daubois, Jakub Zelenka) ++ . Fixed GHSA-7875-c8px-7q5f (Out-of-bounds read in the HTTP stream wrapper ++ when following a redirect with an empty Location header). (CVE-2026-93682) ++ (Ilia Alshanetsky, Jordi Kroon) ++ ++- Windows: ++ . Fixed GHSA-9f67-6fw4-hpfp (Reserved device names are not rejected before ++ file and stream I/O). (CVE-2026-17545) (Shivam Mathur, Jakub Zelenka) ++ ++Backported from 8.2.33 ++ ++- Date: ++ . Fixed leak on double DatePeriod::__construct() call. (ilutov) ++ ++- GD: ++ . Upgrade libgd. (CVE-2026-9672) (Pierre Joye) ++ ++- PGSQL: ++ . Fixed GHSA-7qpv-r5mr-78m4 (SQL injection via E'...' backslash breakout). ++ (CVE-2026-17543) (ilutov) ++ ++- Phar: ++ . Fixed GHSA-vc5h-9ppw-p5f3 (Crash via recursive symlinks). (CVE-2026-7260) ++ (Jakub Zelenka) ++ ++Backported from 8.2.32 ++ ++- OpenSSL: ++ . Fixed bug GH-22187 (Memory corruption (zend_mm_heap corrupted) in ++ openssl_encrypt with AES-WRAP-PAD). (David Carlier) ++ ++Backported from 8.2.31 ++ ++- FPM: ++ . Fixed GHSA-7qg2-v9fj-4mwv (XSS within status endpoint). (CVE-2026-6735) ++ (Jakub Zelenka) ++ ++- SOAP: ++ . Fixed GHSA-85c2-q967-79q5 (Stale SOAP_GLOBAL(ref_map) pointer with Apache ++ Map). (CVE-2026-6722) (ilutov) ++ . Fixed GHSA-m33r-qmcv-p97q (Use-after-free after header parsing failure with ++ SOAP_PERSISTENCE_SESSION). (CVE-2026-7261) (ilutov) ++ . Fixed GHSA-hmxp-6pc4-f3vv (Broken Apache map value NULL check). ++ (CVE-2026-7262) (ilutov) ++ ++- Standard: ++ . Fixed GHSA-96wq-48vp-hh57 (Signed integer overflow of char array offset). ++ (CVE-2026-7568) (TimWolla) ++ . Fixed GHSA-m8rr-4c36-8gq4 (Consistently pass unsigned char to ctype.h ++ functions). (CVE-2026-7258) (ilutov) ++ ++Backported from 8.1.34 ++ ++- Standard: ++ . Fixed GHSA-www2-q4fc-65wf (Null byte termination in dns_get_record()). ++ (ndossche) ++ . Fixed GHSA-h96m-rvf9-jgm2 (Heap buffer overflow in array_merge()). ++ (CVE-2025-14178) (ndossche) ++ . Fixed GHSA-3237-qqm7-mfv7 (Information Leak of Memory in getimagesize). ++ (CVE-2025-14177) (ndossche) ++ ++Backported from 8.1.33 ++ ++- PGSQL: ++ . Fixed GHSA-hrwm-9436-5mv3 (pgsql extension does not check for errors during ++ escaping). (CVE-2025-1735) (Jakub Zelenka) ++ ++- SOAP: ++ . Fixed GHSA-453j-q27h-5p8x (NULL Pointer Dereference in PHP SOAP Extension ++ via Large XML Namespace Prefix). (CVE-2025-6491) (Lekssays, nielsdos) ++ ++- Standard: ++ . Fixed GHSA-3cr5-j632-f35r (Null byte termination in hostnames). ++ (CVE-2025-1220) (Jakub Zelenka) ++ ++Backported from 8.1.32 ++ ++- LibXML: ++ . Fixed GHSA-wg4p-4hqh-c3g9 (Reocurrence of #72714). (nielsdos) ++ . Fixed GHSA-p3x9-6h7p-cgfc (libxml streams use wrong `content-type` header ++ when requesting a redirected resource). (CVE-2025-1219) (timwolla) ++ ++- Streams: ++ . Fixed GHSA-hgf54-96fm-v528 (Stream HTTP wrapper header check might omit ++ basic auth header). (CVE-2025-1736) (Jakub Zelenka) ++ . Fixed GHSA-52jp-hrpf-2jff (Stream HTTP wrapper truncate redirect location ++ to 1024 bytes). (CVE-2025-1861) (Jakub Zelenka) ++ . Fixed GHSA-pcmh-g36c-qc44 (Streams HTTP wrapper does not fail for headers ++ without colon). (CVE-2025-1734) (Jakub Zelenka) ++ . Fixed GHSA-v8xr-gpvj-cx9g (Header parser of `http` stream wrapper does not ++ handle folded headers). (CVE-2025-1217) (Jakub Zelenka) ++ ++Backported from 8.1.31 ++ ++- CLI: ++ . Fixed bug GHSA-4w77-75f9-2c8w (Heap-Use-After-Free in sapi_read_post_data ++ Processing in CLI SAPI Interface). (nielsdos) ++ ++- LDAP: ++ . Fixed bug GHSA-g665-fm4p-vhff (OOB access in ldap_escape). (CVE-2024-8932) ++ (nielsdos) ++ ++- MySQLnd: ++ . Fixed bug GHSA-h35g-vwh6-m678 (Leak partial content of the heap through ++ heap buffer over-read). (CVE-2024-8929) (Jakub Zelenka) ++ ++- PDO DBLIB: ++ . Fixed bug GHSA-5hqh-c84r-qjcv (Integer overflow in the dblib quoter causing ++ OOB writes). (CVE-2024-11236) (nielsdos) ++ ++- PDO Firebird: ++ . Fixed bug GHSA-5hqh-c84r-qjcv (Integer overflow in the firebird quoter ++ causing OOB writes). (CVE-2024-11236) (nielsdos) ++ ++- Streams: ++ . Fixed bug GHSA-c5f2-jwm7-mmq2 (Configuring a proxy in a stream context ++ might allow for CRLF injection in URIs). (CVE-2024-11234) (Jakub Zelenka) ++ . Fixed bug GHSA-r977-prxv-hc43 (Single byte overread with ++ convert.quoted-printable-decode filter). (CVE-2024-11233) (nielsdos) ++ ++Backported from 8.1.30 ++ ++- CGI: ++ . Fixed bug GHSA-p99j-rfp4-xqvq (Bypass of CVE-2024-4577, Parameter Injection ++ Vulnerability). (CVE-2024-8926) (nielsdos) ++ . Fixed bug GHSA-94p6-54jq-9mwp (cgi.force_redirect configuration is ++ bypassable due to the environment variable collision). (CVE-2024-8927) ++ (nielsdos) ++ ++- FPM: ++ . Fixed bug GHSA-865w-9rf3-2wh5 (Logs from childrens may be altered). ++ (CVE-2024-9026) (Jakub Zelenka) ++ ++- SAPI: ++ . Fixed bug GHSA-9pqp-7h25-4f32 (Erroneous parsing of multipart form data). ++ (CVE-2024-8925) (Arnaud) ++ ++Backported from 8.1.29 ++ ++- CGI: ++ . Fixed bug GHSA-3qgc-jrrr-25jv (Bypass of CVE-2012-1823, Argument Injection ++ in PHP-CGI). (CVE-2024-4577) (nielsdos) ++ ++- Filter: ++ . Fixed bug GHSA-w8qr-v226-r27w (Filter bypass in filter_var FILTER_VALIDATE_URL). ++ (CVE-2024-5458) (nielsdos) ++ ++- Standard: ++ . Fixed bug GHSA-9fcc-425m-g385 (Bypass of CVE-2024-1874). ++ (CVE-2024-5585) (nielsdos) ++ ++Backported from 8.1.28 ++ ++- Standard: ++ . Fixed bug GHSA-wpj3-hf5j-x4v4 (__Host-/__Secure- cookie bypass due to ++ partial CVE-2022-31629 fix). (CVE-2024-2756) (nielsdos) ++ . Fixed bug GHSA-h746-cjrr-wfmr (password_verify can erroneously return true, ++ opening ATO risk). (CVE-2024-3096) (Jakub Zelenka) ++ . Fixed bug GHSA-pc52-254m-w9w7 (Command injection via array-ish $command ++ parameter of proc_open). (CVE-2024-1874) (Jakub Zelenka) ++ ++Backported from 8.0.30 ++ ++- Libxml: ++ . Fixed bug GHSA-3qrf-m4j2-pcrr (Security issue with external entity loading ++ in XML without enabling it). (CVE-2023-3823) (nielsdos, ilutov) ++ ++- Phar: ++ . Fixed bug GHSA-jqcx-ccgc-xwhv (Buffer mismanagement in phar_dir_read()). ++ (CVE-2023-3824) (nielsdos) ++ ++Backported from 8.0.29 ++ ++- Soap: ++ . Fixed bug GHSA-76gg-c692-v2mw (Missing error check and insufficient random ++ bytes in HTTP Digest authentication for SOAP). ++ (CVE-2023-3247) (nielsdos, timwolla) ++ ++Backported from 8.0.28 ++ ++- Core: ++ . Fixed bug #81744 (Password_verify() always return true with some hash). ++ (CVE-2023-0567). (Tim Düsterhus) ++ . Fixed bug #81746 (1-byte array overrun in common path resolve code). ++ (CVE-2023-0568). (Niels Dossche) ++ . Fixed bug GHSA-54hq-v5wp-fqgv (DOS vulnerability when parsing multipart ++ request body). (CVE-2023-0662) (Jakub Zelenka) ++ ++Backported from 8.0.27 ++ ++- PDO/SQLite: ++ . Fixed bug #81740 (PDO::quote() may return unquoted string). ++ (CVE-2022-31631) (cmb) ++ + 03 Nov 2022, PHP 7.4.33 + + - GD: +diff --git a/Zend/tests/GHSA-wm6j-2649-pv75.phpt b/Zend/tests/GHSA-wm6j-2649-pv75.phpt +new file mode 100644 +index 0000000..acb947d +--- /dev/null ++++ b/Zend/tests/GHSA-wm6j-2649-pv75.phpt +@@ -0,0 +1,18 @@ ++--TEST-- ++GHSA-wm6j-2649-pv75: Null pointer dereference in php_mb_check_encoding() via mb_ereg_search_init() ++--CREDITS-- ++vi3tL0u1s ++--EXTENSIONS-- ++mbstring ++--SKIPIF-- ++ ++--FILE-- ++ ++--EXPECTF-- ++Warning: mb_ereg_search_init(): Invalid encoding "ISO-8859-11" in %s +diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c +index 8b8cc30..7777b37 100644 +--- a/Zend/zend_compile.c ++++ b/Zend/zend_compile.c +@@ -1772,7 +1772,7 @@ ZEND_API size_t zend_dirname(char *path, size_t len) + /* Note that on Win32 CWD is per drive (heritage from CP/M). + * This means dirname("c:foo") maps to "c:." or "c:" - which means CWD on C: drive. + */ +- if ((2 <= len) && isalpha((int)((unsigned char *)path)[0]) && (':' == path[1])) { ++ if ((2 <= len) && isalpha((unsigned char)path[0]) && (':' == path[1])) { + /* Skip over the drive spec (if any) so as not to change */ + path += 2; + len_adjust += 2; +diff --git a/Zend/zend_operators.c b/Zend/zend_operators.c +index 0318947..b4d804f 100644 +--- a/Zend/zend_operators.c ++++ b/Zend/zend_operators.c +@@ -2804,8 +2804,8 @@ ZEND_API int ZEND_FASTCALL zend_binary_strcasecmp_l(const char *s1, size_t len1, + + len = MIN(len1, len2); + while (len--) { +- c1 = zend_tolower((int)*(unsigned char *)s1++); +- c2 = zend_tolower((int)*(unsigned char *)s2++); ++ c1 = zend_tolower((unsigned char)*(s1++)); ++ c2 = zend_tolower((unsigned char)*(s2++)); + if (c1 != c2) { + return c1 - c2; + } +@@ -2825,8 +2825,8 @@ ZEND_API int ZEND_FASTCALL zend_binary_strncasecmp_l(const char *s1, size_t len1 + } + len = MIN(length, MIN(len1, len2)); + while (len--) { +- c1 = zend_tolower((int)*(unsigned char *)s1++); +- c2 = zend_tolower((int)*(unsigned char *)s2++); ++ c1 = zend_tolower((unsigned char)*(s1++)); ++ c2 = zend_tolower((unsigned char)*(s2++)); + if (c1 != c2) { + return c1 - c2; + } +diff --git a/Zend/zend_virtual_cwd.c b/Zend/zend_virtual_cwd.c +index e16ba50..a876102 100644 +--- a/Zend/zend_virtual_cwd.c ++++ b/Zend/zend_virtual_cwd.c +@@ -201,7 +201,7 @@ void virtual_cwd_main_cwd_init(uint8_t reinit) /* {{{ */ + main_cwd_state.cwd_length = strlen(cwd); + #ifdef ZEND_WIN32 + if (main_cwd_state.cwd_length >= 2 && cwd[1] == ':') { +- cwd[0] = toupper(cwd[0]); ++ cwd[0] = toupper((unsigned char)cwd[0]); + } + #endif + main_cwd_state.cwd = strdup(cwd); +@@ -279,7 +279,7 @@ CWD_API char *virtual_getcwd_ex(size_t *length) /* {{{ */ + *length = state->cwd_length+1; + retval = (char *) emalloc(*length+1); + memcpy(retval, state->cwd, *length); +- retval[0] = toupper(retval[0]); ++ retval[0] = toupper((unsigned char)retval[0]); + retval[*length-1] = DEFAULT_SLASH; + retval[*length] = '\0'; + return retval; +@@ -1035,6 +1035,19 @@ CWD_API int virtual_file_ex(cwd_state *state, const char *path, verify_path_func + fprintf(stderr,"cwd = %s path = %s\n", state->cwd, path); + #endif + ++#ifdef ZEND_WIN32 ++ switch (php_win32_ioutil_path_kind_a(path, path_length)) { ++ case PHP_WIN32_IOUTIL_PATH_RESERVED: ++ SET_ERRNO_FROM_WIN32_CODE(ERROR_INVALID_NAME); ++ return 1; ++ case PHP_WIN32_IOUTIL_PATH_DEVICE: ++ memcpy(resolved_path, path, path_length + 1); ++ goto verify; ++ default: ++ break; ++ } ++#endif ++ + /* cwd_length can be 0 when getcwd() fails. + * This can happen under solaris when a dir does not have read permissions + * but *does* have execute permissions */ +@@ -1120,7 +1133,7 @@ CWD_API int virtual_file_ex(cwd_state *state, const char *path, verify_path_func + if (resolved_path[start] == 0) { + goto verify; + } +- resolved_path[start] = toupper(resolved_path[start]); ++ resolved_path[start] = toupper((unsigned char)resolved_path[start]); + start++; + } + resolved_path[start++] = DEFAULT_SLASH; +@@ -1128,13 +1141,13 @@ CWD_API int virtual_file_ex(cwd_state *state, const char *path, verify_path_func + if (resolved_path[start] == 0) { + goto verify; + } +- resolved_path[start] = toupper(resolved_path[start]); ++ resolved_path[start] = toupper((unsigned char)resolved_path[start]); + start++; + } + resolved_path[start++] = DEFAULT_SLASH; + } else if (IS_ABSOLUTE_PATH(resolved_path, path_length)) { + /* skip DRIVE name */ +- resolved_path[0] = toupper(resolved_path[0]); ++ resolved_path[0] = toupper((unsigned char)resolved_path[0]); + resolved_path[2] = DEFAULT_SLASH; + start = 3; + } +diff --git a/Zend/zend_virtual_cwd.h b/Zend/zend_virtual_cwd.h +index 574bee9..35053f4 100644 +--- a/Zend/zend_virtual_cwd.h ++++ b/Zend/zend_virtual_cwd.h +@@ -84,7 +84,7 @@ typedef unsigned short mode_t; + #define IS_UNC_PATH(path, len) \ + (len >= 2 && IS_SLASH(path[0]) && IS_SLASH(path[1])) + #define IS_ABSOLUTE_PATH(path, len) \ +- (len >= 2 && (/* is local */isalpha(path[0]) && path[1] == ':' || /* is UNC */IS_SLASH(path[0]) && IS_SLASH(path[1]))) ++ (len >= 2 && (/* is local */isalpha((unsigned char)(path)[0]) && path[1] == ':' || /* is UNC */IS_SLASH(path[0]) && IS_SLASH(path[1]))) + + #else + #ifdef HAVE_DIRENT_H +diff --git a/ext/com_dotnet/com_extension.c b/ext/com_dotnet/com_extension.c +index 5ae1481..a3d4afd 100644 +--- a/ext/com_dotnet/com_extension.c ++++ b/ext/com_dotnet/com_extension.c +@@ -241,11 +241,11 @@ static PHP_INI_MH(OnTypeLibFileUpdate) + } + + /* Remove leading/training white spaces on search_string */ +- while (isspace(*typelib_name)) {/* Ends on '\0' in worst case */ ++ while (isspace((unsigned char)*typelib_name)) {/* Ends on '\0' in worst case */ + typelib_name ++; + } + ptr = typelib_name + strlen(typelib_name) - 1; +- while ((ptr != typelib_name) && isspace(*ptr)) { ++ while ((ptr != typelib_name) && isspace((unsigned char)*ptr)) { + *ptr = '\0'; + ptr--; + } +diff --git a/ext/date/lib/parse_date.c b/ext/date/lib/parse_date.c +index 266bad1..d5749b0 100644 +--- a/ext/date/lib/parse_date.c ++++ b/ext/date/lib/parse_date.c +@@ -479,7 +479,7 @@ static timelib_sll timelib_get_nr(char **ptr, int max_length) + + static void timelib_skip_day_suffix(char **ptr) + { +- if (isspace(**ptr)) { ++ if (isspace((unsigned char)**ptr)) { + return; + } + if (!timelib_strncasecmp(*ptr, "nd", 2) || !timelib_strncasecmp(*ptr, "rd", 2) ||!timelib_strncasecmp(*ptr, "st", 2) || !timelib_strncasecmp(*ptr, "th", 2)) { +@@ -744,7 +744,7 @@ static timelib_long timelib_parse_tz_cor(char **ptr) + char *begin = *ptr, *end; + timelib_long tmp; + +- while (isdigit(**ptr) || **ptr == ':') { ++ while (isdigit((unsigned char)**ptr) || **ptr == ':') { + ++*ptr; + } + end = *ptr; +@@ -786,7 +786,7 @@ static timelib_long timelib_parse_tz_minutes(char **ptr, timelib_time *t) + } + + ++*ptr; +- while (isdigit(**ptr)) { ++ while (isdigit((unsigned char)**ptr)) { + ++*ptr; + } + +@@ -24945,10 +24945,10 @@ timelib_time* timelib_strtotime(char *s, size_t len, timelib_error_container **e + in.errors->error_messages = NULL; + + if (len > 0) { +- while (isspace(*s) && s < e) { ++ while (isspace((unsigned char)*s) && s < e) { + s++; + } +- while (isspace(*e) && e > s) { ++ while (isspace((unsigned char)*e) && e > s) { + e--; + } + } +diff --git a/ext/date/lib/parse_date.re b/ext/date/lib/parse_date.re +index 3dcb804..40d50ee 100644 +--- a/ext/date/lib/parse_date.re ++++ b/ext/date/lib/parse_date.re +@@ -477,7 +477,7 @@ static timelib_sll timelib_get_nr(char **ptr, int max_length) + + static void timelib_skip_day_suffix(char **ptr) + { +- if (isspace(**ptr)) { ++ if (isspace((unsigned char)**ptr)) { + return; + } + if (!timelib_strncasecmp(*ptr, "nd", 2) || !timelib_strncasecmp(*ptr, "rd", 2) ||!timelib_strncasecmp(*ptr, "st", 2) || !timelib_strncasecmp(*ptr, "th", 2)) { +@@ -742,7 +742,7 @@ static timelib_long timelib_parse_tz_cor(char **ptr) + char *begin = *ptr, *end; + timelib_long tmp; + +- while (isdigit(**ptr) || **ptr == ':') { ++ while (isdigit((unsigned char)**ptr) || **ptr == ':') { + ++*ptr; + } + end = *ptr; +@@ -784,7 +784,7 @@ static timelib_long timelib_parse_tz_minutes(char **ptr, timelib_time *t) + } + + ++*ptr; +- while (isdigit(**ptr)) { ++ while (isdigit((unsigned char)**ptr)) { + ++*ptr; + } + +@@ -1837,10 +1837,10 @@ timelib_time* timelib_strtotime(char *s, size_t len, timelib_error_container **e + in.errors->error_messages = NULL; + + if (len > 0) { +- while (isspace(*s) && s < e) { ++ while (isspace((unsigned char)*s) && s < e) { + s++; + } +- while (isspace(*e) && e > s) { ++ while (isspace((unsigned char)*e) && e > s) { + e--; + } + } +diff --git a/ext/date/lib/parse_iso_intervals.c b/ext/date/lib/parse_iso_intervals.c +index 4f7e2d4..b56ccb0 100644 +--- a/ext/date/lib/parse_iso_intervals.c ++++ b/ext/date/lib/parse_iso_intervals.c +@@ -946,10 +946,10 @@ void timelib_strtointerval(char *s, size_t len, + in.errors->error_messages = NULL; + + if (len > 0) { +- while (isspace(*s) && s < e) { ++ while (isspace((unsigned char)*s) && s < e) { + s++; + } +- while (isspace(*e) && e > s) { ++ while (isspace((unsigned char)*e) && e > s) { + e--; + } + } +diff --git a/ext/date/lib/parse_iso_intervals.re b/ext/date/lib/parse_iso_intervals.re +index 6e863ea..fd959c0 100644 +--- a/ext/date/lib/parse_iso_intervals.re ++++ b/ext/date/lib/parse_iso_intervals.re +@@ -341,10 +341,10 @@ void timelib_strtointerval(char *s, size_t len, + in.errors->error_messages = NULL; + + if (len > 0) { +- while (isspace(*s) && s < e) { ++ while (isspace((unsigned char)*s) && s < e) { + s++; + } +- while (isspace(*e) && e > s) { ++ while (isspace((unsigned char)*e) && e > s) { + e--; + } + } +diff --git a/ext/date/lib/timelib.c b/ext/date/lib/timelib.c +index fc86619..d36768d 100644 +--- a/ext/date/lib/timelib.c ++++ b/ext/date/lib/timelib.c +@@ -123,7 +123,7 @@ void timelib_time_tz_abbr_update(timelib_time* tm, char* tz_abbr) + TIMELIB_TIME_FREE(tm->tz_abbr); + tm->tz_abbr = timelib_strdup(tz_abbr); + for (i = 0; i < tz_abbr_len; i++) { +- tm->tz_abbr[i] = toupper(tz_abbr[i]); ++ tm->tz_abbr[i] = toupper((unsigned char)tz_abbr[i]); + } + } + +diff --git a/ext/date/php_date.c b/ext/date/php_date.c +index e1a427c..15f13d4 100644 +--- a/ext/date/php_date.c ++++ b/ext/date/php_date.c +@@ -4670,9 +4670,24 @@ static int date_period_initialize(timelib_time **st, timelib_time **et, timelib_ + return retval; + } /* }}} */ + +-/* {{{ proto DatePeriod::__construct(DateTime $start, DateInterval $interval, int recurrences|DateTime $end) +- Creates new DatePeriod object. +-*/ ++static void date_period_reset(php_period_obj *period_obj) ++{ ++ if (period_obj->start) { ++ timelib_time_dtor(period_obj->start); ++ } ++ if (period_obj->current) { ++ timelib_time_dtor(period_obj->current); ++ } ++ if (period_obj->end) { ++ timelib_time_dtor(period_obj->end); ++ } ++ if (period_obj->interval) { ++ timelib_rel_time_dtor(period_obj->interval); ++ } ++ memset(period_obj, 0, XtOffsetOf(php_period_obj, std)); ++} ++ ++/* {{{ Creates new DatePeriod object. */ + PHP_METHOD(DatePeriod, __construct) + { + php_period_obj *dpobj; +@@ -4696,7 +4711,7 @@ PHP_METHOD(DatePeriod, __construct) + } + + dpobj = Z_PHPPERIOD_P(ZEND_THIS); +- dpobj->current = NULL; ++ date_period_reset(dpobj); + + if (isostr) { + date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len); +@@ -4718,6 +4733,8 @@ PHP_METHOD(DatePeriod, __construct) + } + dpobj->start_ce = date_ce_date; + } else { ++ DATE_CHECK_INITIALIZED(Z_PHPINTERVAL_P(interval)->initialized, Z_OBJCE_P(interval)); ++ + /* init */ + php_interval_obj *intobj = Z_PHPINTERVAL_P(interval); + +diff --git a/ext/date/tests/DatePeriod_double_constructor_call.phpt b/ext/date/tests/DatePeriod_double_constructor_call.phpt +new file mode 100644 +index 0000000..551d272 +--- /dev/null ++++ b/ext/date/tests/DatePeriod_double_constructor_call.phpt +@@ -0,0 +1,14 @@ ++--TEST-- ++Double DatePeriod::__construct() call ++--FILE-- ++__construct($start, $interval, 1); ++ ++?> ++===DONE=== ++--EXPECT-- ++===DONE=== +diff --git a/ext/dom/document.c b/ext/dom/document.c +index b478e1a..989b5b3 100644 +--- a/ext/dom/document.c ++++ b/ext/dom/document.c +@@ -1379,7 +1379,7 @@ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, size_t so + int validate, recover, resolve_externals, keep_blanks, substitute_ent; + int resolved_path_len; + int old_error_reporting = 0; +- char *directory=NULL, resolved_path[MAXPATHLEN]; ++ char *directory=NULL, resolved_path[MAXPATHLEN + 1]; + + if (id != NULL) { + intern = Z_DOMOBJ_P(id); +@@ -1458,6 +1458,7 @@ static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, size_t so + options |= XML_PARSE_NOBLANKS; + } + ++ php_libxml_sanitize_parse_ctxt_options(ctxt); + xmlCtxtUseOptions(ctxt, options); + + ctxt->recovery = recover; +@@ -1758,7 +1759,9 @@ PHP_FUNCTION(dom_document_xinclude) + + DOM_GET_OBJ(docp, id, xmlDocPtr, intern); + ++ PHP_LIBXML_SANITIZE_GLOBALS(xinclude); + err = xmlXIncludeProcessFlags(docp, (int)flags); ++ PHP_LIBXML_RESTORE_GLOBALS(xinclude); + + /* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these + are added via xmlXIncludeProcess to mark beginning and ending of xincluded document +@@ -1798,6 +1801,7 @@ PHP_FUNCTION(dom_document_validate) + + DOM_GET_OBJ(docp, id, xmlDocPtr, intern); + ++ PHP_LIBXML_SANITIZE_GLOBALS(validate); + cvp = xmlNewValidCtxt(); + + cvp->userData = NULL; +@@ -1809,6 +1813,7 @@ PHP_FUNCTION(dom_document_validate) + } else { + RETVAL_FALSE; + } ++ PHP_LIBXML_RESTORE_GLOBALS(validate); + + xmlFreeValidCtxt(cvp); + +@@ -1843,14 +1848,18 @@ static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type + + DOM_GET_OBJ(docp, id, xmlDocPtr, intern); + ++ PHP_LIBXML_SANITIZE_GLOBALS(new_parser_ctxt); ++ + switch (type) { + case DOM_LOAD_FILE: + if (CHECK_NULL_PATH(source, source_len)) { ++ PHP_LIBXML_RESTORE_GLOBALS(new_parser_ctxt); + php_error_docref(NULL, E_WARNING, "Invalid Schema file source"); + RETURN_FALSE; + } + valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN); + if (!valid_file) { ++ PHP_LIBXML_RESTORE_GLOBALS(new_parser_ctxt); + php_error_docref(NULL, E_WARNING, "Invalid Schema file source"); + RETURN_FALSE; + } +@@ -1871,6 +1880,7 @@ static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type + parser); + sptr = xmlSchemaParse(parser); + xmlSchemaFreeParserCtxt(parser); ++ PHP_LIBXML_RESTORE_GLOBALS(new_parser_ctxt); + if (!sptr) { + php_error_docref(NULL, E_WARNING, "Invalid Schema"); + RETURN_FALSE; +@@ -1889,11 +1899,13 @@ static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type + valid_opts |= XML_SCHEMA_VAL_VC_I_CREATE; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(validate); + xmlSchemaSetValidOptions(vptr, valid_opts); + xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr); + is_valid = xmlSchemaValidateDoc(vptr, docp); + xmlSchemaFree(sptr); + xmlSchemaFreeValidCtxt(vptr); ++ PHP_LIBXML_RESTORE_GLOBALS(validate); + + if (is_valid == 0) { + RETURN_TRUE; +@@ -1964,12 +1976,14 @@ static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int typ + return; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(parse); + xmlRelaxNGSetParserErrors(parser, + (xmlRelaxNGValidityErrorFunc) php_libxml_error_handler, + (xmlRelaxNGValidityWarningFunc) php_libxml_error_handler, + parser); + sptr = xmlRelaxNGParse(parser); + xmlRelaxNGFreeParserCtxt(parser); ++ PHP_LIBXML_RESTORE_GLOBALS(parse); + if (!sptr) { + php_error_docref(NULL, E_WARNING, "Invalid RelaxNG"); + RETURN_FALSE; +@@ -2068,6 +2082,7 @@ static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */ + ctxt->sax->error = php_libxml_ctx_error; + ctxt->sax->warning = php_libxml_ctx_warning; + } ++ php_libxml_sanitize_parse_ctxt_options(ctxt); + if (options) { + htmlCtxtUseOptions(ctxt, (int)options); + } +diff --git a/ext/dom/documentfragment.c b/ext/dom/documentfragment.c +index 9b22258..711c42f 100644 +--- a/ext/dom/documentfragment.c ++++ b/ext/dom/documentfragment.c +@@ -131,7 +131,9 @@ PHP_METHOD(domdocumentfragment, appendXML) { + } + + if (data) { ++ PHP_LIBXML_SANITIZE_GLOBALS(parse); + err = xmlParseBalancedChunkMemory(nodep->doc, NULL, NULL, 0, (xmlChar *) data, &lst); ++ PHP_LIBXML_RESTORE_GLOBALS(parse); + if (err != 0) { + RETURN_FALSE; + } +diff --git a/ext/dom/tests/DOMDocument_loadXML_error2_gte2_11.phpt b/ext/dom/tests/DOMDocument_loadXML_error2_gte2_11.phpt +new file mode 100644 +index 0000000..ff5ceb3 +--- /dev/null ++++ b/ext/dom/tests/DOMDocument_loadXML_error2_gte2_11.phpt +@@ -0,0 +1,34 @@ ++--TEST-- ++Test DOMDocument::loadXML() detects not-well formed XML ++--SKIPIF-- ++= 2.11'); ++?> ++--DESCRIPTION-- ++This test verifies the method detects attributes values not closed between " or ' ++Environment variables used in the test: ++- XML_FILE: the xml file to load ++- LOAD_OPTIONS: the second parameter to pass to the method ++- EXPECTED_RESULT: the expected result ++--CREDITS-- ++Antonio Diaz Ruiz ++--INI-- ++assert.bail=true ++--EXTENSIONS-- ++dom ++--ENV-- ++XML_FILE=/not_well_formed2.xml ++LOAD_OPTIONS=0 ++EXPECTED_RESULT=0 ++--FILE_EXTERNAL-- ++domdocumentloadxml_test_method.inc ++--EXPECTF-- ++Warning: DOMDocument::loadXML(): AttValue: " or ' expected in Entity, line: 4 in %s on line %d ++ ++Warning: DOMDocument::loadXML(): internal error: xmlParseStartTag: problem parsing attributes in Entity, line: 4 in %s on line %d ++ ++Warning: DOMDocument::loadXML(): Couldn't find end of Start Tag book line 4 in Entity, line: 4 in %s on line %d ++ ++Warning: DOMDocument::loadXML(): Opening and ending tag mismatch: books line 3 and book in Entity, line: 7 in %s on line %d ++ ++Warning: DOMDocument::loadXML(): Extra content at the end of the document in Entity, line: 8 in %s on line %d +diff --git a/ext/dom/tests/DOMDocument_loadXML_error2.phpt b/ext/dom/tests/DOMDocument_loadXML_error2_pre2_11.phpt +similarity index 89% +rename from ext/dom/tests/DOMDocument_loadXML_error2.phpt +rename to ext/dom/tests/DOMDocument_loadXML_error2_pre2_11.phpt +index 6d56a31..7e10771 100644 +--- a/ext/dom/tests/DOMDocument_loadXML_error2.phpt ++++ b/ext/dom/tests/DOMDocument_loadXML_error2_pre2_11.phpt +@@ -1,5 +1,10 @@ + --TEST-- + Test DOMDocument::loadXML() detects not-well formed XML ++--SKIPIF-- ++= 21100) die('skip libxml2 test variant for version < 2.11'); ++?> + --DESCRIPTION-- + This test verifies the method detects attributes values not closed between " or ' + Environment variables used in the test: +@@ -10,8 +15,6 @@ Environment variables used in the test: + Antonio Diaz Ruiz + --INI-- + assert.bail=true +---SKIPIF-- +- + --ENV-- + XML_FILE=/not_well_formed2.xml + LOAD_OPTIONS=0 +diff --git a/ext/dom/tests/DOMDocument_load_error2_gte2_11.phpt b/ext/dom/tests/DOMDocument_load_error2_gte2_11.phpt +new file mode 100644 +index 0000000..32b6bf1 +--- /dev/null ++++ b/ext/dom/tests/DOMDocument_load_error2_gte2_11.phpt +@@ -0,0 +1,34 @@ ++--TEST-- ++Test DOMDocument::load() detects not-well formed ++--SKIPIF-- ++= 2.11'); ++?> ++--DESCRIPTION-- ++This test verifies the method detects attributes values not closed between " or ' ++Environment variables used in the test: ++- XML_FILE: the xml file to load ++- LOAD_OPTIONS: the second parameter to pass to the method ++- EXPECTED_RESULT: the expected result ++--CREDITS-- ++Antonio Diaz Ruiz ++--INI-- ++assert.bail=true ++--EXTENSIONS-- ++dom ++--ENV-- ++XML_FILE=/not_well_formed2.xml ++LOAD_OPTIONS=0 ++EXPECTED_RESULT=0 ++--FILE_EXTERNAL-- ++domdocumentload_test_method.inc ++--EXPECTF-- ++Warning: DOMDocument::load(): AttValue: " or ' expected in %s on line %d ++ ++Warning: DOMDocument::load(): internal error: xmlParseStartTag: problem parsing attributes in %s on line %d ++ ++Warning: DOMDocument::load(): Couldn't find end of Start Tag book line 4 in %s on line %d ++ ++Warning: DOMDocument::load(): Opening and ending tag mismatch: books line 3 and book in %s on line %d ++ ++Warning: DOMDocument::load(): Extra content at the end of the document in %s on line %d +diff --git a/ext/dom/tests/DOMDocument_load_error2.phpt b/ext/dom/tests/DOMDocument_load_error2_pre2_11.phpt +similarity index 89% +rename from ext/dom/tests/DOMDocument_load_error2.phpt +rename to ext/dom/tests/DOMDocument_load_error2_pre2_11.phpt +index f450cf1..74b20c1 100644 +--- a/ext/dom/tests/DOMDocument_load_error2.phpt ++++ b/ext/dom/tests/DOMDocument_load_error2_pre2_11.phpt +@@ -1,5 +1,10 @@ + --TEST-- + Test DOMDocument::load() detects not-well formed XML ++--SKIPIF-- ++= 21100) die('skip libxml2 test variant for version < 2.11'); ++?> + --DESCRIPTION-- + This test verifies the method detects attributes values not closed between " or ' + Environment variables used in the test: +@@ -10,8 +15,6 @@ Environment variables used in the test: + Antonio Diaz Ruiz + --INI-- + assert.bail=true +---SKIPIF-- +- + --ENV-- + XML_FILE=/not_well_formed2.xml + LOAD_OPTIONS=0 +diff --git a/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt +new file mode 100644 +index 0000000..87cb2aa +--- /dev/null ++++ b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt +@@ -0,0 +1,60 @@ ++--TEST-- ++GHSA-p3x9-6h7p-cgfc: libxml streams use wrong `content-type` header when requesting a redirected resource (Basic) ++--EXTENSIONS-- ++dom ++--SKIPIF-- ++ ++--FILE-- ++ ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++ EOT; ++ // Intentionally using non-standard casing for content-type to verify it is matched not case sensitively. ++ yield "data://text/plain,HTTP/1.1 200 OK\r\nconteNt-tyPe: text/html; charset=utf-8\r\n\r\n{$xml}"; ++} ++ ++['pid' => $pid, 'uri' => $uri] = http_server('genResponses', $output); ++$document = new \DOMDocument(); ++$document->loadHTMLFile($uri); ++ ++$h1 = $document->getElementsByTagName('h1'); ++var_dump($h1->length); ++var_dump($document->saveHTML()); ++http_server_kill($pid); ++?> ++--EXPECT-- ++int(1) ++string(266) " ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++" +diff --git a/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt +new file mode 100644 +index 0000000..1ce468c +--- /dev/null ++++ b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt +@@ -0,0 +1,60 @@ ++--TEST-- ++GHSA-p3x9-6h7p-cgfc: libxml streams use wrong `content-type` header when requesting a redirected resource (Missing content-type) ++--EXTENSIONS-- ++dom ++--SKIPIF-- ++ ++--FILE-- ++ ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++ EOT; ++ // Missing content-type in actual response. ++ yield "data://text/plain,HTTP/1.1 200 OK\r\n\r\n{$xml}"; ++} ++ ++['pid' => $pid, 'uri' => $uri] = http_server('genResponses', $output); ++$document = new \DOMDocument(); ++$document->loadHTMLFile($uri); ++ ++$h1 = $document->getElementsByTagName('h1'); ++var_dump($h1->length); ++var_dump($document->saveHTML()); ++http_server_kill($pid); ++?> ++--EXPECT-- ++int(1) ++string(266) " ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++" +diff --git a/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_003.phpt b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_003.phpt +new file mode 100644 +index 0000000..b8cac7e +--- /dev/null ++++ b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_003.phpt +@@ -0,0 +1,60 @@ ++--TEST-- ++GHSA-p3x9-6h7p-cgfc: libxml streams use wrong `content-type` header when requesting a redirected resource (Reason with colon) ++--EXTENSIONS-- ++dom ++--SKIPIF-- ++ ++--FILE-- ++ ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++ EOT; ++ // Missing content-type in actual response. ++ yield "data://text/plain,HTTP/1.1 200 OK: This is fine\r\n\r\n{$xml}"; ++} ++ ++['pid' => $pid, 'uri' => $uri] = http_server('genResponses', $output); ++$document = new \DOMDocument(); ++$document->loadHTMLFile($uri); ++ ++$h1 = $document->getElementsByTagName('h1'); ++var_dump($h1->length); ++var_dump($document->saveHTML()); ++http_server_kill($pid); ++?> ++--EXPECT-- ++int(1) ++string(266) " ++ ++ ++ GHSA-p3x9-6h7p-cgfc ++ ++ ++ ++ ++ ++ ++

GHSA-p3x9-6h7p-cgfc

++ ++ ++" +diff --git a/ext/dom/tests/libxml_global_state_entity_loader_bypass.phpt b/ext/dom/tests/libxml_global_state_entity_loader_bypass.phpt +new file mode 100644 +index 0000000..7fc2a24 +--- /dev/null ++++ b/ext/dom/tests/libxml_global_state_entity_loader_bypass.phpt +@@ -0,0 +1,37 @@ ++--TEST-- ++GHSA-3qrf-m4j2-pcrr (libxml global state entity loader bypass) ++--SKIPIF-- ++ ++--FILE-- ++ %bork;]>"; ++ ++libxml_use_internal_errors(true); ++ ++function parseXML($xml) { ++ $doc = new DOMDocument(); ++ @$doc->loadXML($xml); ++ $doc->createDocumentFragment()->appendXML("&bork;"); ++ foreach (libxml_get_errors() as $error) { ++ var_dump(trim($error->message)); ++ } ++} ++ ++parseXML($xml); ++zend_test_override_libxml_global_state(); ++parseXML($xml); ++ ++echo "Done\n"; ++ ++?> ++--EXPECT-- ++string(25) "Entity 'bork' not defined" ++string(25) "Entity 'bork' not defined" ++string(25) "Entity 'bork' not defined" ++Done +diff --git a/ext/filter/logical_filters.c b/ext/filter/logical_filters.c +index e5e87c0..5cc019e 100644 +--- a/ext/filter/logical_filters.c ++++ b/ext/filter/logical_filters.c +@@ -91,7 +91,7 @@ + #define FORMAT_IPV4 4 + #define FORMAT_IPV6 6 + +-static int _php_filter_validate_ipv6(char *str, size_t str_len, int ip[8]); ++static int _php_filter_validate_ipv6(const char *str, size_t str_len, int ip[8]); + + static int php_filter_parse_int(const char *str, size_t str_len, zend_long *ret) { /* {{{ */ + zend_long ctx_value; +@@ -519,21 +519,21 @@ static int _php_filter_validate_domain(char * domain, int len, zend_long flags) + } + + /* First char must be alphanumeric */ +- if(*s == '.' || (hostname && !isalnum((int)*(unsigned char *)s))) { ++ if(*s == '.' || (hostname && !isalnum((unsigned char)*s))) { + return 0; + } + + while (s < e) { + if (*s == '.') { + /* The first and the last character of a label must be alphanumeric */ +- if (*(s + 1) == '.' || (hostname && (!isalnum((int)*(unsigned char *)(s - 1)) || !isalnum((int)*(unsigned char *)(s + 1))))) { ++ if (*(s + 1) == '.' || (hostname && (!isalnum((unsigned char)s[-1]) || !isalnum((unsigned char)s[1])))) { + return 0; + } + + /* Reset label length counter */ + i = 1; + } else { +- if (i > 63 || (hostname && *s != '-' && !isalnum((int)*(unsigned char *)s))) { ++ if (i > 63 || (hostname && *s != '-' && !isalnum((unsigned char)*s))) { + return 0; + } + +@@ -560,9 +560,9 @@ static int is_userinfo_valid(zend_string *str) + const char *valid = "-._~!$&'()*+,;=:"; + const char *p = ZSTR_VAL(str); + while (p - ZSTR_VAL(str) < ZSTR_LEN(str)) { +- if (isalpha(*p) || isdigit(*p) || strchr(valid, *p)) { ++ if (isalpha((unsigned char)*p) || isdigit((unsigned char)*p) || strchr(valid, *p)) { + p++; +- } else if (*p == '%' && p - ZSTR_VAL(str) <= ZSTR_LEN(str) - 3 && isdigit(*(p+1)) && isxdigit(*(p+2))) { ++ } else if (*p == '%' && p - ZSTR_VAL(str) <= ZSTR_LEN(str) - 3 && isdigit((unsigned char)p[1]) && isxdigit((unsigned char)p[2])) { + p += 3; + } else { + return 0; +@@ -571,6 +571,14 @@ static int is_userinfo_valid(zend_string *str) + return 1; + } + ++static zend_bool php_filter_is_valid_ipv6_hostname(const char *s, size_t l) ++{ ++ const char *e = s + l; ++ const char *t = e - 1; ++ ++ return *s == '[' && *t == ']' && _php_filter_validate_ipv6(s + 1, l - 2, NULL); ++} ++ + void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ + { + php_url *url; +@@ -596,7 +604,7 @@ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ + + if (url->scheme != NULL && + (zend_string_equals_literal_ci(url->scheme, "http") || zend_string_equals_literal_ci(url->scheme, "https"))) { +- char *e, *s, *t; ++ const char *s; + size_t l; + + if (url->host == NULL) { +@@ -605,17 +613,14 @@ void php_filter_validate_url(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */ + + s = ZSTR_VAL(url->host); + l = ZSTR_LEN(url->host); +- e = s + l; +- t = e - 1; +- +- /* An IPv6 enclosed by square brackets is a valid hostname */ +- if (*s == '[' && *t == ']' && _php_filter_validate_ipv6((s + 1), l - 2, NULL)) { +- php_url_free(url); +- return; +- } + +- // Validate domain +- if (!_php_filter_validate_domain(ZSTR_VAL(url->host), l, FILTER_FLAG_HOSTNAME)) { ++ if ( ++ /* An IPv6 enclosed by square brackets is a valid hostname.*/ ++ !php_filter_is_valid_ipv6_hostname(s, l) && ++ /* Validate domain. ++ * This includes a loose check for an IPv4 address. */ ++ !_php_filter_validate_domain(ZSTR_VAL(url->host), l, FILTER_FLAG_HOSTNAME) ++ ) { + php_url_free(url); + RETURN_VALIDATION_FAILED + } +@@ -749,15 +754,15 @@ static int _php_filter_validate_ipv4(char *str, size_t str_len, int *ip) /* {{{ + } + /* }}} */ + +-static int _php_filter_validate_ipv6(char *str, size_t str_len, int ip[8]) /* {{{ */ ++static int _php_filter_validate_ipv6(const char *str, size_t str_len, int ip[8]) /* {{{ */ + { + int compressed_pos = -1; + int blocks = 0; + int num, n, i; + char *ipv4; +- char *end; ++ const char *end; + int ip4elm[4]; +- char *s = str; ++ const char *s = str; + + if (!memchr(str, ':', str_len)) { + return 0; +diff --git a/ext/filter/sanitizing_filters.c b/ext/filter/sanitizing_filters.c +index c17dc02..47f7a62 100644 +--- a/ext/filter/sanitizing_filters.c ++++ b/ext/filter/sanitizing_filters.c +@@ -69,7 +69,7 @@ static void php_filter_encode_url(zval *value, const unsigned char* chars, const + unsigned char *e = s + char_len; + zend_string *str; + +- memset(tmp, 1, sizeof(tmp)-1); ++ memset(tmp, 1, sizeof(tmp)); + + while (s < e) { + tmp[*s++] = '\0'; +diff --git a/ext/filter/tests/filter_sanitize_encoded_0xff.phpt b/ext/filter/tests/filter_sanitize_encoded_0xff.phpt +new file mode 100644 +index 0000000..1ee61ab +--- /dev/null ++++ b/ext/filter/tests/filter_sanitize_encoded_0xff.phpt +@@ -0,0 +1,12 @@ ++--TEST-- ++FILTER_SANITIZE_ENCODED percent-encodes 0xFF ++--EXTENSIONS-- ++filter ++--FILE-- ++ ++--EXPECT-- ++string(3) "%FF" ++string(10) "%FE%FF%00A" +diff --git a/ext/filter/tests/ghsa-w8qr-v226-r27w.phpt b/ext/filter/tests/ghsa-w8qr-v226-r27w.phpt +new file mode 100644 +index 0000000..0092408 +--- /dev/null ++++ b/ext/filter/tests/ghsa-w8qr-v226-r27w.phpt +@@ -0,0 +1,41 @@ ++--TEST-- ++GHSA-w8qr-v226-r27w ++--EXTENSIONS-- ++filter ++--FILE-- ++ ++--EXPECT-- ++--- These ones should fail --- ++bool(false) ++bool(false) ++bool(false) ++bool(false) ++bool(false) ++bool(false) ++bool(false) ++bool(false) ++--- These ones should work --- ++string(21) "http://test@127.0.0.1" ++string(50) "http://test@[2001:db8:3333:4444:5555:6666:1.2.3.4]" ++string(17) "http://test@[::1]" +diff --git a/ext/ftp/ftp.c b/ext/ftp/ftp.c +index a11aa32..13d3264 100644 +--- a/ext/ftp/ftp.c ++++ b/ext/ftp/ftp.c +@@ -513,7 +513,7 @@ ftp_raw(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, zval *return_value + array_init(return_value); + while (ftp_readline(ftp)) { + add_next_index_string(return_value, ftp->inbuf); +- if (isdigit(ftp->inbuf[0]) && isdigit(ftp->inbuf[1]) && isdigit(ftp->inbuf[2]) && ftp->inbuf[3] == ' ') { ++ if (isdigit((unsigned char)ftp->inbuf[0]) && isdigit((unsigned char)ftp->inbuf[1]) && isdigit((unsigned char)ftp->inbuf[2]) && ftp->inbuf[3] == ' ') { + return; + } + } +@@ -867,7 +867,7 @@ ftp_pasv(ftpbuf_t *ftp, int pasv) + return 0; + } + /* parse out the IP and port */ +- for (ptr = ftp->inbuf; *ptr && !isdigit(*ptr); ptr++); ++ for (ptr = ftp->inbuf; *ptr && !isdigit((unsigned char)*ptr); ptr++); + n = sscanf(ptr, "%lu,%lu,%lu,%lu,%lu,%lu", &b[0], &b[1], &b[2], &b[3], &b[4], &b[5]); + if (n != 6) { + return 0; +@@ -1178,7 +1178,7 @@ ftp_mdtm(ftpbuf_t *ftp, const char *path, const size_t path_len) + return -1; + } + /* parse out the timestamp */ +- for (ptr = ftp->inbuf; *ptr && !isdigit(*ptr); ptr++); ++ for (ptr = ftp->inbuf; *ptr && !isdigit((unsigned char)*ptr); ptr++); + n = sscanf(ptr, "%4u%2u%2u%2u%2u%2u", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec); + if (n != 6) { + return -1; +@@ -1382,13 +1382,13 @@ ftp_getresp(ftpbuf_t *ftp) + } + + /* Break out when the end-tag is found */ +- if (isdigit(ftp->inbuf[0]) && isdigit(ftp->inbuf[1]) && isdigit(ftp->inbuf[2]) && ftp->inbuf[3] == ' ') { ++ if (isdigit((unsigned char)ftp->inbuf[0]) && isdigit((unsigned char)ftp->inbuf[1]) && isdigit((unsigned char)ftp->inbuf[2]) && ftp->inbuf[3] == ' ') { + break; + } + } + + /* translate the tag */ +- if (!isdigit(ftp->inbuf[0]) || !isdigit(ftp->inbuf[1]) || !isdigit(ftp->inbuf[2])) { ++ if (!isdigit((unsigned char)ftp->inbuf[0]) || !isdigit((unsigned char)ftp->inbuf[1]) || !isdigit((unsigned char)ftp->inbuf[2])) { + return 0; + } + +diff --git a/ext/gd/libgd/gd_gif_in.c b/ext/gd/libgd/gd_gif_in.c +index 1f69723..e055f90 100644 +--- a/ext/gd/libgd/gd_gif_in.c ++++ b/ext/gd/libgd/gd_gif_in.c +@@ -450,7 +450,7 @@ LWZReadByte_(gdIOCtx *fd, LZW_STATIC_DATA *sd, char flag, int input_code_size, i + sd->table[1][i] = i; + } + for (; i < (1<table[0][i] = sd->table[1][0] = 0; ++ sd->table[0][i] = sd->table[1][i] = 0; + + sd->sp = sd->stack; + +@@ -494,6 +494,8 @@ LWZReadByte_(gdIOCtx *fd, LZW_STATIC_DATA *sd, char flag, int input_code_size, i + + if (count != 0) + return -2; ++ ++ return -2; + } + + incode = code; +@@ -560,7 +562,7 @@ ReadImage(gdImagePtr im, gdIOCtx *fd, int len, int height, unsigned char (*cmap) + int v; + int xpos = 0, ypos = 0, pass = 0; + int i; +- LZW_STATIC_DATA sd; ++ LZW_STATIC_DATA sd = {0}; + + + /* +diff --git a/ext/gd/libgd/gd_xbm.c b/ext/gd/libgd/gd_xbm.c +index dae2e62..b86dc10 100644 +--- a/ext/gd/libgd/gd_xbm.c ++++ b/ext/gd/libgd/gd_xbm.c +@@ -193,7 +193,7 @@ void gdImageXbmCtx(gdImagePtr image, char* file_name, int fg, gdIOCtx * out) + } else { + for (i=0; i= 0x7f) + + /* validate a modified-base64 character */ +-#define B64CHAR(c) (isalnum(c) || (c) == '+' || (c) == ',') ++#define B64CHAR(c) (isalnum((unsigned char)(c)) || (c) == '+' || (c) == ',') + + /* map the low 64 bits of `n' to the modified-base64 characters */ + #define B64(n) ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ +diff --git a/ext/intl/locale/locale_methods.c b/ext/intl/locale/locale_methods.c +index 1bdfb27..127a12e 100644 +--- a/ext/intl/locale/locale_methods.c ++++ b/ext/intl/locale/locale_methods.c +@@ -1216,7 +1216,7 @@ static int strToMatch(const char* str ,char *retstr) + if( *str == '-' ){ + *retstr = '_'; + } else { +- *retstr = tolower(*str); ++ *retstr = tolower((unsigned char)*str); + } + str++; + retstr++; +diff --git a/ext/ldap/ldap.c b/ext/ldap/ldap.c +index 72a39bd..75adf1b 100644 +--- a/ext/ldap/ldap.c ++++ b/ext/ldap/ldap.c +@@ -49,6 +49,7 @@ + + #include "ext/standard/php_string.h" + #include "ext/standard/info.h" ++#include "Zend/zend_exceptions.h" + + #ifdef HAVE_LDAP_SASL + #include +@@ -3836,13 +3837,23 @@ static zend_string* php_ldap_do_escape(const zend_bool *map, const char *value, + zend_string *ret; + + for (i = 0; i < valuelen; i++) { +- len += (map[(unsigned char) value[i]]) ? 3 : 1; ++ size_t addend = (map[(unsigned char) value[i]]) ? 3 : 1; ++ if (len > ZSTR_MAX_LEN - addend) { ++ return NULL; ++ } ++ len += addend; + } + /* Per RFC 4514, a leading and trailing space must be escaped */ + if ((flags & PHP_LDAP_ESCAPE_DN) && (value[0] == ' ')) { ++ if (len > ZSTR_MAX_LEN - 2) { ++ return NULL; ++ } + len += 2; + } + if ((flags & PHP_LDAP_ESCAPE_DN) && ((valuelen > 1) && (value[valuelen - 1] == ' '))) { ++ if (len > ZSTR_MAX_LEN - 2) { ++ return NULL; ++ } + len += 2; + } + +@@ -3909,7 +3920,13 @@ PHP_FUNCTION(ldap_escape) + php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0); + } + +- RETURN_NEW_STR(php_ldap_do_escape(map, value, valuelen, flags)); ++ zend_string *result = php_ldap_do_escape(map, value, valuelen, flags); ++ if (UNEXPECTED(!result)) { ++ zend_throw_exception(NULL, "Argument #1 ($value) is too long", 0); ++ return; ++ } ++ ++ RETURN_NEW_STR(result); + } + + #ifdef STR_TRANSLATION +diff --git a/ext/ldap/tests/GHSA-g665-fm4p-vhff-1.phpt b/ext/ldap/tests/GHSA-g665-fm4p-vhff-1.phpt +new file mode 100644 +index 0000000..734bbe9 +--- /dev/null ++++ b/ext/ldap/tests/GHSA-g665-fm4p-vhff-1.phpt +@@ -0,0 +1,28 @@ ++--TEST-- ++GHSA-g665-fm4p-vhff (OOB access in ldap_escape) ++--EXTENSIONS-- ++ldap ++--INI-- ++memory_limit=-1 ++--SKIPIF-- ++ ++--FILE-- ++getMessage(), "\n"; ++} ++ ++try { ++ ldap_escape(str_repeat("#", 1431655758).' ', "", LDAP_ESCAPE_DN); ++} catch (Exception $e) { ++ echo $e->getMessage(), "\n"; ++} ++?> ++--EXPECT-- ++ldap_escape(): Argument #1 ($value) is too long ++ldap_escape(): Argument #1 ($value) is too long +diff --git a/ext/ldap/tests/GHSA-g665-fm4p-vhff-2.phpt b/ext/ldap/tests/GHSA-g665-fm4p-vhff-2.phpt +new file mode 100644 +index 0000000..5c1b0fb +--- /dev/null ++++ b/ext/ldap/tests/GHSA-g665-fm4p-vhff-2.phpt +@@ -0,0 +1,29 @@ ++--TEST-- ++GHSA-g665-fm4p-vhff (OOB access in ldap_escape) ++--EXTENSIONS-- ++ldap ++--INI-- ++memory_limit=-1 ++--SKIPIF-- ++ ++--FILE-- ++getMessage(), "\n"; ++} ++ ++// would allocate a string of length 2 ++try { ++ ldap_escape(str_repeat("*", 1431655766), "", LDAP_ESCAPE_FILTER); ++} catch (Exception $e) { ++ echo $e->getMessage(), "\n"; ++} ++?> ++--EXPECT-- ++ldap_escape(): Argument #1 ($value) is too long ++ldap_escape(): Argument #1 ($value) is too long +diff --git a/ext/libxml/libxml.c b/ext/libxml/libxml.c +index d343135..b800b1c 100644 +--- a/ext/libxml/libxml.c ++++ b/ext/libxml/libxml.c +@@ -420,42 +420,53 @@ php_libxml_input_buffer_create_filename(const char *URI, xmlCharEncoding enc) + if (Z_TYPE(s->wrapperdata) == IS_ARRAY) { + zval *header; + +- ZEND_HASH_FOREACH_VAL_IND(Z_ARRVAL(s->wrapperdata), header) { ++ /* Scan backwards: The header array might contain the headers for multiple responses, if ++ * a redirect was followed. ++ */ ++ ZEND_HASH_REVERSE_FOREACH_VAL_IND(Z_ARRVAL(s->wrapperdata), header) { + const char buf[] = "Content-Type:"; +- if (Z_TYPE_P(header) == IS_STRING && +- !zend_binary_strncasecmp(Z_STRVAL_P(header), Z_STRLEN_P(header), buf, sizeof(buf)-1, sizeof(buf)-1)) { +- char *needle = estrdup("charset="); +- char *haystack = estrndup(Z_STRVAL_P(header), Z_STRLEN_P(header)); +- char *encoding = php_stristr(haystack, needle, Z_STRLEN_P(header), sizeof("charset=")-1); +- +- if (encoding) { +- char *end; +- +- encoding += sizeof("charset=")-1; +- if (*encoding == '"') { +- encoding++; +- } +- end = strchr(encoding, ';'); +- if (end == NULL) { +- end = encoding + strlen(encoding); +- } +- end--; /* end == encoding-1 isn't a buffer underrun */ +- while (*end == ' ' || *end == '\t') { +- end--; +- } +- if (*end == '"') { +- end--; +- } +- if (encoding >= end) continue; +- *(end+1) = '\0'; +- enc = xmlParseCharEncoding(encoding); +- if (enc <= XML_CHAR_ENCODING_NONE) { +- enc = XML_CHAR_ENCODING_NONE; ++ if (Z_TYPE_P(header) == IS_STRING) { ++ /* If no colon is found in the header, we assume it's the HTTP status line and bail out. */ ++ char *colon = memchr(Z_STRVAL_P(header), ':', Z_STRLEN_P(header)); ++ char *space = memchr(Z_STRVAL_P(header), ' ', Z_STRLEN_P(header)); ++ if (colon == NULL || space < colon) { ++ break; ++ } ++ ++ if (!zend_binary_strncasecmp(Z_STRVAL_P(header), Z_STRLEN_P(header), buf, sizeof(buf)-1, sizeof(buf)-1)) { ++ char *needle = estrdup("charset="); ++ char *haystack = estrndup(Z_STRVAL_P(header), Z_STRLEN_P(header)); ++ char *encoding = php_stristr(haystack, needle, Z_STRLEN_P(header), sizeof("charset=")-1); ++ ++ if (encoding) { ++ char *end; ++ ++ encoding += sizeof("charset=")-1; ++ if (*encoding == '"') { ++ encoding++; ++ } ++ end = strchr(encoding, ';'); ++ if (end == NULL) { ++ end = encoding + strlen(encoding); ++ } ++ end--; /* end == encoding-1 isn't a buffer underrun */ ++ while (*end == ' ' || *end == '\t') { ++ end--; ++ } ++ if (*end == '"') { ++ end--; ++ } ++ if (encoding >= end) continue; ++ *(end+1) = '\0'; ++ enc = xmlParseCharEncoding(encoding); ++ if (enc <= XML_CHAR_ENCODING_NONE) { ++ enc = XML_CHAR_ENCODING_NONE; ++ } + } ++ efree(haystack); ++ efree(needle); ++ break; /* found content-type */ + } +- efree(haystack); +- efree(needle); +- break; /* found content-type */ + } + } ZEND_HASH_FOREACH_END(); + } +@@ -574,6 +585,8 @@ static void php_libxml_ctx_error_level(int level, void *ctx, const char *msg) + } else { + php_error_docref(NULL, level, "%s in Entity, line: %d", msg, parser->input->line); + } ++ } else { ++ php_error_docref(NULL, E_WARNING, "%s", msg); + } + } + +diff --git a/ext/libxml/php_libxml.h b/ext/libxml/php_libxml.h +index cf936e9..92028d5 100644 +--- a/ext/libxml/php_libxml.h ++++ b/ext/libxml/php_libxml.h +@@ -120,6 +120,42 @@ PHP_LIBXML_API void php_libxml_shutdown(void); + ZEND_TSRMLS_CACHE_EXTERN() + #endif + ++/* Other extension may override the global state options, these global options ++ * are copied initially to ctxt->options. Set the options to a known good value. ++ * See libxml2 globals.c and parserInternals.c. ++ * The unique_name argument allows multiple sanitizes and restores within the ++ * same function, even nested is necessary. */ ++#define PHP_LIBXML_SANITIZE_GLOBALS(unique_name) \ ++ int xml_old_loadsubset_##unique_name = xmlLoadExtDtdDefaultValue; \ ++ xmlLoadExtDtdDefaultValue = 0; \ ++ int xml_old_validate_##unique_name = xmlDoValidityCheckingDefaultValue; \ ++ xmlDoValidityCheckingDefaultValue = 0; \ ++ int xml_old_pedantic_##unique_name = xmlPedanticParserDefault(0); \ ++ int xml_old_substitute_##unique_name = xmlSubstituteEntitiesDefault(0); \ ++ int xml_old_linenrs_##unique_name = xmlLineNumbersDefault(0); \ ++ int xml_old_blanks_##unique_name = xmlKeepBlanksDefault(1); ++ ++#define PHP_LIBXML_RESTORE_GLOBALS(unique_name) \ ++ xmlLoadExtDtdDefaultValue = xml_old_loadsubset_##unique_name; \ ++ xmlDoValidityCheckingDefaultValue = xml_old_validate_##unique_name; \ ++ (void) xmlPedanticParserDefault(xml_old_pedantic_##unique_name); \ ++ (void) xmlSubstituteEntitiesDefault(xml_old_substitute_##unique_name); \ ++ (void) xmlLineNumbersDefault(xml_old_linenrs_##unique_name); \ ++ (void) xmlKeepBlanksDefault(xml_old_blanks_##unique_name); ++ ++/* Alternative for above, working directly on the context and not setting globals. ++ * Generally faster because no locking is involved, and this has the advantage that it sets the options to a known good value. */ ++static zend_always_inline void php_libxml_sanitize_parse_ctxt_options(xmlParserCtxtPtr ctxt) ++{ ++ ctxt->loadsubset = 0; ++ ctxt->validate = 0; ++ ctxt->pedantic = 0; ++ ctxt->replaceEntities = 0; ++ ctxt->linenumbers = 0; ++ ctxt->keepBlanks = 1; ++ ctxt->options = 0; ++} ++ + #else /* HAVE_LIBXML */ + #define libxml_module_ptr NULL + #endif +diff --git a/ext/libxml/tests/bug61367-read_2.phpt b/ext/libxml/tests/bug61367-read_2.phpt +index 8cc0b50..12743ad 100644 +--- a/ext/libxml/tests/bug61367-read_2.phpt ++++ b/ext/libxml/tests/bug61367-read_2.phpt +@@ -55,6 +55,6 @@ bool(true) + int(4) + bool(true) + +-Warning: DOMDocument::loadXML(): I/O warning : failed to load external entity "file:///%s/test_bug_61367-read/bad" in %s on line %d ++Warning: DOMDocument::loadXML(): %Sfailed to load external entity "file:///%s/test_bug_61367-read/bad" in %s on line %d + + Notice: Trying to get property 'nodeValue' of non-object in %s on line %d +diff --git a/ext/libxml/tests/libxml_disable_entity_loader_2.phpt b/ext/libxml/tests/libxml_disable_entity_loader_2.phpt +index 845bd4b..55d8e61 100644 +--- a/ext/libxml/tests/libxml_disable_entity_loader_2.phpt ++++ b/ext/libxml/tests/libxml_disable_entity_loader_2.phpt +@@ -36,6 +36,6 @@ echo "Done\n"; + bool(true) + bool(false) + +-Warning: DOMDocument::loadXML(): I/O warning : failed to load external entity "%s" in %s on line %d ++Warning: DOMDocument::loadXML(): %Sfailed to load external entity "%s" in %s on line %d + bool(true) + Done +diff --git a/ext/libxml/tests/libxml_set_external_entity_loader_error1.phpt b/ext/libxml/tests/libxml_set_external_entity_loader_error1.phpt +index 40b31ea..00e06eb 100644 +--- a/ext/libxml/tests/libxml_set_external_entity_loader_error1.phpt ++++ b/ext/libxml/tests/libxml_set_external_entity_loader_error1.phpt +@@ -35,6 +35,8 @@ Warning: libxml_set_external_entity_loader() expects exactly 1 parameter, 2 give + NULL + bool(true) + ++Warning: DOMDocument::validate(): Call to user entity loader callback %s ++ + Warning: DOMDocument::validate(): Could not load the external subset "http://example.com/foobar" in %s on line %d + Exception: Too few arguments to function {closure}(), 3 passed and exactly 4 expected + Done. +diff --git a/ext/libxml/tests/libxml_set_external_entity_loader_variation2.phpt b/ext/libxml/tests/libxml_set_external_entity_loader_variation2.phpt +index e51869c..0664de1 100644 +--- a/ext/libxml/tests/libxml_set_external_entity_loader_variation2.phpt ++++ b/ext/libxml/tests/libxml_set_external_entity_loader_variation2.phpt +@@ -38,6 +38,8 @@ echo "Done.\n"; + string(10) "-//FOO/BAR" + string(%d) "%sfoobar.dtd" + ++Warning: DOMDocument::validate(): Failed to load external entity "-//FOO/BAR" in %s on line %d ++ + Warning: DOMDocument::validate(): Could not load the external subset "foobar.dtd" in %s on line %d + bool(false) + bool(true) +diff --git a/ext/mbstring/mbstring.c b/ext/mbstring/mbstring.c +index f170b93..2d63693 100644 +--- a/ext/mbstring/mbstring.c ++++ b/ext/mbstring/mbstring.c +@@ -1176,7 +1176,7 @@ static char *php_mb_rfc1867_getword(const zend_encoding *encoding, char **line, + + static char *php_mb_rfc1867_getword_conf(const zend_encoding *encoding, char *str) /* {{{ */ + { +- while (*str && isspace(*(unsigned char *)str)) { ++ while (*str && isspace((unsigned char)*str)) { + ++str; + } + +@@ -1192,7 +1192,7 @@ static char *php_mb_rfc1867_getword_conf(const zend_encoding *encoding, char *st + } else { + char *strend = str; + +- while (*strend && !isspace(*(unsigned char *)strend)) { ++ while (*strend && !isspace((unsigned char)*strend)) { + ++strend; + } + return php_mb_rfc1867_substring_conf(encoding, str, strend - str, 0); +diff --git a/ext/mbstring/php_mbregex.c b/ext/mbstring/php_mbregex.c +index 76aff4f..791d4b0 100644 +--- a/ext/mbstring/php_mbregex.c ++++ b/ext/mbstring/php_mbregex.c +@@ -777,7 +777,7 @@ static inline void mb_regex_substitute( + continue; + } + if (name_end[0] == delim) break; +- if (maybe_num && !isdigit(name_end[0])) maybe_num = 0; ++ if (maybe_num && !isdigit((unsigned char)name_end[0])) maybe_num = 0; + name_end++; + } + p = name_end + 1; +diff --git a/ext/mysqli/tests/fake_server.inc b/ext/mysqli/tests/fake_server.inc +new file mode 100644 +index 0000000..b4e0e41 +--- /dev/null ++++ b/ext/mysqli/tests/fake_server.inc +@@ -0,0 +1,1451 @@ ++ [ ++ 'type' => '03', ++ 'charset' => '3f00', ++ 'length' => '0b000000', ++ 'flags' => '0110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '080000', ++ 'query_data_value' => '023134', ++ 'stmt_data_packet_length' => '0b0000', ++ 'stmt_data_value' => '0e000000' ++ ], ++ 'fltval' => [ ++ 'type' => '04', ++ 'charset' => '3f00', ++ 'length' => '0c000000', ++ 'flags' => '0110', ++ 'decimal' => '1f', ++ 'query_data_packet_length' => '090000', ++ 'query_data_value' => '03322e33', ++ 'stmt_data_packet_length' => '0b0000', ++ 'stmt_data_value' => '33331340', ++ ], ++ 'dblval' => [ ++ 'type' => '05', ++ 'charset' => '3f00', ++ 'length' => '16000000', ++ 'flags' => '0110', ++ 'decimal' => '1f', ++ 'query_data_packet_length' => '090000', ++ 'query_data_value' => '03312e32', ++ 'stmt_data_packet_length' => '0f0000', ++ 'stmt_data_value' => '333333333333f33f' ++ ], ++ 'datval' => [ ++ 'type' => '0a', ++ 'charset' => '3f00', ++ 'length' => '0a000000', ++ 'flags' => '8110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '100000', ++ 'query_data_value' => '0a323031342d31322d3135', ++ 'stmt_data_packet_length' => '0c0000', ++ 'stmt_data_value' => '04de070c0f' ++ ], ++ 'timval' => [ ++ 'type' => '0b', ++ 'charset' => '3f00', ++ 'length' => '0a000000', ++ 'flags' => '8110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '0e0000', ++ 'query_data_value' => '0831333a30303a3032', ++ 'stmt_data_packet_length' => '100000', ++ 'stmt_data_value' => '080000000000150801' ++ ], ++ 'dtival' => [ ++ 'type' => '0c', ++ 'charset' => '3f00', ++ 'length' => '13000000', ++ 'flags' => '8110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '190000', ++ 'query_data_value' => '13323031342d31322d31362031333a30303a3031', ++ 'stmt_data_packet_length' => '0f0000', ++ 'stmt_data_value' => '07de070c100d0001' ++ ], ++ 'bitval' => [ ++ 'type' => '10', ++ 'charset' => '3f00', ++ 'length' => '40000000', ++ 'flags' => '2110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '0e0000', ++ 'query_data_value' => '080808080808080808', ++ 'stmt_data_packet_length' => '100000', ++ 'stmt_data_value' => '080808080808080808' ++ ], ++ 'strval' => [ ++ 'type' => 'fd', ++ 'charset' => 'e000', ++ 'length' => 'c8000000', ++ 'flags' => '0110', ++ 'decimal' => '00', ++ 'query_data_packet_length' => '0a0000', ++ 'query_data_value' => '0474657374', ++ 'stmt_data_packet_length' => '0c0000', ++ 'stmt_data_value' => '0474657374' ++ ], ++ ]; ++} ++ ++function my_mysqli_data_field(string $field): array ++{ ++ $fields = my_mysqli_data_fields(); ++ if (!isset($fields[$field])) { ++ throw new Exception("Unknown field $field"); ++ } ++ return $fields[$field]; ++} ++ ++ ++ ++class my_mysqli_fake_packet_item ++{ ++ public function __construct($name, string $value, bool $is_hex = true) ++ { ++ $this->name = $name; ++ $this->value = $value; ++ $this->is_hex = $is_hex; ++ } ++} ++ ++class my_mysqli_fake_packet ++{ ++ private array $data = array(); ++ ++ public function __get(string $name) ++ { ++ foreach ($this->data as $item) { ++ if ($item->name === $name) { ++ return $item->value; ++ } ++ } ++ return null; ++ } ++ ++ public function __set(string $name, $value) ++ { ++ if ($value instanceof my_mysqli_fake_packet_item) { ++ if ($value->name === null) { ++ $value->name = $name; ++ } ++ } else { ++ $value = new my_mysqli_fake_packet_item($name, $value, true); ++ } ++ ++ for ($i = 0; $i < count($this->data); $i++) { ++ if ($this->data[$i]->name === $name) { ++ $this->data[$i] = $value; ++ return; ++ } ++ } ++ ++ $this->data[] = $value; ++ } ++ ++ public function to_bytes() ++ { ++ $bytes = ''; ++ foreach ($this->data as $item) { ++ $bytes .= $item->is_hex ? hex2bin($item->value) : $item->value; ++ } ++ return $bytes; ++ } ++} ++ ++class my_mysqli_fake_packet_generator ++{ ++ public static function create_packet_item($value, bool $is_hex = false, string $format = 'v') ++ { ++ if (is_string($value)) { ++ $packed_value = $value; ++ } else { ++ $packed_value = pack($format, $value); ++ } ++ return new my_mysqli_fake_packet_item(null, $packed_value, $is_hex); ++ } ++ ++ public function server_ok($number = "02") ++ { ++ $packet = new my_mysqli_fake_packet(); ++ $packet->packet_length = "070000"; ++ $packet->packet_number = $number; ++ $packet->header = "00"; // OK ++ $packet->affected_rows = "00"; ++ $packet->last_insert_id = "00"; ++ $packet->server_status = "0200"; ++ $packet->warning_count = "0000"; ++ return $packet; ++ } ++ ++ public function server_eof() ++ { ++ $packet = new my_mysqli_fake_packet(); ++ $packet->packet_length = "050000"; ++ $packet->packet_number = "01"; ++ $packet->header = "fe"; // EOF ++ $packet->warning_count = "0000"; ++ $packet->server_status = "0200"; ++ return $packet; ++ } ++ ++ public function server_greetings() ++ { ++ $packet = new my_mysqli_fake_packet(); ++ $packet->packet_length = "580000"; ++ $packet->packet_number = "00"; ++ $packet->proto_version = "0a"; ++ $packet->version = self::create_packet_item('5.5.5-10.5.18-MariaDB' . chr(0)); ++ $packet->thread_id = "03000000"; ++ $packet->salt = "473e3f6047257c67"; ++ $packet->filler = "00"; ++ $packet->server_capabilities = self::create_packet_item(0b1111011111111110); ++ $packet->server_character_set = "08"; ++ $packet->server_status = self::create_packet_item(0b000000000000010); ++ $packet->extended_server_capabilities = self::create_packet_item(0b1000000111111111); ++ $packet->auth_plugin = "15"; ++ $packet->unused = "000000000000"; ++ $packet->mariadb_extended_server_capabilities = self::create_packet_item(0b1111, false, 'V'); ++ $packet->mariadb_extended_server_capabilities_salt = "6c6b55463f49335f686c643100"; ++ $packet->mariadb_extended_server_capabilities_auth_plugin = self::create_packet_item('mysql_native_password'); ++ ++ return $packet; ++ } ++ ++ public function server_greetings_sha256(): my_mysqli_fake_packet ++ { ++ $packet = $this->server_greetings(); ++ // 6 bytes shorter than the default mysql_native_password greeting ++ $packet->packet_length = "520000"; ++ $packet->mariadb_extended_server_capabilities_auth_plugin = ++ self::create_packet_item('sha256_password'); ++ ++ return $packet; ++ } ++ public function server_greetings_caching_sha2(): my_mysqli_fake_packet ++ { ++ $packet = $this->server_greetings(); ++ // same length as the default mysql_native_password so the length stays ++ $packet->mariadb_extended_server_capabilities_auth_plugin = ++ self::create_packet_item('caching_sha2_password'); ++ ++ return $packet; ++ } ++ public function server_tabular_query_response() ++ { ++ $qr1 = new my_mysqli_fake_packet(); ++ $qr1->packet_length = "010000"; ++ $qr1->packet_number = "01"; ++ $qr1->field_count = "01"; ++ ++ $qr2 = new my_mysqli_fake_packet(); ++ $qr2->packet_length = "190000"; ++ $qr2->packet_number = "02"; ++ $qr2->catalog_length_plus_name = "0164"; ++ $qr2->db_length_plus_name = "0164"; ++ $qr2->table_length_plus_name = "0164"; ++ $qr2->original_t = "0164"; ++ $qr2->name_length_plus_name = "0164"; ++ $qr2->original_n = "0164"; ++ $qr2->canary = "0c"; ++ $qr2->charset = "3f00"; ++ $qr2->length = "0b000000"; ++ $qr2->type = "03"; ++ $qr2->flags = "0350"; ++ $qr2->decimals = "000000"; ++ ++ $qr3 = new my_mysqli_fake_packet(); ++ $qr3->full = "05000003fe00002200"; ++ ++ $qr4 = new my_mysqli_fake_packet(); ++ $qr4->full = "0400000401350174"; ++ ++ $qr5 = new my_mysqli_fake_packet(); ++ $qr5->full = "05000005fe00002200"; ++ ++ return [$qr1, $qr2, $qr3, $qr4, $qr5]; ++ } ++ ++ public function server_upsert_query_response() ++ { ++ $qr1 = new my_mysqli_fake_packet(); ++ $qr1->packet_length = "010000"; ++ $qr1->packet_number = "01"; ++ $qr1->field_count = "00"; // UPSERT ++ $qr1->affected_rows = "00"; ++ $qr1->last_insert_id = "00"; ++ $qr1->server_status = "0000"; ++ $qr1->warning_count = "0000"; ++ $qr1->len = "01"; ++ $qr1->filename = "65"; ++ $qr1->packet_length = sprintf("%02x0000", strlen($qr1->to_bytes())-4); ++ ++ return [$qr1]; ++ } ++ ++ public function server_upsert_result_response(): my_mysqli_fake_packet ++ { ++ $ur = new my_mysqli_fake_packet(); ++ $ur->packet_length = "300000"; ++ $ur->packet_number = "01"; ++ $ur->field_count = "00"; // UPSERT ++ $ur->affected_rows = "00"; ++ $ur->last_insert_id = "00"; ++ $ur->server_status = "0002"; ++ $ur->warning_count = "0000"; ++ $ur->payload = "28526f7773206d6174636865643a203120204368616e6765643a203020205761726e696e67733a2030"; ++ ++ return $ur; ++ } ++ ++ public function server_stmt_prepare_response_start($num_field) ++ { ++ $pr1 = new my_mysqli_fake_packet(); ++ $pr1->packet_length = "0c0000"; ++ $pr1->packet_number = "01"; ++ $pr1->response_code = '00'; // OK ++ $pr1->statement_id = '01000000'; ++ $pr1->num_fields = $num_field; ++ $pr1->num_params = '0000'; ++ $pr1->filler = '00'; ++ $pr1->warnings = '0000'; ++ ++ return $pr1; ++ } ++ ++ public function server_stmt_prepare_response_end($packer_number) ++ { ++ $pr3 = new my_mysqli_fake_packet(); ++ $pr3->packet_length = "050000"; ++ $pr3->packet_number = $packer_number; ++ $pr3->packet_type = 'fe'; // EOF ++ $pr3->warnings = '0000'; ++ $pr3->server_status = '0200'; ++ ++ return $pr3; ++ } ++ ++ public function server_stmt_prepare_items_response() ++ { ++ $pr1 = $this->server_stmt_prepare_response_start('0100'); ++ ++ $pr2 = new my_mysqli_fake_packet(); ++ $pr2->packet_length = "300000"; ++ $pr2->packet_number = "02"; ++ $pr2->catalogue_len = '03'; ++ $pr2->catalogue = '646566'; // def ++ $pr2->db_len = '08'; ++ $pr2->db = '7068705f74657374'; // php_test ++ $pr2->table_len = '05'; ++ $pr2->table = '6974656d73'; // items ++ $pr2->orig_table_len = '05'; ++ $pr2->orig_table = '6974656d73'; // items ++ $pr2->name_len = '04'; ++ $pr2->name = '6974656d'; ++ $pr2->orig_name_len = '04'; ++ $pr2->orig_name = '6974656d'; ++ $pr2->something = '0c'; ++ $pr2->charset = 'e000'; ++ $pr2->length = 'c8000000'; ++ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING ++ $pr2->flags = '0110'; ++ $pr2->decimal = '00'; ++ $pr2->padding = '0000'; ++ ++ $pr3 = $this->server_stmt_prepare_response_end('03'); ++ ++ return [$pr1, $pr2, $pr3]; ++ } ++ ++ public function server_stmt_prepare_data_response_field($packet_number, $field_name) ++ { ++ if (strlen($field_name) != 6) { ++ throw new Exception("Invalid field length - only 6 is allowed"); ++ } ++ ++ $field = my_mysqli_data_field($field_name); ++ ++ $pr = new my_mysqli_fake_packet(); ++ $pr->packet_length = "320000"; ++ $pr->packet_number = $packet_number; ++ $pr->catalogue_len = '03'; ++ $pr->catalogue = bin2hex('def'); ++ $pr->db_len = '08'; ++ $pr->db = bin2hex('php_test'); ++ $pr->table_len = '04'; ++ $pr->table = bin2hex('data'); ++ $pr->orig_table_len = '04'; ++ $pr->orig_table = bin2hex('data'); ++ $pr->name_len = '06'; ++ $pr->name = bin2hex($field_name); ++ $pr->orig_name_len = '06'; ++ $pr->orig_name = bin2hex($field_name); ++ $pr->something = '0c'; ++ $pr->charset = $field['charset']; ++ $pr->length = $field['length']; ++ $pr->field_type = $field['type']; ++ $pr->flags = $field['flags']; ++ $pr->decimal = $field['decimal']; ++ $pr->padding = '0000'; ++ ++ return $pr; ++ } ++ ++ public function server_stmt_prepare_data_response(string $field_name) ++ { ++ $pr1 = $this->server_stmt_prepare_response_start('0200'); ++ ++ $pr2 = $this->server_stmt_prepare_data_response_field('02', 'strval'); ++ $pr3 = $this->server_stmt_prepare_data_response_field('03', $field_name); ++ ++ $pr4 = $this->server_stmt_prepare_response_end('04'); ++ ++ return [$pr1, $pr2, $pr3, $pr4]; ++ } ++ ++ public function server_stmt_execute_items_response() ++ { ++ $pr1 = new my_mysqli_fake_packet(); ++ $pr1->packet_length = "010000"; ++ $pr1->packet_number = "01"; ++ $pr1->num_fields = '01'; ++ ++ $pr2 = new my_mysqli_fake_packet(); ++ $pr2->packet_length = "300000"; ++ $pr2->packet_number = "02"; ++ $pr2->catalogue_len = '03'; ++ $pr2->catalogue = '646566'; // def ++ $pr2->db_len = '08'; ++ $pr2->db = '7068705f74657374'; // php_test ++ $pr2->table_len = '05'; ++ $pr2->table = '6974656d73'; // items ++ $pr2->orig_table_len = '05'; ++ $pr2->orig_table = '6974656d73'; // items ++ $pr2->name_len = '04'; ++ $pr2->name = '6974656d'; ++ $pr2->orig_name_len = '04'; ++ $pr2->orig_name = '6974656d'; ++ $pr2->something = '0c'; ++ $pr2->charset = 'e000'; ++ $pr2->length = 'c8000000'; ++ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING ++ $pr2->flags = '0110'; ++ $pr2->decimal = '00'; ++ $pr2->padding = '0000'; ++ ++ $pr3 = new my_mysqli_fake_packet(); ++ $pr3->packet_length = "050000"; ++ $pr3->packet_number = "03"; ++ $pr3->packet_type = 'fe'; // EOF ++ $pr3->warnings = '0000'; ++ $pr3->server_status = '2200'; ++ ++ $pr4 = new my_mysqli_fake_packet(); ++ $pr4->packet_length = "070000"; ++ $pr4->packet_number = "04"; ++ $pr4->packet_type = '00'; // OK ++ $pr4->affected_rows = '00'; ++ $pr4->row_data_len = '04'; ++ $pr4->row_data = '74657374'; // item ++ ++ $pr5 = new my_mysqli_fake_packet(); ++ $pr5->full = '05000005fe00002200'; ++ ++ return [$pr1, $pr2, $pr3, $pr4, $pr5]; ++ } ++ ++ private function server_execute_data_response_start(string $field_name) ++ { ++ $pr1 = new my_mysqli_fake_packet(); ++ $pr1->packet_length = "010000"; ++ $pr1->packet_number = "01"; ++ $pr1->num_fields = '02'; ++ ++ $pr2 = new my_mysqli_fake_packet(); ++ $pr2->packet_length = "320000"; ++ $pr2->packet_number = "02"; ++ $pr2->catalogue_len = '03'; ++ $pr2->catalogue = '646566'; // def ++ $pr2->db_len = '08'; ++ $pr2->db = '7068705f74657374'; // php_test ++ $pr2->table_len = '04'; ++ $pr2->table = bin2hex('data'); ++ $pr2->orig_table_len = '04'; ++ $pr2->orig_table = bin2hex('data'); ++ $pr2->name_len = '06'; ++ $pr2->name = bin2hex('strval'); ++ $pr2->orig_name_len = '06'; ++ $pr2->orig_name = bin2hex('strval'); ++ $pr2->something = '0c'; ++ $pr2->charset = 'e000'; ++ $pr2->length = 'c8000000'; ++ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING ++ $pr2->flags = '0110'; ++ $pr2->decimal = '00'; ++ $pr2->padding = '0000'; ++ ++ $field = my_mysqli_data_field($field_name); ++ ++ $pr3 = new my_mysqli_fake_packet(); ++ $pr3->packet_length = "320000"; ++ $pr3->packet_number = "03"; ++ $pr3->catalogue_len = '03'; ++ $pr3->catalogue = '646566'; // def ++ $pr3->db_len = '08'; ++ $pr3->db = '7068705f74657374'; // php_test ++ $pr3->table_len = '04'; ++ $pr3->table = bin2hex('data'); ++ $pr3->orig_table_len = '04'; ++ $pr3->orig_table = bin2hex('data'); ++ $pr3->name_len = '06'; ++ $pr3->name = bin2hex($field_name); ++ $pr3->orig_name_len = '06'; ++ $pr3->orig_name = bin2hex($field_name); ++ $pr3->something = '0c'; ++ $pr3->charset = $field['charset']; ++ $pr3->length = $field['length']; ++ $pr3->field_type = $field['type']; ++ $pr3->flags = $field['flags']; ++ $pr3->decimal = $field['decimal']; ++ $pr3->padding = '0000'; ++ ++ $pr4 = new my_mysqli_fake_packet(); ++ $pr4->packet_length = "050000"; ++ $pr4->packet_number = "04"; ++ $pr4->packet_type = 'fe'; // EOF ++ $pr4->warnings = '0000'; ++ $pr4->server_status = '2200'; ++ ++ return [$field, $pr1, $pr2, $pr3, $pr4]; ++ } ++ ++ private function server_execute_data_response_end() ++ { ++ $pr6 = new my_mysqli_fake_packet(); ++ $pr6->packet_length = '050000'; ++ $pr6->packet_number = "06"; ++ $pr6->packet_type = 'fe'; // EOF ++ $pr6->warnings = '0000'; ++ $pr6->server_status = '2200'; ++ ++ return $pr6; ++ } ++ ++ public function server_stmt_execute_data_response(string $field_name) ++ { ++ [$field, $pr1, $pr2, $pr3, $pr4] = $this->server_execute_data_response_start($field_name); ++ ++ $pr5 = new my_mysqli_fake_packet(); ++ $pr5->packet_length = $field['stmt_data_packet_length']; ++ $pr5->packet_number = "05"; ++ $pr5->packet_type = '00'; // OK ++ $pr5->affected_rows = '00'; ++ $pr5->row_field1_len = '04'; ++ $pr5->row_field1_data = '74657374'; // test ++ $pr5->row_field2 = $field['stmt_data_value']; ++ ++ return [$pr1, $pr2, $pr3, $pr4, $pr5, $this->server_execute_data_response_end()]; ++ } ++ ++ public function server_query_execute_data_response(string $field_name) ++ { ++ [$field, $pr1, $pr2, $pr3, $pr4] = $this->server_execute_data_response_start($field_name); ++ ++ $pr5 = new my_mysqli_fake_packet(); ++ $pr5->packet_length = $field['query_data_packet_length']; ++ $pr5->packet_number = "05"; ++ $pr5->row_field1_len = '04'; ++ $pr5->row_field1_data = '74657374'; // test ++ $pr5->row_field2 = $field['query_data_value']; ++ ++ return [$pr1, $pr2, $pr3, $pr4, $pr5, $this->server_execute_data_response_end()]; ++ } ++} ++ ++class my_mysqli_fake_server_conn ++{ ++ private $conn; ++ public $packet_generator; ++ ++ public function __construct($socket) ++ { ++ $this->packet_generator = new my_mysqli_fake_packet_generator(); ++ $this->conn = stream_socket_accept($socket); ++ if ($this->conn) { ++ fprintf(STDERR, "[*] Connection established\n"); ++ } else { ++ fprintf(STDERR, "[*] Failed to establish connection\n"); ++ } ++ } ++ ++ public function packets_to_bytes(array $packets) ++ { ++ return implode('', array_map(fn($s) => $s->to_bytes(), $packets)); ++ } ++ ++ public function send($payload, $message = null) ++ { ++ if ($message) { ++ fprintf(STDERR, "[*] Sending - %s: %s\n", $message, bin2hex($payload)); ++ } ++ fwrite($this->conn, $payload); ++ } ++ ++ public function read($bytes_len = 1024) ++ { ++ // wait 20ms to fill the buffer ++ usleep(20000); ++ $data = fread($this->conn, $bytes_len); ++ if ($data) { ++ fprintf(STDERR, "[*] Received: %s\n", bin2hex($data)); ++ } ++ } ++ ++ public function close() ++ { ++ fclose($this->conn); ++ } ++ ++ public function send_server_greetings() ++ { ++ $this->send($this->packet_generator->server_greetings()->to_bytes(), "Server Greeting"); ++ } ++ ++ public function send_server_ok() ++ { ++ $this->send($this->packet_generator->server_ok()->to_bytes(), "Server OK"); ++ } ++ ++ public function send_server_tabular_query_response() ++ { ++ $packets = $this->packet_generator->server_tabular_query_response(); ++ $this->send($this->packets_to_bytes($packets), "Tabular response"); ++ } ++ ++ public function send_server_stmt_prepare_items_response() ++ { ++ $packets = $this->packet_generator->server_stmt_prepare_items_response(); ++ $this->send($this->packets_to_bytes($packets), "Stmt prepare items"); ++ } ++ ++ ++ public function send_server_stmt_prepare_data_response(string $field_name) ++ { ++ $packets = $this->packet_generator->server_stmt_prepare_data_response($field_name); ++ $this->send($this->packets_to_bytes($packets), "Stmt prepare data $field_name"); ++ } ++ ++ public function send_server_stmt_execute_items_response() ++ { ++ $packets = $this->packet_generator->server_stmt_execute_items_response(); ++ $this->send($this->packets_to_bytes($packets), "Stmt execute items"); ++ } ++ ++ public function send_server_stmt_execute_data_response(string $field_name) ++ { ++ $packets = $this->packet_generator->server_stmt_execute_data_response($field_name); ++ $this->send($this->packets_to_bytes($packets), "Stmt execute data $field_name"); ++ } ++ ++ public function send_server_query_execute_data_response(string $field_name) ++ { ++ $packets = $this->packet_generator->server_query_execute_data_response($field_name); ++ $this->send($this->packets_to_bytes($packets), "Query execute data $field_name"); ++ } ++} ++ ++class my_mysqli_fake_server_process ++{ ++ public function __construct($process, array $pipes) ++ { ++ $this->process = $process; ++ $this->pipes = $pipes; ++ } ++ ++ public function terminate(bool $wait = false) ++ { ++ if ($wait) { ++ $this->wait(); ++ } ++ proc_terminate($this->process); ++ } ++ ++ public function wait() ++ { ++ echo fgets($this->pipes[1]); ++ } ++} ++ ++function my_mysqli_test_tabular_response_def_over_read(my_mysqli_fake_server_conn $conn) ++{ ++ $rh = $conn->packet_generator->server_tabular_query_response(); ++ ++ // Length of the packet is modified to include the next added data ++ $rh[1]->packet_length = "1e0000"; ++ ++ // We add a length field encoded on 4 bytes which evaluates to 65536. If the process crashes because ++ // the heap has been overread, lower this value. ++ $rh[1]->extra_def_size = "fd000001"; # 65536 ++ ++ // Filler ++ $rh[1]->extra_def_data = "aa"; ++ ++ $trrh = $conn->packets_to_bytes($rh); ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($trrh, "Malicious Tabular Response [Extract heap through buffer over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_upsert_response_filename_over_read(my_mysqli_fake_server_conn $conn) ++{ ++ $rh = $conn->packet_generator->server_upsert_query_response(); ++ ++ // Set extra length to overread ++ $rh[0]->len = "fa"; ++ ++ $trrh = $conn->packets_to_bytes($rh); ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($trrh, "Malicious Tabular Response [Extract heap through buffer over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_auth_response_message_over_read(my_mysqli_fake_server_conn $conn) ++{ ++ $p = $conn->packet_generator->server_ok(); ++ $p->packet_length = "090000"; ++ $p->message_len = "fcff"; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response [Extract heap through buffer over-read]"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_string(my_mysqli_fake_server_conn $conn) ++{ ++ $rh = $conn->packet_generator->server_stmt_execute_items_response(); ++ ++ // Set extra length to overread ++ $rh[3]->row_data_len = "fa"; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send_server_stmt_prepare_items_response(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Stmt Response for items [Extract heap through buffer over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_stmt_response_row_short_length( ++ my_mysqli_fake_server_conn $conn, ++ string $field_name ++): void { ++ $rh = $conn->packet_generator->server_stmt_execute_data_response($field_name); ++ ++ // The length does not cover the fixed offsets that the field type reads ++ $rh[4]->packet_length = '090000'; ++ $rh[4]->row_field2 = '01de'; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send_server_stmt_prepare_data_response($field_name); ++ $conn->read(); ++ $conn->send( ++ $conn->packets_to_bytes($rh), ++ "Malicious Stmt Response for data $field_name [length too short]" ++ ); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_stmt_response_row_short_length_date(my_mysqli_fake_server_conn $conn): void ++{ ++ my_mysqli_test_stmt_response_row_short_length($conn, 'datval'); ++} ++ ++function my_mysqli_test_stmt_response_row_short_length_time(my_mysqli_fake_server_conn $conn): void ++{ ++ my_mysqli_test_stmt_response_row_short_length($conn, 'timval'); ++} ++ ++function my_mysqli_test_stmt_response_row_short_length_datetime(my_mysqli_fake_server_conn $conn): void ++{ ++ my_mysqli_test_stmt_response_row_short_length($conn, 'dtival'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_two_fields( ++ my_mysqli_fake_server_conn $conn, ++ string $field_name, ++ string $row_field1_len = '06' ++) { ++ $rh = $conn->packet_generator->server_stmt_execute_data_response($field_name); ++ ++ // Set extra length to overread by two bytes ++ $rh[4]->row_field1_len = $row_field1_len; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send_server_stmt_prepare_data_response($field_name); ++ $conn->read(); ++ $conn->send( ++ $conn->packets_to_bytes($rh), ++ "Malicious Stmt Response for data $field_name [Extract heap through buffer over-read]" ++ ); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_int(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'intval'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_float(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'fltval'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_double(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'dblval'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_date(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'datval'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_time(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'timval', '0c'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_datetime(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'dtival'); ++} ++ ++function my_mysqli_test_stmt_response_row_no_space(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'strval', '09'); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_bit(my_mysqli_fake_server_conn $conn) ++{ ++ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'bitval'); ++} ++ ++function my_mysqli_test_stmt_response_row_read_two_fields(my_mysqli_fake_server_conn $conn) ++{ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $field_names = array_keys(my_mysqli_data_fields()); ++ foreach ($field_names as $field_name) { ++ $conn->send_server_stmt_prepare_data_response($field_name); ++ $conn->read(65536); ++ $conn->send_server_stmt_execute_data_response($field_name); ++ $conn->read(65536); ++ } ++} ++ ++function my_mysqli_test_query_response_row_length_overflow(my_mysqli_fake_server_conn $conn) ++{ ++ $rh = $conn->packet_generator->server_query_execute_data_response('strval'); ++ ++ // Set extra length to overread by two bytes ++ $rh[4]->row_field2 = 'fefefefefe'; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Query Response for data strval field [length overflow]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_query_response_row_field_len(my_mysqli_fake_server_conn $conn): void ++{ ++ $rh = $conn->packet_generator->server_query_execute_data_response('strval'); ++ ++ // 2-byte length prefix (0xfc) with the packet ending right after it, so ++ // decoding the length itself would read past the end of the packet ++ $rh[4]->row_field2 = 'fc'; ++ $rh[4]->packet_length = '060000'; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Query Response for data strval field [field length over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_query_response_row(my_mysqli_fake_server_conn $conn, string $packet_length, ++ string $row_field2, string $message): void ++{ ++ $rh = $conn->packet_generator->server_query_execute_data_response('strval'); ++ $rh[4]->packet_length = $packet_length; ++ $rh[4]->row_field2 = $row_field2; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), $message); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_query_response_row_eof_short(my_mysqli_fake_server_conn $conn): void ++{ ++ $rh = $conn->packet_generator->server_query_execute_data_response('strval'); ++ // EOF row packet that has no space for the warnings and the status ++ $rh[5]->packet_length = '030000'; ++ $rh[5]->server_status = ''; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Query Response [short EOF row packet]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_query_response_row_field_null(my_mysqli_fake_server_conn $conn): void ++{ ++ // NULL field, which is encoded as a single 0xfb byte ++ my_mysqli_test_query_response_row($conn, "060000", "fb", "Query Response for data strval field [NULL]"); ++} ++ ++function my_mysqli_test_query_response_row_field_len_2_bytes(my_mysqli_fake_server_conn $conn): void ++{ ++ // field length encoded on 2 bytes ++ my_mysqli_test_query_response_row($conn, "0c0000", "fc040074657374", ++ "Query Response for data strval field [length on 2 bytes]"); ++} ++ ++function my_mysqli_test_query_rset_header_field_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $rh = $conn->packet_generator->server_query_execute_data_response('strval'); ++ ++ $rh[0]->num_fields = "fd"; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Query Response for data strval field [length overflow]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_upsert_rset_header_affected_rows_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $ur = $conn->packet_generator->server_upsert_result_response(); ++ ++ $ur->packet_length = "020000"; ++ $ur->affected_rows = "fd"; ++ $ur->last_insert_id = ""; ++ $ur->server_status = ""; ++ $ur->warning_count = ""; ++ $ur->payload = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($ur->to_bytes(), "Malicious Upsert Response [affected rows overflow]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_upsert_rset_header_packet_len_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $ur = $conn->packet_generator->server_upsert_result_response(); ++ ++ $ur->affected_rows = "fd"; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($ur->to_bytes(), "Malicious Upsert Response [affected rows overflow]"); ++ $conn->read(65536); ++} ++ ++ ++function my_mysqli_test_query_response_row_read_two_fields(my_mysqli_fake_server_conn $conn) ++{ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $field_names = array_keys(my_mysqli_data_fields()); ++ foreach ($field_names as $field_name) { ++ $conn->send_server_query_execute_data_response($field_name); ++ $conn->read(); ++ } ++} ++ ++function my_mysqli_test_auth_affected_rows_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok(); ++ $p->packet_length = "020000"; ++ $p->affected_rows = "fe"; ++ $p->last_insert_id = ""; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_auth_last_insert_id_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok(); ++ $p->packet_length = "030000"; ++ $p->last_insert_id = "fd"; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_auth_warning_count_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok(); ++ $p->packet_length = "060000"; ++ $p->warning_count = "00"; // Shrunk 1 byte ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_cached_sha2_result(my_mysqli_fake_server_conn $conn, string $packet_length, string $payload, ++ string $message): void ++{ ++ $p = new my_mysqli_fake_packet(); ++ $p->packet_length = $packet_length; ++ $p->packet_number = "02"; ++ if ($payload !== '') { ++ $p->payload = $payload; ++ } ++ ++ $conn->send($conn->packet_generator->server_greetings_caching_sha2()->to_bytes(), "Server Greeting"); ++ $conn->read(65536); ++ // sent in one go so that the client cannot interleave its output in between ++ $conn->send($p->to_bytes() . $conn->packet_generator->server_ok("03")->to_bytes(), $message); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_cached_sha2_result_fast_auth(my_mysqli_fake_server_conn $conn): void ++{ ++ // What a real server sends for a successful fast auth: CR_OK and the status byte ++ my_mysqli_test_cached_sha2_result($conn, "020000", "0103", "Cached SHA2 Result [fast auth]"); ++} ++ ++function my_mysqli_test_cached_sha2_result_empty(my_mysqli_fake_server_conn $conn): void ++{ ++ // Empty packet, so reading the response code reads past the packet ++ my_mysqli_test_cached_sha2_result($conn, "000000", "", "Malicious Cached SHA2 Result [empty packet]"); ++} ++ ++function my_mysqli_test_cached_sha2_result_len(my_mysqli_fake_server_conn $conn): void ++{ ++ // Only the response code is left, so there is no space for the status byte ++ my_mysqli_test_cached_sha2_result($conn, "010000", "01", "Malicious Cached SHA2 Result [packet too short]"); ++} ++ ++function my_mysqli_test_sha256_pk_response_empty(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = new my_mysqli_fake_packet(); ++ // Empty packet, so reading the response code reads past the packet ++ $p->packet_length = "000000"; ++ $p->packet_number = "02"; ++ ++ $conn->send($conn->packet_generator->server_greetings_sha256()->to_bytes(), "Server Greeting"); ++ $conn->read(65536); ++ $conn->send($p->to_bytes(), "Malicious SHA256 PK Response [empty packet]"); ++ $conn->read(65536); ++ $conn->send($conn->packet_generator->server_ok("04")->to_bytes(), "Server OK"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_sha256_pk_response_len(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = new my_mysqli_fake_packet(); ++ // Only the response code is left, so there is no space for the public key ++ $p->packet_length = "010000"; ++ $p->packet_number = "02"; ++ $p->response_code = "00"; ++ ++ $conn->send($conn->packet_generator->server_greetings_sha256()->to_bytes(), "Server Greeting"); ++ $conn->read(65536); ++ $conn->send($p->to_bytes(), "Malicious SHA256 PK Response [packet too short]"); ++ $conn->read(65536); ++ $conn->send($conn->packet_generator->server_ok("04")->to_bytes(), "Server OK"); ++ $conn->read(65536); ++} ++ ++/* An auth switch packet whose plugin name is not NUL terminated. */ ++function my_mysqli_auth_switch_packet(string $packet_number): my_mysqli_fake_packet ++{ ++ $p = new my_mysqli_fake_packet(); ++ $p->packet_length = "160000"; ++ $p->packet_number = $packet_number; ++ $p->response_code = "fe"; ++ // 21 bytes of plugin name and no terminator ++ $p->auth_plugin_name = bin2hex('mysql_native_password'); ++ ++ return $p; ++} ++ ++function my_mysqli_test_auth_response_switch_unterminated(my_mysqli_fake_server_conn $conn): void ++{ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send(my_mysqli_auth_switch_packet("02")->to_bytes(), ++ "Malicious Auth Switch Response [plugin name not terminated]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_chg_user_switch_unterminated(my_mysqli_fake_server_conn $conn): void ++{ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(65536); ++ $conn->send(my_mysqli_auth_switch_packet("01")->to_bytes(), ++ "Malicious Change User Response [plugin name not terminated]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_cached_sha2_switch_unterminated(my_mysqli_fake_server_conn $conn): void ++{ ++ $conn->send($conn->packet_generator->server_greetings_caching_sha2()->to_bytes(), "Server Greeting"); ++ $conn->read(65536); ++ // sent in one go so that the client cannot interleave its output in between ++ $conn->send(my_mysqli_auth_switch_packet("02")->to_bytes() ++ . $conn->packet_generator->server_ok("03")->to_bytes(), ++ "Malicious Cached SHA2 Result [plugin name not terminated]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_chg_user_response_empty(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ // Empty packet, so reading the response code reads past the packet ++ $p->packet_length = "000000"; ++ $p->header = ""; ++ $p->affected_rows = ""; ++ $p->last_insert_id = ""; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(65536); ++ $conn->send($p->to_bytes(), "Malicious Change User Response [empty packet]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_chg_user_response_len(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ // Only the response code is left, so there is no space for the rest ++ $p->packet_length = "010000"; ++ $p->affected_rows = ""; ++ $p->last_insert_id = ""; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(65536); ++ $conn->send($p->to_bytes(), "Malicious Change User Response [packet too short]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_auth_ok(my_mysqli_fake_server_conn $conn, string $packet_length, string $affected_rows, ++ string $last_insert_id, string $server_status, string $warning_count, ++ string $message): void ++{ ++ $p = $conn->packet_generator->server_ok(); ++ $p->packet_length = $packet_length; ++ $p->affected_rows = $affected_rows; ++ $p->last_insert_id = $last_insert_id; ++ $p->server_status = $server_status; ++ $p->warning_count = $warning_count; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), $message); ++ $conn->read(); ++} ++ ++function my_mysqli_test_auth_last_insert_id_no_space(my_mysqli_fake_server_conn $conn): void ++{ ++ // affected rows takes the last byte, so there is nothing left for the last insert id ++ my_mysqli_test_auth_ok($conn, "020000", "00", "", "", "", ++ "Malicious OK Auth Response [no space for last insert id]"); ++} ++ ++function my_mysqli_test_auth_affected_rows_null_length(my_mysqli_fake_server_conn $conn): void ++{ ++ // affected rows sent as the NULL length marker ++ my_mysqli_test_auth_ok($conn, "070000", "fb", "00", "0200", "0000", ++ "OK Auth Response [affected rows as NULL length]"); ++} ++ ++function my_mysqli_test_auth_affected_rows_2_bytes(my_mysqli_fake_server_conn $conn): void ++{ ++ // affected rows encoded on 2 bytes ++ my_mysqli_test_auth_ok($conn, "090000", "fc3412", "00", "0200", "0000", ++ "OK Auth Response [affected rows on 2 bytes]"); ++} ++ ++function my_mysqli_test_auth_affected_rows_8_bytes(my_mysqli_fake_server_conn $conn): void ++{ ++ // affected rows encoded on 8 bytes ++ my_mysqli_test_auth_ok($conn, "0f0000", "fe0100000000000000", "00", "0200", "0000", ++ "OK Auth Response [affected rows on 8 bytes]"); ++} ++ ++function my_mysqli_test_greet_scramble_len_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_greetings(); ++ // the scramble length claims more data than the packet holds ++ $p->auth_plugin = "ff"; ++ ++ $conn->send($p->to_bytes(), "Malicious Server Greeting [scramble length over-read]"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_greet_over_read_string(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = new my_mysqli_fake_packet(); ++ $p->packet_length = "080000"; ++ $p->packet_number = "00"; ++ $p->proto_version = "0a"; ++ $p->version = my_mysqli_fake_packet_generator::create_packet_item('5.5'); ++ $p->thread_id = "03030303"; ++ $p->salt = "473e3f6047257c67"; ++ ++ $conn->send($p->to_bytes(), "Malicious Server Greeting"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_greet_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = new my_mysqli_fake_packet(); ++ $p->packet_length = "110000"; ++ $p->packet_number = "00"; ++ $p->proto_version = "0a"; ++ $p->version = my_mysqli_fake_packet_generator::create_packet_item('8.0' . chr(0)); ++ $p->thread_id = "03000000"; ++ $p->salt = "473e3f6047257c67"; ++ ++ $conn->send($p->to_bytes(), "Malicious Server Greeting"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_ok_affected_rows_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ $p->packet_length = "020000"; ++ $p->affected_rows = "fe"; ++ $p->last_insert_id = ""; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_ok_last_insert_id_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ $p->packet_length = "030000"; ++ $p->last_insert_id = "fd"; ++ $p->server_status = ""; ++ $p->warning_count = ""; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_ok_message_len_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ $p->packet_length = "080000"; ++ $p->message_len = "fd"; ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_ok_warning_count_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_ok("01"); ++ $p->packet_length = "060000"; ++ $p->warning_count = "00"; // Shrunk 1 byte ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious OK Auth Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_eof_warning_count_over_read(my_mysqli_fake_server_conn $conn): void ++{ ++ $p = $conn->packet_generator->server_eof(); ++ $p->packet_length = "040000"; ++ $p->warning_count = "00"; // Shrunk 1 byte ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $conn->send($p->to_bytes(), "Malicious EOF Response"); ++ $conn->read(); ++} ++ ++function my_mysqli_test_stmt_response_row_over_read_status(my_mysqli_fake_server_conn $conn): void ++{ ++ $rh = $conn->packet_generator->server_stmt_execute_items_response(); ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $packets = $conn->packet_generator->server_stmt_prepare_items_response(); ++ $packets[2]->server_status = '02'; ++ $packets[2]->packet_length = '040000'; ++ $conn->send($conn->packets_to_bytes($packets), "Stmt prepare items"); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Stmt Response for items [Extract heap through buffer over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_stmt_response_field_len_faulty(my_mysqli_fake_server_conn $conn): void ++{ ++ $rh = $conn->packet_generator->server_stmt_execute_items_response(); ++ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $packets = $conn->packet_generator->server_stmt_prepare_items_response(); ++ // org_name length exceeds the whole remaining packet ++ $packets[1]->orig_name_len = 'fe'; ++ $packets[2]->packet_length = '1f0000'; ++ $conn->send($conn->packets_to_bytes($packets), "Stmt prepare items"); ++ $conn->read(); ++ $conn->send($conn->packets_to_bytes($rh), "Malicious Stmt Response for fields [Extract heap through buffer over-read]"); ++ $conn->read(65536); ++} ++ ++function my_mysqli_test_stmt_response_field_len_premature(my_mysqli_fake_server_conn $conn): void ++{ ++ $conn->send_server_greetings(); ++ $conn->read(); ++ $conn->send_server_ok(); ++ $conn->read(); ++ $packets = $conn->packet_generator->server_stmt_prepare_items_response(); ++ // org_name length over-reads into the trailing fixed-length metadata block ++ $packets[1]->orig_name_len = '0c'; ++ $conn->send($conn->packets_to_bytes($packets), "Malicious Stmt Prepare items [Field length over-read]"); ++ $conn->read(65536); ++} ++ ++function run_fake_server(string $test_function, $port = 33305) ++{ ++ $address = '127.0.0.1'; ++ ++ $socket = @stream_socket_server("tcp://$address:$port", $errno, $errstr); ++ if (!$socket) { ++ die("Failed to create socket: $errstr ($errno)\n"); ++ } ++ echo "[*] Server started\n"; ++ ++ try { ++ $conn = new my_mysqli_fake_server_conn($socket); ++ $test_function_name = 'my_mysqli_test_' . $test_function; ++ call_user_func($test_function_name, $conn); ++ $conn->close(); ++ } catch (Exception $e) { ++ fprintf(STDERR, "[!] Exception: " . $e->getMessage() . "\n"); ++ } ++ ++ fclose($socket); ++ ++ echo "[*] Server finished\n"; ++} ++ ++ ++function run_fake_server_in_background($test_function, $port = 33305) ++{ ++ if ($port == 0) { ++ $port = (int) getenv('MYSQLI_TEST_FAKE_SERVER_PORT'); ++ } ++ ++ $command = [PHP_BINARY, '-n', __FILE__, 'mysqli_fake_server', $test_function, $port]; ++ ++ $descriptorspec = array( ++ 0 => array("pipe", "r"), ++ 1 => array("pipe", "w"), ++ 2 => STDERR, ++ ); ++ ++ $process = proc_open($command, $descriptorspec, $pipes); ++ ++ if (is_resource($process)) { ++ return new my_mysqli_fake_server_process($process, $pipes); ++ } else { ++ throw new Exception("Failed to start server process"); ++ } ++} ++ ++if (isset($argv) && $argc > 2 && $argv[1] == 'mysqli_fake_server') { ++ run_fake_server($argv[2], $argv[3] ?? '33305'); ++} +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt +new file mode 100644 +index 0000000..161c9a5 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt +@@ -0,0 +1,37 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - auth message buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", $port ); ++ $info = mysqli_info($conn); ++ var_dump($info); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious OK Auth Response [Extract heap through buffer over-read]: 0900000200000002000000fcff ++ ++Warning: mysqli::__construct(): OK packet message length is past the packet size in %s on line %d ++%A +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt +new file mode 100644 +index 0000000..77f2232 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - tabular default) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Running query on the fake server...\n"; ++ ++$result = $conn->query("SELECT * from users"); ++ ++if ($result) { ++ $all_fields = $result->fetch_fields(); ++ var_dump($result->fetch_all(MYSQLI_ASSOC)); ++ var_dump(get_object_vars($all_fields[0])["def"]); ++} ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Running query on the fake server... ++[*] Received: 140000000353454c454354202a2066726f6d207573657273 ++[*] Sending - Malicious Tabular Response [Extract heap through buffer over-read]: 01000001011e0000020164016401640164016401640c3f000b000000030350000000fd000001aa05000003fe00002200040000040135017405000005fe00002200 ++ ++Warning: mysqli::query(): Protocol error. Server sent default for unsupported field list (mysqlnd_wireprotocol.c:%d) in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt +new file mode 100644 +index 0000000..0b4db8c +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - upsert filename buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++echo "[*] Running query on the fake server...\n"; ++ ++$result = $conn->query("SELECT * from users"); ++$info = mysqli_info($conn); ++ ++var_dump($info); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Running query on the fake server... ++[*] Received: 140000000353454c454354202a2066726f6d207573657273 ++[*] Sending - Malicious Tabular Response [Extract heap through buffer over-read]: 0900000100000000000000fa65 ++ ++Warning: mysqli::query(): RSET_HEADER packet additional data length is past 249 bytes the packet size in %s on line %d ++ ++Warning: mysqli::query(): Error reading result set's header in %s on line %d ++NULL ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt +new file mode 100644 +index 0000000..f141a79 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row no space for the field) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Query the fake server...\n"; ++$sql = "SELECT strval, strval FROM data"; ++ ++$result = $conn->query($sql); ++ ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row['strval']); ++ } ++} ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Malicious Query Response for data strval field [length overflow]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374fefefefefe05000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after end of packet in %s on line %d ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt +new file mode 100644 +index 0000000..e435182 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row bit buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT bitval, timval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["bitval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542062697476616c2c2074696d76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data bitval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data bitval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00002200100000050000067465737408080808080808080805000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt +new file mode 100644 +index 0000000..76158e9 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row date buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, datval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["datval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2064617476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data datval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data datval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022000c0000050000067465737404de070c0f05000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt +new file mode 100644 +index 0000000..f53d5b8 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row datetime buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, dtival FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["dtival"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2064746976616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data dtival: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data dtival [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe000022000f0000050000067465737407de070c100d000105000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt +new file mode 100644 +index 0000000..03c9b04 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row double buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, dblval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["dblval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2064626c76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data dblval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data dblval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe000022000f00000500000674657374333333333333f33f05000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt +new file mode 100644 +index 0000000..b1ec9aa +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row int buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, fltval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["fltval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c20666c7476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data fltval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data fltval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe000022000b000005000006746573743333134005000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt +new file mode 100644 +index 0000000..426d9ea +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row int buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, intval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["intval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c20696e7476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data intval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data intval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe000022000b000005000006746573740e00000005000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt +new file mode 100644 +index 0000000..6db6952 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row no space for the field) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, strval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["strval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data strval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data strval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000c00000500000974657374047465737405000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. No packet space left for the field in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt +new file mode 100644 +index 0000000..55bad4c +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row string buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT item FROM items"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["item"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 170000001653454c454354206974656d2046524f4d206974656d73 ++[*] Sending - Stmt prepare items: 0c0000010001000000010000000000003000000203646566087068705f74657374056974656d73056974656d73046974656d046974656d0ce000c8000000fd011000000005000003fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for items [Extract heap through buffer over-read]: 01000001013000000203646566087068705f74657374056974656d73056974656d73046974656d046974656d0ce000c8000000fd011000000005000003fe00002200070000040000fa7465737405000005fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt +new file mode 100644 +index 0000000..06918c3 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt +@@ -0,0 +1,53 @@ ++--TEST-- ++GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row time buffer over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, timval FROM data"); ++ ++$stmt->execute(); ++$result = $stmt->get_result(); ++ ++// Fetch and display the results ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row["timval"]); ++ } ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2074696d76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data timval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data timval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe000022001000000500000c7465737408000000000015080105000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %d ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-2-bytes.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-2-bytes.phpt +new file mode 100644 +index 0000000..2d935f1 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-2-bytes.phpt +@@ -0,0 +1,32 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet with affected rows on 2 bytes) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - OK Auth Response [affected rows on 2 bytes]: 0900000200fc34120002000000 ++[*] connect_errno: 0 ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-8-bytes.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-8-bytes.phpt +new file mode 100644 +index 0000000..cbfdeca +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-8-bytes.phpt +@@ -0,0 +1,32 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet with affected rows on 8 bytes) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - OK Auth Response [affected rows on 8 bytes]: 0f00000200fe01000000000000000002000000 ++[*] connect_errno: 0 ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-null-length.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-null-length.phpt +new file mode 100644 +index 0000000..965df62 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows-null-length.phpt +@@ -0,0 +1,32 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet with affected rows as NULL length) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - OK Auth Response [affected rows as NULL length]: 0700000200fb0002000000 ++[*] connect_errno: 0 ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows.phpt +new file mode 100644 +index 0000000..0f9a237 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet over-read in affected rows) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious OK Auth Response: 0200000200fe ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): AUTH_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id-no-space.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id-no-space.phpt +new file mode 100644 +index 0000000..1d01894 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id-no-space.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet with no space for last inserted id) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious OK Auth Response [no space for last insert id]: 020000020000 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): AUTH_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id.phpt +new file mode 100644 +index 0000000..7232ec6 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet over-read in last inserted id) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious OK Auth Response: 030000020000fd ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): AUTH_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-warning-count.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-warning-count.phpt +new file mode 100644 +index 0000000..a122511 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-warning-count.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth packet over-read in warning count) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious OK Auth Response: 06000002000000020000 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): AUTH_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-switch-unterminated.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-switch-unterminated.phpt +new file mode 100644 +index 0000000..2bc1e8f +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-switch-unterminated.phpt +@@ -0,0 +1,38 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - auth switch response with an unterminated plugin name) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 7d00000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400140c7b6398a9794c7dc95737fa731fe62e95fe56626d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Auth Switch Response [plugin name not terminated]: 16000002fe6d7973716c5f6e61746976655f70617373776f7264 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): AUTH_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): (HY000/2000): mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-empty.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-empty.phpt +new file mode 100644 +index 0000000..f477849 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-empty.phpt +@@ -0,0 +1,45 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - cached sha2 result with empty packet) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++echo "[*] Connecting to the fake server...\n"; ++$conn = new mysqli($servername, $username, $password, "", 33305); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connecting to the fake server... ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c64310063616368696e675f736861325f70617373776f7264 ++[*] Received: 8900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400204829cef922c9e8d5c6b4a4299cb857d65b18323a1b833559f3aa6a0b462994be63616368696e675f736861325f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Cached SHA2 Result [empty packet]: 000000020700000300000002000000 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): SHA256_PK_REQUEST_RESPONSE packet shorter than expected in %s on line %d ++[*] connect_errno: 0 ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-fast-auth.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-fast-auth.phpt +new file mode 100644 +index 0000000..e9403b1 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-fast-auth.phpt +@@ -0,0 +1,41 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - cached sha2 result for a successful fast auth) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++echo "[*] Connecting to the fake server...\n"; ++$conn = new mysqli($servername, $username, $password, "", 33305); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connecting to the fake server... ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c64310063616368696e675f736861325f70617373776f7264 ++[*] Received: 8900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400204829cef922c9e8d5c6b4a4299cb857d65b18323a1b833559f3aa6a0b462994be63616368696e675f736861325f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Cached SHA2 Result [fast auth]: 0200000201030700000300000002000000 ++[*] connect_errno: 0 ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-len.phpt +new file mode 100644 +index 0000000..7d888e6 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-len.phpt +@@ -0,0 +1,45 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - cached sha2 result shorter than expected) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++echo "[*] Connecting to the fake server...\n"; ++$conn = new mysqli($servername, $username, $password, "", 33305); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connecting to the fake server... ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c64310063616368696e675f736861325f70617373776f7264 ++[*] Received: 8900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400204829cef922c9e8d5c6b4a4299cb857d65b18323a1b833559f3aa6a0b462994be63616368696e675f736861325f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Cached SHA2 Result [packet too short]: 01000002010700000300000002000000 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): SHA256_PK_REQUEST_RESPONSE packet shorter than expected in %s on line %d ++[*] connect_errno: 0 ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-switch-unterminated.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-switch-unterminated.phpt +new file mode 100644 +index 0000000..79be8a1 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-cached-sha2-switch-unterminated.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - cached sha2 result with an unterminated plugin name) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++echo "[*] connect_errno: ", $conn->connect_errno, "\n"; ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c64310063616368696e675f736861325f70617373776f7264 ++[*] Received: 8900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400204829cef922c9e8d5c6b4a4299cb857d65b18323a1b833559f3aa6a0b462994be63616368696e675f736861325f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Cached SHA2 Result [plugin name not terminated]: 16000002fe6d7973716c5f6e61746976655f70617373776f72640700000300000002000000 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): SHA256_PK_REQUEST_RESPONSE packet shorter than expected in %s on line %d ++[*] connect_errno: 0 ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-empty.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-empty.phpt +new file mode 100644 +index 0000000..8df0497 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-empty.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - change user response with empty packet) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Changing user on the fake server...\n"; ++var_dump($conn->change_user("root2", "", "")); ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Changing user on the fake server... ++[*] Received: 4e00000011726f6f743200000008006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Change User Response [empty packet]: 00000001 ++ ++Warning: mysqli::change_user(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::change_user(): CHANGE_USER packet shorter than expected in %s on line %d ++bool(false) ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-len.phpt +new file mode 100644 +index 0000000..ab5a4de +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-len.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - change user response shorter than expected) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Changing user on the fake server...\n"; ++var_dump($conn->change_user("root2", "", "")); ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Changing user on the fake server... ++[*] Received: 4e00000011726f6f743200000008006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Change User Response [packet too short]: 0100000100 ++ ++Warning: mysqli::change_user(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::change_user(): CHANGE_USER packet shorter than expected in %s on line %d ++bool(false) ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-switch-unterminated.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-switch-unterminated.phpt +new file mode 100644 +index 0000000..454bac6 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-chg-user-switch-unterminated.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - change user response with an unterminated plugin name) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, "", "", 33305 ); ++ ++echo "[*] Changing user on the fake server...\n"; ++try { ++ var_dump($conn->change_user("root2", "", "")); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Changing user on the fake server... ++[*] Received: 4e00000011726f6f743200000008006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Malicious Change User Response [plugin name not terminated]: 16000001fe6d7973716c5f6e61746976655f70617373776f7264 ++ ++Warning: mysqli::change_user(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::change_user(): CHANGE_USER packet shorter than expected in %s on line %d ++bool(false) ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-eof-warning-count.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-eof-warning-count.phpt +new file mode 100644 +index 0000000..4932646 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-eof-warning-count.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - eof packet over-read in warning count) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli($servername, $username, $password, "", 33305); ++ $query = "SELECT 1; SELECT 2;"; ++ $conn->multi_query($query); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 030000001b0000 ++[*] Sending - Malicious EOF Response: 04000001fe000200 ++ ++Warning: mysqli::multi_query(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::multi_query(): EOF packet shorter than expected in %s on line %d ++ ++Warning: mysqli::multi_query(): Error while reading SET_OPTION's response packet. PID=%d in %s on line %d ++[*] Received: 140000000353454c45435420313b2053454c45435420323b ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet-string.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet-string.phpt +new file mode 100644 +index 0000000..db21535 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet-string.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - greet packet over-read string) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Malicious Server Greeting: 080000000a352e3503030303473e3f6047257c67 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): GREET packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): Error while reading greeting packet. PID=%d in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet.phpt +new file mode 100644 +index 0000000..2a7f9a8 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - greet packet over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Malicious Server Greeting: 110000000a382e300003000000473e3f6047257c67 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): GREET packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): Error while reading greeting packet. PID=%d in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-scramble-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-scramble-len.phpt +new file mode 100644 +index 0000000..21f10e9 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-scramble-len.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - greet packet scramble length over-read) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli( $servername, $username, $password, "", 33305 ); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Malicious Server Greeting [scramble length over-read]: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81ff0000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): GREET packet shorter than expected in %s on line %d ++ ++Warning: mysqli::__construct(): Error while reading greeting packet. PID=%d in %s on line %d ++ ++Warning: mysqli::__construct(): [2002] (trying to connect via (null)) in %s ++ ++Warning: mysqli::__construct(): (HY000/2002): in %s ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-affected-rows.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-affected-rows.phpt +new file mode 100644 +index 0000000..960f998 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-affected-rows.phpt +@@ -0,0 +1,42 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - ok packet over-read in affected rows) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli($servername, $username, $password, "", 33305); ++ var_dump($conn->select_db("php_test")); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 09000000027068705f74657374 ++[*] Sending - Malicious OK Auth Response: 0200000100fe ++ ++Warning: mysqli::select_db(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::select_db(): OK packet shorter than expected in %s on line %d ++ ++Warning: mysqli::select_db(): Error while reading INIT_DB's response packet. PID=%d in %s on line %d ++bool(false) ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-last-insert-id.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-last-insert-id.phpt +new file mode 100644 +index 0000000..1bd2445 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-last-insert-id.phpt +@@ -0,0 +1,42 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - ok packet over-read in last inserted id) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli($servername, $username, $password, "", 33305); ++ var_dump($conn->select_db("php_test")); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 09000000027068705f74657374 ++[*] Sending - Malicious OK Auth Response: 030000010000fd ++ ++Warning: mysqli::select_db(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::select_db(): OK packet shorter than expected in %s on line %d ++ ++Warning: mysqli::select_db(): Error while reading INIT_DB's response packet. PID=%d in %s on line %d ++bool(false) ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-message-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-message-len.phpt +new file mode 100644 +index 0000000..d25ee8d +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-message-len.phpt +@@ -0,0 +1,42 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - ok packet over-read in message length) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli($servername, $username, $password, "", 33305); ++ var_dump($conn->select_db("php_test")); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 09000000027068705f74657374 ++[*] Sending - Malicious OK Auth Response: 0800000100000002000000fd ++ ++Warning: mysqli::select_db(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::select_db(): OK packet shorter than expected in %s on line %d ++ ++Warning: mysqli::select_db(): Error while reading INIT_DB's response packet. PID=%d in %s on line %d ++bool(false) ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-warning-count.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-warning-count.phpt +new file mode 100644 +index 0000000..0d3bf7d +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-ok-packet-warning-count.phpt +@@ -0,0 +1,42 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - ok packet over-read in warning count) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++try { ++ $conn = new mysqli($servername, $username, $password, "", 33305); ++ var_dump($conn->select_db("php_test")); ++} catch (Exception $e) { ++ echo $e->getMessage() . PHP_EOL; ++} ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 09000000027068705f74657374 ++[*] Sending - Malicious OK Auth Response: 06000001000000020000 ++ ++Warning: mysqli::select_db(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::select_db(): OK packet shorter than expected in %s on line %d ++ ++Warning: mysqli::select_db(): Error while reading INIT_DB's response packet. PID=%d in %s on line %d ++bool(false) ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-eof-short.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-eof-short.phpt +new file mode 100644 +index 0000000..6d2b4bc +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-eof-short.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - row packet with an EOF shorter than the status it announces) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Query the fake server...\n"; ++$result = $conn->query("SELECT strval, strval FROM data"); ++ ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_row()) { ++ var_dump($row); ++ } ++} ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Malicious Query Response [short EOF row packet]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374047465737403000006fe0000 ++array(2) { ++ [0]=> ++ string(4) "test" ++ [1]=> ++ string(4) "test" ++} ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len-2-bytes.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len-2-bytes.phpt +new file mode 100644 +index 0000000..491ef15 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len-2-bytes.phpt +@@ -0,0 +1,49 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - text protocol row field length on 2 bytes) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Query the fake server...\n"; ++$result = $conn->query("SELECT strval, strval FROM data"); ++ ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_row()) { ++ var_dump($row); ++ } ++} ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Query Response for data strval field [length on 2 bytes]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000c0000050474657374fc04007465737405000006fe00002200 ++array(2) { ++ [0]=> ++ string(4) "test" ++ [1]=> ++ string(4) "test" ++} ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len.phpt +new file mode 100644 +index 0000000..59d54e0 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-len.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - text protocol row field length prefix) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Query the fake server...\n"; ++$sql = "SELECT strval, strval FROM data"; ++ ++$result = $conn->query($sql); ++ ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row['strval']); ++ } ++} ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Malicious Query Response for data strval field [field length over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00002200060000050474657374fc05000006fe00002200 ++ ++Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after end of packet in %s on line %d ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-null.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-null.phpt +new file mode 100644 +index 0000000..94ffeed +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-query-row-field-null.phpt +@@ -0,0 +1,49 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - text protocol row with a NULL field) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Query the fake server...\n"; ++$result = $conn->query("SELECT strval, strval FROM data"); ++ ++if ($result->num_rows > 0) { ++ while ($row = $result->fetch_row()) { ++ var_dump($row); ++ } ++} ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Query Response for data strval field [NULL]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00002200060000050474657374fb05000006fe00002200 ++array(2) { ++ [0]=> ++ string(4) "test" ++ [1]=> ++ NULL ++} ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-field-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-field-len.phpt +new file mode 100644 +index 0000000..29c5b90 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-field-len.phpt +@@ -0,0 +1,50 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - rset header read field length) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Query the fake server...\n"; ++$sql = "SELECT strval, strval FROM data"; ++ ++$result = $conn->query($sql); ++ ++if ($result && $result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row['strval']); ++ } ++} ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Query the fake server... ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Malicious Query Response for data strval field [length overflow]: 01000001fd3200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374047465737405000006fe00002200 ++ ++Warning: mysqli::query(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::query(): RSET_HEADER packet shorter than expected in %s on line %d ++ ++Warning: mysqli::query(): Error reading result set's header in %s on line %d ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-affected-rows.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-affected-rows.phpt +new file mode 100644 +index 0000000..6aa4892 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-affected-rows.phpt +@@ -0,0 +1,50 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - rset header upsert affected_rows) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++// Construct the SQL query directly ++$sql = "UPDATE data SET strval = 'test' WHERE id = 1"; ++ ++// Execute the query ++$result = $conn->query($sql); ++if ($result) { ++ echo "Affected rows: " . $conn->affected_rows . "\n"; ++ echo "Info: " . $conn->info . "\n"; ++} ++ ++// Close the connection ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 2d000000035550444154452064617461205345542073747276616c203d20277465737427205748455245206964203d2031 ++[*] Sending - Malicious Upsert Response [affected rows overflow]: 0200000100fd ++ ++Warning: mysqli::query(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::query(): RSET_HEADER packet shorter than expected in %s on line %d ++ ++Warning: mysqli::query(): Error reading result set's header in %s on line %d ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-len.phpt +new file mode 100644 +index 0000000..6e6e086 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-rset-header-upsert-len.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - rset header upsert packet length) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++// Construct the SQL query directly ++$sql = "UPDATE data SET strval = 'test' WHERE id = 1"; ++ ++// Execute the query ++$result = $conn->query($sql); ++if ($result) { ++ echo "Affected rows: " . $conn->affected_rows . "\n"; ++ echo "Info: " . $conn->info . "\n"; ++} ++ ++// Close the connection ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 2d000000035550444154452064617461205345542073747276616c203d20277465737427205748455245206964203d2031 ++[*] Sending - Malicious Upsert Response [affected rows overflow]: 3000000100fd000002000028526f7773206d6174636865643a203120204368616e6765643a203020205761726e696e67733a2030 ++ ++Warning: mysqli::query(): RSET_HEADER packet additional data length is past 82 bytes the packet size in %s on line %d ++ ++Warning: mysqli::query(): Error reading result set's header in %s on line %d ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-empty.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-empty.phpt +new file mode 100644 +index 0000000..984dd43 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-empty.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - sha256 public key response with empty packet) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++echo "[*] Connecting to the fake server...\n"; ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connecting to the fake server... ++[*] Connection established ++[*] Sending - Server Greeting: 520000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431007368613235365f70617373776f7264 ++[*] Received: 0100000101 ++[*] Sending - Malicious SHA256 PK Response [empty packet]: 00000002 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): SHA256_PK_REQUEST_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: Error while receiving public key. PID=%d in %s on line %d ++[*] Received: 6300000385a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400007368613235365f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000400000002000000 ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-len.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-len.phpt +new file mode 100644 +index 0000000..b6f64c1 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-sha256-pk-len.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - sha256 public key response shorter than expected) ++--EXTENSIONS-- ++mysqli ++--SKIPIF-- ++ ++--FILE-- ++wait(); ++ ++echo "[*] Connecting to the fake server...\n"; ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connecting to the fake server... ++[*] Connection established ++[*] Sending - Server Greeting: 520000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431007368613235365f70617373776f7264 ++[*] Received: 0100000101 ++[*] Sending - Malicious SHA256 PK Response [packet too short]: 0100000200 ++ ++Warning: mysqli::__construct(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::__construct(): SHA256_PK_REQUEST_RESPONSE packet shorter than expected in %s on line %d ++ ++Warning: Error while receiving public key. PID=%d in %s on line %d ++[*] Received: 6300000385a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400007368613235365f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000400000002000000 ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-faulty.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-faulty.phpt +new file mode 100644 +index 0000000..ae3191d +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-faulty.phpt +@@ -0,0 +1,38 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt field length exceeding the packet) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$conn->prepare("SELECT item FROM items"); ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 170000001653454c454354206974656d2046524f4d206974656d73 ++[*] Sending - Stmt prepare items: 0c0000010001000000010000000000003000000203646566087068705f74657374056974656d73056974656d73046974656dfe6974656d0ce000c8000000fd01100000001f000003fe00000200 ++ ++Warning: mysqli::prepare(): Protocol error. Server sent NULL_LENGTH. The server is faulty in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-premature.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-premature.phpt +new file mode 100644 +index 0000000..6cd5ade +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-field-len-premature.phpt +@@ -0,0 +1,42 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt field length over-reading into fixed block) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$conn->prepare("SELECT item FROM items"); ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 170000001653454c454354206974656d2046524f4d206974656d73 ++[*] Sending - Malicious Stmt Prepare items [Field length over-read]: 0c0000010001000000010000000000003000000203646566087068705f74657374056974656d73056974656d73046974656d0c6974656d0ce000c8000000fd011000000005000003fe00000200 ++ ++Warning: mysqli::prepare(): Protocol error. Server sent false length. Expected 12 in %s on line %d ++ ++Warning: mysqli::prepare(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::prepare(): Result set field packet shorter than expected in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-row-status.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-row-status.phpt +new file mode 100644 +index 0000000..57ebf2d +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-response-row-status.phpt +@@ -0,0 +1,40 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt response) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli( $servername, $username, $password, "", 33305 ); ++ ++echo "[*] Preparing statement on the fake server...\n"; ++$conn->prepare("SELECT item FROM items"); ++ ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Preparing statement on the fake server... ++[*] Received: 170000001653454c454354206974656d2046524f4d206974656d73 ++[*] Sending - Stmt prepare items: 0c0000010001000000010000000000003000000203646566087068705f74657374056974656d73056974656d73046974656d046974656d0ce000c8000000fd011000000004000003fe000002 ++ ++Warning: mysqli::prepare(): Premature end of data (mysqlnd_wireprotocol.c:%d) in %s on line %d ++ ++Warning: mysqli::prepare(): EOF packet shorter than expected in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-date.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-date.phpt +new file mode 100644 +index 0000000..fd1d80c +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-date.phpt +@@ -0,0 +1,45 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt row date field length too short for the type) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Prepare and execute on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, datval FROM data"); ++$stmt->execute(); ++$result = $stmt->get_result(); ++while ($row = $result->fetch_row()) { ++ var_dump($row); ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Prepare and execute on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2064617476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data datval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data datval [length too short]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00002200090000050000047465737401de05000006fe00002200 ++ ++Warning: mysqli_result::fetch_row(): Malformed server packet. Field length is too short for the field type in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-datetime.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-datetime.phpt +new file mode 100644 +index 0000000..0e403b2 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-datetime.phpt +@@ -0,0 +1,45 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt row datetime field length too short for the type) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Prepare and execute on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, dtival FROM data"); ++$stmt->execute(); ++$result = $stmt->get_result(); ++while ($row = $result->fetch_row()) { ++ var_dump($row); ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Prepare and execute on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2064746976616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data dtival: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data dtival [length too short]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00002200090000050000047465737401de05000006fe00002200 ++ ++Warning: mysqli_result::fetch_row(): Malformed server packet. Field length is too short for the field type in %s on line %d ++done! +diff --git a/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-time.phpt b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-time.phpt +new file mode 100644 +index 0000000..3c76892 +--- /dev/null ++++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-stmt-row-short-length-time.phpt +@@ -0,0 +1,45 @@ ++--TEST-- ++GHSA-r6x9-5r99-36j7 (Various packet overreads in mysqlnd_writeprotocol.c - stmt row time field length too short for the type) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", 33305); ++ ++echo "[*] Prepare and execute on the fake server...\n"; ++$stmt = $conn->prepare("SELECT strval, timval FROM data"); ++$stmt->execute(); ++$result = $stmt->get_result(); ++while ($row = $result->fetch_row()) { ++ var_dump($row); ++} ++$stmt->close(); ++$conn->close(); ++ ++$process->terminate(); ++ ++print "done!"; ++?> ++--EXPECTF-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Prepare and execute on the fake server... ++[*] Received: 200000001653454c4543542073747276616c2c2074696d76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data timval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Malicious Stmt Response for data timval [length too short]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00002200090000050000047465737401de05000006fe00002200 ++ ++Warning: mysqli_result::fetch_row(): Malformed server packet. Field length is too short for the field type in %s on line %d ++done! +diff --git a/ext/mysqli/tests/mysqli_change_user_new.phpt b/ext/mysqli/tests/mysqli_change_user_new.phpt +index 2b8993f..d8fed6d 100644 +--- a/ext/mysqli/tests/mysqli_change_user_new.phpt ++++ b/ext/mysqli/tests/mysqli_change_user_new.phpt +@@ -12,6 +12,9 @@ if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket)) + + if (mysqli_get_server_version($link) < 50600) + die("SKIP For MySQL >= 5.6.0"); ++ ++if (mysqli_get_server_version($link) >= 10_00_00) ++ die("SKIP Not applicable for MariaDB"); + ?> + --FILE-- + wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++function my_query($conn, $field) ++{ ++ $sql = "SELECT strval, $field FROM data"; ++ ++ $result = $conn->query($sql); ++ ++ if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row[$field]); ++ } ++ } ++} ++ ++foreach (my_mysqli_data_fields() as $field_name => $field) { ++ my_query($conn, $field_name); ++} ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECT-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 200000000353454c4543542073747276616c2c20696e7476616c2046524f4d2064617461 ++[*] Sending - Query execute data intval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe0000220008000005047465737402313405000006fe00002200 ++string(2) "14" ++[*] Received: 200000000353454c4543542073747276616c2c20666c7476616c2046524f4d2064617461 ++[*] Sending - Query execute data fltval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe0000220009000005047465737403322e3305000006fe00002200 ++string(3) "2.3" ++[*] Received: 200000000353454c4543542073747276616c2c2064626c76616c2046524f4d2064617461 ++[*] Sending - Query execute data dblval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe0000220009000005047465737403312e3205000006fe00002200 ++string(3) "1.2" ++[*] Received: 200000000353454c4543542073747276616c2c2064617476616c2046524f4d2064617461 ++[*] Sending - Query execute data datval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022001000000504746573740a323031342d31322d313505000006fe00002200 ++string(10) "2014-12-15" ++[*] Received: 200000000353454c4543542073747276616c2c2074696d76616c2046524f4d2064617461 ++[*] Sending - Query execute data timval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe000022000e00000504746573740831333a30303a303205000006fe00002200 ++string(8) "13:00:02" ++[*] Received: 200000000353454c4543542073747276616c2c2064746976616c2046524f4d2064617461 ++[*] Sending - Query execute data dtival: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe0000220019000005047465737413323031342d31322d31362031333a30303a303105000006fe00002200 ++string(19) "2014-12-16 13:00:01" ++[*] Received: 200000000353454c4543542073747276616c2c2062697476616c2046524f4d2064617461 ++[*] Sending - Query execute data bitval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe000022000e000005047465737408080808080808080805000006fe00002200 ++string(18) "578721382704613384" ++[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Query execute data strval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374047465737405000006fe00002200 ++string(4) "test" ++[*] Received: 0100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt b/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt +new file mode 100644 +index 0000000..d461ec2 +--- /dev/null ++++ b/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt +@@ -0,0 +1,91 @@ ++--TEST-- ++MySQL protocol - statement row data fetch) ++--EXTENSIONS-- ++mysqli ++--FILE-- ++wait(); ++ ++$conn = new mysqli($servername, $username, $password, "", $port); ++ ++function my_query($conn, $field) ++{ ++ $stmt = $conn->prepare("SELECT strval, $field FROM data"); ++ ++ $stmt->execute(); ++ $result = $stmt->get_result(); ++ ++ if ($result->num_rows > 0) { ++ while ($row = $result->fetch_assoc()) { ++ var_dump($row[$field]); ++ } ++ } ++} ++ ++foreach (my_mysqli_data_fields() as $field_name => $field) { ++ my_query($conn, $field_name); ++} ++ ++$conn->close(); ++ ++$process->terminate(true); ++ ++print "done!"; ++?> ++--EXPECT-- ++[*] Server started ++[*] Connection established ++[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264 ++[*] Received: 6900000185a21a00000000c0080000000000000000000000000000000000000000000000726f6f7400006d7973716c5f6e61746976655f70617373776f7264002c0c5f636c69656e745f6e616d65076d7973716c6e640c5f7365727665725f686f7374093132372e302e302e31 ++[*] Sending - Server OK: 0700000200000002000000 ++[*] Received: 200000001653454c4543542073747276616c2c20696e7476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data intval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data intval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe000022000b000005000004746573740e00000005000006fe00002200 ++int(14) ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c20666c7476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data fltval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data fltval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe000022000b000005000004746573743333134005000006fe00002200 ++float(2.3) ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064626c76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data dblval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data dblval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe000022000f00000500000474657374333333333333f33f05000006fe00002200 ++float(1.2) ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064617476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data datval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data datval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022000c0000050000047465737404de070c0f05000006fe00002200 ++string(10) "2014-12-15" ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2074696d76616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data timval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data timval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00002200100000050000047465737408000000000015080105000006fe00002200 ++string(8) "21:08:01" ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064746976616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data dtival: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data dtival: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe000022000f0000050000047465737407de070c100d000105000006fe00002200 ++string(19) "2014-12-16 13:00:01" ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2062697476616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data bitval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data bitval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00002200100000050000047465737408080808080808080805000006fe00002200 ++int(578721382704613384) ++[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2073747276616c2046524f4d2064617461 ++[*] Sending - Stmt prepare data strval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00000200 ++[*] Received: 0a00000017010000000001000000 ++[*] Sending - Stmt execute data strval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000c00000500000474657374047465737405000006fe00002200 ++string(4) "test" ++[*] Received: 0500000019010000000100000001 ++[*] Server finished ++done! +diff --git a/ext/mysqlnd/mysqlnd_ps.c b/ext/mysqlnd/mysqlnd_ps.c +index ce0ad01..0813ba8 100644 +--- a/ext/mysqlnd/mysqlnd_ps.c ++++ b/ext/mysqlnd/mysqlnd_ps.c +@@ -373,6 +373,9 @@ mysqlnd_stmt_prepare_read_eof(MYSQLND_STMT * s) + if (FAIL == (ret = PACKET_READ(conn, &fields_eof))) { + if (stmt->result) { + stmt->result->m.free_result_contents(stmt->result); ++ /* The memset() below resets the statement, so release what it still owns first. */ ++ conn->m->free_reference(conn); ++ mnd_efree(stmt->execute_cmd_buffer.buffer); + /* XXX: This will crash, because we will null also the methods. + But seems it happens in extreme cases or doesn't. Should be fixed by exporting a function + (from mysqlnd_driver.c?) to do the reset. +diff --git a/ext/mysqlnd/mysqlnd_ps_codec.c b/ext/mysqlnd/mysqlnd_ps_codec.c +index 12edd9a..db44edb 100644 +--- a/ext/mysqlnd/mysqlnd_ps_codec.c ++++ b/ext/mysqlnd/mysqlnd_ps_codec.c +@@ -52,6 +52,51 @@ struct st_mysqlnd_perm_bind mysqlnd_ps_fetch_functions[MYSQL_TYPE_LAST + 1]; + #define MYSQLND_PS_SKIP_RESULT_W_LEN -1 + #define MYSQLND_PS_SKIP_RESULT_STR -2 + ++static inline void ps_fetch_over_read_error(const zend_uchar ** row) ++{ ++ php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing after the end of packet"); ++ *row = NULL; ++} ++ ++static inline zend_bool ps_fetch_is_packet_over_read_with_variable_length(const unsigned int pack_len, ++ const zend_uchar ** row, const zend_uchar *p, unsigned int length) ++{ ++ if (pack_len == 0) { ++ return 0; ++ } ++ size_t length_len = *row - p; ++ /* This assert should never fire, otherwise we invoked UB earlier */ ++ ZEND_ASSERT(length_len <= pack_len); ++ if (length > pack_len - length_len) { ++ ps_fetch_over_read_error(row); ++ return 1; ++ } ++ return 0; ++} ++ ++static inline zend_bool ps_fetch_is_packet_over_read_with_static_length(const unsigned int pack_len, ++ const zend_uchar ** row, unsigned int length) ++{ ++ if (pack_len > 0 && length > pack_len) { ++ ps_fetch_over_read_error(row); ++ return 1; ++ } ++ return 0; ++} ++ ++/* The declared length has to cover the fixed offsets that the field type reads. */ ++static inline zend_bool ps_fetch_is_length_too_short(const zend_uchar ** row, const zend_ulong length, ++ const unsigned int min_length) ++{ ++ if (UNEXPECTED(length < min_length)) { ++ php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length is too short for the field type"); ++ *row = NULL; ++ return 1; ++ } ++ return 0; ++} ++ ++ + /* {{{ ps_fetch_from_1_to_8_bytes */ + void + ps_fetch_from_1_to_8_bytes(zval * zv, const MYSQLND_FIELD * const field, const unsigned int pack_len, +@@ -60,6 +105,11 @@ ps_fetch_from_1_to_8_bytes(zval * zv, const MYSQLND_FIELD * const field, const u + char tmp[22]; + size_t tmp_len = 0; + zend_bool is_bit = field->type == MYSQL_TYPE_BIT; ++ ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, byte_count))) { ++ return; ++ } ++ + DBG_ENTER("ps_fetch_from_1_to_8_bytes"); + DBG_INF_FMT("zv=%p byte_count=%u", zv, byte_count); + if (field->flags & UNSIGNED_FLAG) { +@@ -178,6 +228,11 @@ ps_fetch_float(zval * zv, const MYSQLND_FIELD * const field, const unsigned int + float fval; + double dval; + DBG_ENTER("ps_fetch_float"); ++ ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, 4))) { ++ return; ++ } ++ + float4get(fval, *row); + (*row)+= 4; + DBG_INF_FMT("value=%f", fval); +@@ -200,6 +255,11 @@ ps_fetch_double(zval * zv, const MYSQLND_FIELD * const field, const unsigned int + { + double value; + DBG_ENTER("ps_fetch_double"); ++ ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, 8))) { ++ return; ++ } ++ + float8get(value, *row); + ZVAL_DOUBLE(zv, value); + (*row)+= 8; +@@ -216,9 +276,18 @@ ps_fetch_time(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p + struct st_mysqlnd_time t; + zend_ulong length; /* First byte encodes the length*/ + char * value; ++ const zend_uchar *p = *row; + DBG_ENTER("ps_fetch_time"); + +- if ((length = php_mysqlnd_net_field_length(row))) { ++ if ((length = php_mysqlnd_net_field_length(row, pack_len))) { ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) { ++ return; ++ } ++ ++ if (UNEXPECTED(ps_fetch_is_length_too_short(row, length, 8))) { ++ return; ++ } ++ + const zend_uchar * to = *row; + + t.time_type = MYSQLND_TIMESTAMP_TIME; +@@ -228,7 +297,7 @@ ps_fetch_time(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p + t.hour = (unsigned int) to[5]; + t.minute = (unsigned int) to[6]; + t.second = (unsigned int) to[7]; +- t.second_part = (length > 8) ? (zend_ulong) sint4korr(to+8) : 0; ++ t.second_part = (length >= 12) ? (zend_ulong) sint4korr(to+8) : 0; + t.year = t.month= 0; + if (t.day) { + /* Convert days to hours at once */ +@@ -273,9 +342,18 @@ ps_fetch_date(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p + struct st_mysqlnd_time t = {0}; + zend_ulong length; /* First byte encodes the length*/ + char * value; ++ const zend_uchar *p = *row; + DBG_ENTER("ps_fetch_date"); + +- if ((length = php_mysqlnd_net_field_length(row))) { ++ if ((length = php_mysqlnd_net_field_length(row, pack_len))) { ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) { ++ return; ++ } ++ ++ if (UNEXPECTED(ps_fetch_is_length_too_short(row, length, 4))) { ++ return; ++ } ++ + const zend_uchar * to = *row; + + t.time_type = MYSQLND_TIMESTAMP_DATE; +@@ -287,7 +365,7 @@ ps_fetch_date(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p + t.month = (unsigned int) to[2]; + t.day = (unsigned int) to[3]; + +- (*row)+= length; ++ (*row) += length; + } else { + memset(&t, 0, sizeof(t)); + t.time_type = MYSQLND_TIMESTAMP_DATE; +@@ -310,9 +388,18 @@ ps_fetch_datetime(zval * zv, const MYSQLND_FIELD * const field, const unsigned i + struct st_mysqlnd_time t; + zend_ulong length; /* First byte encodes the length*/ + char * value; ++ const zend_uchar *p = *row; + DBG_ENTER("ps_fetch_datetime"); + +- if ((length = php_mysqlnd_net_field_length(row))) { ++ if ((length = php_mysqlnd_net_field_length(row, pack_len))) { ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) { ++ return; ++ } ++ ++ if (UNEXPECTED(ps_fetch_is_length_too_short(row, length, 4))) { ++ return; ++ } ++ + const zend_uchar * to = *row; + + t.time_type = MYSQLND_TIMESTAMP_DATETIME; +@@ -322,16 +409,16 @@ ps_fetch_datetime(zval * zv, const MYSQLND_FIELD * const field, const unsigned i + t.month = (unsigned int) to[2]; + t.day = (unsigned int) to[3]; + +- if (length > 4) { ++ if (length >= 7) { + t.hour = (unsigned int) to[4]; + t.minute = (unsigned int) to[5]; + t.second = (unsigned int) to[6]; + } else { + t.hour = t.minute = t.second= 0; + } +- t.second_part = (length > 7) ? (zend_ulong) sint4korr(to+7) : 0; ++ t.second_part = (length >= 11) ? (zend_ulong) sint4korr(to+7) : 0; + +- (*row)+= length; ++ (*row) += length; + } else { + memset(&t, 0, sizeof(t)); + t.time_type = MYSQLND_TIMESTAMP_DATETIME; +@@ -371,7 +458,11 @@ ps_fetch_string(zval * zv, const MYSQLND_FIELD * const field, const unsigned int + For now just copy, before we make it possible + to write \0 to the row buffer + */ +- const zend_ulong length = php_mysqlnd_net_field_length(row); ++ const zend_uchar *p = *row; ++ const zend_ulong length = php_mysqlnd_net_field_length(row, pack_len); ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) { ++ return; ++ } + DBG_ENTER("ps_fetch_string"); + DBG_INF_FMT("len = %lu", length); + DBG_INF("copying from the row buffer"); +@@ -387,7 +478,11 @@ ps_fetch_string(zval * zv, const MYSQLND_FIELD * const field, const unsigned int + static void + ps_fetch_bit(zval * zv, const MYSQLND_FIELD * const field, const unsigned int pack_len, const zend_uchar ** row) + { +- const zend_ulong length = php_mysqlnd_net_field_length(row); ++ const zend_uchar *p = *row; ++ const zend_ulong length = php_mysqlnd_net_field_length(row, pack_len); ++ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) { ++ return; ++ } + ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, length); + } + /* }}} */ +diff --git a/ext/mysqlnd/mysqlnd_result.c b/ext/mysqlnd/mysqlnd_result.c +index 4dcaf12..9f19adb 100644 +--- a/ext/mysqlnd/mysqlnd_result.c ++++ b/ext/mysqlnd/mysqlnd_result.c +@@ -505,7 +505,7 @@ mysqlnd_query_read_result_set_header(MYSQLND_CONN_DATA * conn, MYSQLND_STMT * s) + if (FAIL == (ret = result->m.read_result_metadata(result, conn))) { + /* For PS, we leave them in Prepared state */ + if (!stmt && conn->current_result) { +- mnd_efree(conn->current_result); ++ conn->current_result->m.free_result(conn->current_result, TRUE); + conn->current_result = NULL; + } + DBG_ERR("Error occurred while reading metadata"); +@@ -549,8 +549,8 @@ mysqlnd_query_read_result_set_header(MYSQLND_CONN_DATA * conn, MYSQLND_STMT * s) + } + MYSQLND_INC_CONN_STATISTIC(conn->stats, statistic); + } ++ PACKET_FREE(&fields_eof); + } while (0); +- PACKET_FREE(&fields_eof); + break; /* switch break */ + } + } while (0); +diff --git a/ext/mysqlnd/mysqlnd_wireprotocol.c b/ext/mysqlnd/mysqlnd_wireprotocol.c +index e4a298a..75dbe5e 100644 +--- a/ext/mysqlnd/mysqlnd_wireprotocol.c ++++ b/ext/mysqlnd/mysqlnd_wireprotocol.c +@@ -26,11 +26,18 @@ + #include "mysqlnd_statistics.h" + #include "mysqlnd_debug.h" + +-#define BAIL_IF_NO_MORE_DATA \ +- if (UNEXPECTED((size_t)(p - begin) > packet->header.size)) { \ ++#define BAIL_PREMATURE_END do { \ + php_error_docref(NULL, E_WARNING, "Premature end of data (mysqlnd_wireprotocol.c:%u)", __LINE__); \ + goto premature_end; \ +- } \ ++ } while (0) ++ ++/* Bail out unless the packet still has the required number of bytes left to read. */ ++#define BAIL_IF_NOT_ENOUGH_DATA_EX(min_required_bytes) \ ++ if (UNEXPECTED((size_t)(p - begin) + (min_required_bytes) > packet->header.size)) { \ ++ BAIL_PREMATURE_END; \ ++ } ++ ++#define BAIL_IF_NOT_ENOUGH_DATA BAIL_IF_NOT_ENOUGH_DATA_EX(1) + + + static const char *unknown_sqlstate= "HY000"; +@@ -92,10 +99,14 @@ static enum_mysqlnd_collected_stats packet_type_to_statistic_packet_count[PROT_L + /* {{{ php_mysqlnd_net_field_length + Get next field's length */ + zend_ulong +-php_mysqlnd_net_field_length(const zend_uchar **packet) ++php_mysqlnd_net_field_length(const zend_uchar **packet, size_t remaining_size) + { + register const zend_uchar *p= (const zend_uchar *)*packet; + ++ if (UNEXPECTED(remaining_size == 0)) { ++ return MYSQLND_INVALID_NET_FIELD_LENGTH; ++ } ++ + if (*p < 251) { + (*packet)++; + return (zend_ulong) *p; +@@ -106,14 +117,23 @@ php_mysqlnd_net_field_length(const zend_uchar **packet) + (*packet)++; + return MYSQLND_NULL_LENGTH; + case 252: +- (*packet) += 3; +- return (zend_ulong) uint2korr(p+1); ++ if (EXPECTED(remaining_size >= 3)) { ++ (*packet) += 3; ++ return (zend_ulong) uint2korr(p+1); ++ } ++ return MYSQLND_INVALID_NET_FIELD_LENGTH; + case 253: +- (*packet) += 4; +- return (zend_ulong) uint3korr(p+1); ++ if (EXPECTED(remaining_size >= 4)) { ++ (*packet) += 4; ++ return (zend_ulong) uint3korr(p+1); ++ } ++ return MYSQLND_INVALID_NET_FIELD_LENGTH; + default: +- (*packet) += 9; +- return (zend_ulong) uint4korr(p+1); ++ if (EXPECTED(remaining_size >= 9)) { ++ (*packet) += 9; ++ return (zend_ulong) uint4korr(p+1); ++ } ++ return MYSQLND_INVALID_NET_FIELD_LENGTH; + } + } + /* }}} */ +@@ -121,29 +141,53 @@ php_mysqlnd_net_field_length(const zend_uchar **packet) + + /* {{{ php_mysqlnd_net_field_length_ll + Get next field's length */ +-uint64_t +-php_mysqlnd_net_field_length_ll(const zend_uchar **packet) ++MYSQLND_OPTIONAL_UINT64_T ++php_mysqlnd_net_field_length_ll(const zend_uchar **packet, size_t remaining_size) + { + register const zend_uchar *p = (zend_uchar *)*packet; + ++ MYSQLND_OPTIONAL_UINT64_T result; ++ result.has_value = 0; ++ result.value = 0; ++ ++ if (UNEXPECTED(remaining_size == 0)) { ++ return result; ++ } ++ + if (*p < 251) { + (*packet)++; +- return (uint64_t) *p; ++ result.value = (uint64_t) *p; ++ result.has_value = 1; ++ return result; + } + + switch (*p) { + case 251: + (*packet)++; +- return (uint64_t) MYSQLND_NULL_LENGTH; ++ result.value = MYSQLND_NULL_LENGTH; ++ result.has_value = 1; ++ return result; + case 252: +- (*packet) += 3; +- return (uint64_t) uint2korr(p + 1); ++ if (EXPECTED(remaining_size >= 3)) { ++ (*packet) += 3; ++ result.value = (uint64_t) uint2korr(p+1); ++ result.has_value = 1; ++ } ++ return result; + case 253: +- (*packet) += 4; +- return (uint64_t) uint3korr(p + 1); ++ if (EXPECTED(remaining_size >= 4)) { ++ (*packet) += 4; ++ result.value = (uint64_t) uint3korr(p+1); ++ result.has_value = 1; ++ } ++ return result; + default: +- (*packet) += 9; +- return (uint64_t) uint8korr(p + 1); ++ if (EXPECTED(remaining_size >= 9)) { ++ (*packet) += 9; ++ result.value = uint8korr(p+1); ++ result.has_value = 1; ++ } ++ return result; + } + } + /* }}} */ +@@ -339,22 +383,14 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, sizeof(buf), "greeting", PROT_GREET_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + packet->authentication_plugin_data.s = packet->intern_auth_plugin_data; + packet->authentication_plugin_data.l = sizeof(packet->intern_auth_plugin_data); + +- if (packet->header.size < sizeof(buf)) { +- /* +- Null-terminate the string, so strdup can work even if the packets have a string at the end, +- which is not ASCIIZ +- */ +- buf[packet->header.size] = '\0'; +- } +- + packet->protocol_version = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->protocol_version) { + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, +@@ -372,39 +408,38 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_RETURN(PASS); + } + +- packet->server_version = estrdup((char *)p); +- p+= strlen(packet->server_version) + 1; /* eat the '\0' */ +- BAIL_IF_NO_MORE_DATA; ++ /* This server version string MUST be NUL terminated, search for a NUL byte in the remaining space. */ ++ const char *version_nul_byte = memchr(p, '\0', packet->header.size - (p - begin)); ++ if (!version_nul_byte) { ++ BAIL_PREMATURE_END; ++ } ++ packet->server_version = estrndup((char *) p, version_nul_byte - (const char *) p); ++ p = (unsigned char *) version_nul_byte + 1; /* eat the '\0' */ ++ ++ BAIL_IF_NOT_ENOUGH_DATA_EX(4 + SCRAMBLE_LENGTH_323 + 1 + 2 + 1 + 2 + 13); + + packet->thread_id = uint4korr(p); + p+=4; +- BAIL_IF_NO_MORE_DATA; + + memcpy(packet->authentication_plugin_data.s, p, SCRAMBLE_LENGTH_323); + p+= SCRAMBLE_LENGTH_323; +- BAIL_IF_NO_MORE_DATA; + + /* pad1 */ + p++; +- BAIL_IF_NO_MORE_DATA; + + packet->server_capabilities = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + DBG_INF_FMT("4.1 server_caps=%u\n", (uint32_t) packet->server_capabilities); + + packet->charset_no = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; + + packet->server_status = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + /* pad2 */ + pad_start = p; + p+= 13; +- BAIL_IF_NO_MORE_DATA; + + if ((size_t) (p - buf) < packet->header.size) { + /* auth_plugin_data is split into two parts */ +@@ -426,6 +461,9 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) + /* And a length of the server scramble in one byte */ + packet->authentication_plugin_data.l = uint1korr(pad_start + 2); + if (packet->authentication_plugin_data.l > SCRAMBLE_LENGTH) { ++ /* the rest of the scramble has to be in the packet */ ++ BAIL_IF_NOT_ENOUGH_DATA_EX(packet->authentication_plugin_data.l - SCRAMBLE_LENGTH); ++ + /* more data*/ + char * new_auth_plugin_data = emalloc(packet->authentication_plugin_data.l); + +@@ -439,10 +477,36 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) + } + + if (packet->server_capabilities & CLIENT_PLUGIN_AUTH) { +- BAIL_IF_NO_MORE_DATA; ++ /* This is actually checked above and it needs to pass to set extended server capabilities ++ * so it should never bail. */ ++ BAIL_IF_NOT_ENOUGH_DATA; + /* The server is 5.5.x and supports authentication plugins */ +- packet->auth_protocol = estrdup((char *)p); +- p+= strlen(packet->auth_protocol) + 1; /* eat the '\0' */ ++ size_t remaining_size = packet->header.size - (size_t)(p - buf); ++ if (remaining_size == 0) { ++ /* This should never happen as the size should be at least 1 but it is kept just in ++ * case something above changes. */ ++ packet->auth_protocol = estrdup(""); ++ } else { ++ /* Check if NUL present */ ++ char *null_terminator = memchr(p, '\0', remaining_size); ++ size_t auth_protocol_len; ++ if (null_terminator) { ++ /* If present, do basically estrdup */ ++ auth_protocol_len = null_terminator - (char *)p; ++ } else { ++ /* If not present, copy the rest of the buffer */ ++ auth_protocol_len = remaining_size; ++ } ++ char *auth_protocol = emalloc(auth_protocol_len + 1); ++ memcpy(auth_protocol, p, auth_protocol_len); ++ auth_protocol[auth_protocol_len] = '\0'; ++ packet->auth_protocol = auth_protocol; ++ ++ p += auth_protocol_len; ++ if (null_terminator) { ++ p++; ++ } ++ } + } + + DBG_INF_FMT("proto=%u server=%s thread_id=%u", +@@ -454,9 +518,8 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) + + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("GREET packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "GREET packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("GREET packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "GREET packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -661,7 +724,7 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "OK", PROT_OK_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + /* + zero-terminate the buffer for safety. We are sure there is place for the \0 +@@ -672,7 +735,7 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) + /* Should be always 0x0 or ERROR_MARKER for error */ + packet->response_code = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->response_code) { + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, +@@ -684,9 +747,14 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (0xFE == packet->response_code) { + /* Authentication Switch Response */ + if (packet->header.size > (size_t) (p - buf)) { +- packet->new_auth_protocol = mnd_pestrdup((char *)p, FALSE); +- packet->new_auth_protocol_len = strlen(packet->new_auth_protocol); +- p+= packet->new_auth_protocol_len + 1; /* +1 for the \0 */ ++ /* The plugin name MUST be NUL terminated, search for a NUL byte in the remaining space. */ ++ const char *auth_protocol_nul_byte = memchr(p, '\0', packet->header.size - (p - buf)); ++ if (!auth_protocol_nul_byte) { ++ BAIL_PREMATURE_END; ++ } ++ packet->new_auth_protocol_len = auth_protocol_nul_byte - (const char *) p; ++ packet->new_auth_protocol = mnd_pestrndup((char *) p, packet->new_auth_protocol_len, FALSE); ++ p = (zend_uchar *) auth_protocol_nul_byte + 1; /* eat the '\0' */ + + packet->new_auth_protocol_data_len = packet->header.size - (size_t) (p - buf); + if (packet->new_auth_protocol_data_len) { +@@ -697,25 +765,42 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_INF_FMT("Server salt : [%d][%.*s]", packet->new_auth_protocol_data_len, packet->new_auth_protocol_data_len, packet->new_auth_protocol_data); + } + } else { +- zend_ulong net_len; + /* Everything was fine! */ +- packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; ++ zend_ulong net_len; ++ MYSQLND_OPTIONAL_UINT64_T len_ll; ++ ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->affected_rows = len_ll.value; ++ ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->last_insert_id = len_ll.value; + +- packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA_EX(4); + + packet->server_status = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + packet->warning_count = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + /* There is a message */ +- if (packet->header.size > (size_t) (p - buf) && (net_len = php_mysqlnd_net_field_length(&p))) { +- packet->message_len = MIN(net_len, buf_len - (p - begin)); ++ if (packet->header.size > (size_t) (p - buf) && (net_len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)))) { ++ /* In older versions of mysqlnd we had to perform an extra check because reading the field length ++ * could overread the OK packet. Now reading the length won't go out of bounds and we only have ++ * to check whether the message length is in bounds. */ ++ ZEND_ASSERT((p - buf) <= packet->header.size); ++ if (packet->header.size - (p - buf) < net_len) { ++ DBG_ERR_FMT("OK packet message length is past the packet size"); ++ php_error_docref(NULL, E_WARNING, "OK packet message length is past the packet size"); ++ DBG_RETURN(FAIL); ++ } ++ packet->message_len = net_len; + packet->message = mnd_pestrndup((char *)p, packet->message_len, FALSE); + } else { + packet->message = NULL; +@@ -729,9 +814,8 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) + + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "AUTH_RESPONSE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("OK packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "AUTH_RESPONSE packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -824,12 +908,12 @@ php_mysqlnd_ok_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "OK", PROT_OK_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + /* Should be always 0x0 or ERROR_MARKER for error */ + packet->field_count = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->field_count) { + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, +@@ -839,22 +923,33 @@ php_mysqlnd_ok_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_RETURN(PASS); + } + /* Everything was fine! */ +- packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; ++ MYSQLND_OPTIONAL_UINT64_T len_ll; + +- packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->affected_rows = len_ll.value; ++ ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->last_insert_id = len_ll.value; ++ ++ BAIL_IF_NOT_ENOUGH_DATA_EX(4); + + packet->server_status = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + packet->warning_count = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + /* There is a message */ +- if (packet->header.size > (size_t) (p - buf) && (net_len = php_mysqlnd_net_field_length(&p))) { ++ if (packet->header.size > (size_t) (p - buf) && (net_len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)))) { ++ if (UNEXPECTED(net_len == MYSQLND_INVALID_NET_FIELD_LENGTH)) { ++ BAIL_PREMATURE_END; ++ } + packet->message_len = MIN(net_len, buf_len - (p - begin)); + packet->message = mnd_pestrndup((char *)p, packet->message_len, FALSE); + } else { +@@ -866,13 +961,10 @@ php_mysqlnd_ok_read(MYSQLND_CONN_DATA * conn, void * _packet) + packet->affected_rows, packet->last_insert_id, packet->server_status, + packet->warning_count); + +- BAIL_IF_NO_MORE_DATA; +- + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "OK packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("OK packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "OK packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -917,12 +1009,12 @@ php_mysqlnd_eof_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "EOF", PROT_EOF_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + /* Should be always EODATA_MARKER */ + packet->field_count = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->field_count) { + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, +@@ -938,28 +1030,25 @@ php_mysqlnd_eof_read(MYSQLND_CONN_DATA * conn, void * _packet) + according to the Docs@Forge!!! + */ + if (packet->header.size > 1) { ++ BAIL_IF_NOT_ENOUGH_DATA_EX(4); ++ + packet->warning_count = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + + packet->server_status = uint2korr(p); + p+= 2; +- BAIL_IF_NO_MORE_DATA; + } else { + packet->warning_count = 0; + packet->server_status = 0; + } + +- BAIL_IF_NO_MORE_DATA; +- + DBG_INF_FMT("EOF packet: fields=%u status=%u warnings=%u", + packet->field_count, packet->server_status, packet->warning_count); + + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("EOF packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "EOF packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("EOF packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "EOF packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -1049,13 +1138,14 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + const zend_uchar * p = buf; + const zend_uchar * const begin = buf; + size_t len; ++ MYSQLND_OPTIONAL_UINT64_T len_ll; + + DBG_ENTER("php_mysqlnd_rset_header_read"); + + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "resultset header", PROT_RSET_HEADER_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + /* + Don't increment. First byte is ERROR_MARKER on error, but otherwise is starting byte +@@ -1064,7 +1154,7 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (ERROR_MARKER == *p) { + /* Error */ + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, + packet->error_info.error, sizeof(packet->error_info.error), + &packet->error_info.error_no, packet->error_info.sqlstate +@@ -1072,8 +1162,11 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_RETURN(PASS); + } + +- packet->field_count = php_mysqlnd_net_field_length(&p); +- BAIL_IF_NO_MORE_DATA; ++ zend_ulong field_count = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(field_count == MYSQLND_INVALID_NET_FIELD_LENGTH)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->field_count = field_count; + + switch (packet->field_count) { + case MYSQLND_NULL_LENGTH: +@@ -1081,7 +1174,7 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + /* + First byte in the packet is the field count. + Thus, the name is size - 1. And we add 1 for a trailing \0. +- Because we have BAIL_IF_NO_MORE_DATA before the switch, we are guaranteed ++ Because we have BAIL_IF_NOT_ENOUGH_DATA before the switch, we are guaranteed + that packet->header.size is > 0. Which means that len can't underflow, that + would lead to 0 byte allocation but 2^32 or 2^64 bytes copied. + */ +@@ -1098,21 +1191,42 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + break; + case 0x00: + DBG_INF("UPSERT"); +- packet->affected_rows = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; + +- packet->last_insert_id = php_mysqlnd_net_field_length_ll(&p); +- BAIL_IF_NO_MORE_DATA; ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->affected_rows = len_ll.value; ++ ++ len_ll = php_mysqlnd_net_field_length_ll(&p, packet->header.size - (p - begin)); ++ if (UNEXPECTED(!len_ll.has_value)) { ++ BAIL_PREMATURE_END; ++ } ++ packet->last_insert_id = len_ll.value; ++ ++ BAIL_IF_NOT_ENOUGH_DATA_EX(4); + + packet->server_status = uint2korr(p); + p+=2; +- BAIL_IF_NO_MORE_DATA; + + packet->warning_count = uint2korr(p); + p+=2; +- BAIL_IF_NO_MORE_DATA; ++ ++ len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)); ++ + /* Check for additional textual data */ +- if (packet->header.size > (size_t) (p - buf) && (len = php_mysqlnd_net_field_length(&p))) { ++ if (len && len != MYSQLND_INVALID_NET_FIELD_LENGTH) { ++ /* This checks both whether reading the len was successful ++ * and that the len is not greater than the packet size */ ++ if (packet->header.size - (p - buf) < len) { ++ size_t local_file_name_over_read = ((p - buf) - packet->header.size) + len; ++ DBG_ERR_FMT("RSET_HEADER packet additional data length is past %zu bytes the packet size", ++ local_file_name_over_read); ++ php_error_docref(NULL, E_WARNING, ++ "RSET_HEADER packet additional data length is past %zu bytes the packet size", ++ local_file_name_over_read); ++ DBG_RETURN(FAIL); ++ } + packet->info_or_local_file.s = mnd_emalloc(len + 1); + if (packet->info_or_local_file.s) { + memcpy(packet->info_or_local_file.s, p, len); +@@ -1132,13 +1246,11 @@ php_mysqlnd_rset_header_read(MYSQLND_CONN_DATA * conn, void * _packet) + /* Result set */ + break; + } +- BAIL_IF_NO_MORE_DATA; + + DBG_RETURN(ret); + premature_end: +- DBG_ERR_FMT("RSET_HEADER packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "RSET_HEADER packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("RSET_HEADER packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "RSET_HEADER packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -1159,8 +1271,8 @@ void php_mysqlnd_rset_header_free_mem(void * _packet) + /* }}} */ + + #define READ_RSET_FIELD(field_name) do { \ +- len = php_mysqlnd_net_field_length(&p); \ +- if (UNEXPECTED(len == MYSQLND_NULL_LENGTH)) { \ ++ zend_ulong len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)); \ ++ if (UNEXPECTED(len > packet->header.size - (p - begin))) { \ + goto faulty_or_fake; \ + } else if (len != 0) { \ + meta->field_name = (const char *)p; \ +@@ -1204,11 +1316,11 @@ php_mysqlnd_rset_field_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_RETURN(PASS); + } + +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + if (ERROR_MARKER == *p) { + /* Error */ + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, + packet->error_info.error, sizeof(packet->error_info.error), + &packet->error_info.error_no, packet->error_info.sqlstate +@@ -1271,23 +1383,15 @@ php_mysqlnd_rset_field_read(MYSQLND_CONN_DATA * conn, void * _packet) + meta->flags |= NUM_FLAG; + } + +- +- /* +- def could be empty, thus don't allocate on the root. +- NULL_LENGTH (0xFB) comes from COM_FIELD_LIST when the default value is NULL. +- Otherwise the string is length encoded. +- */ +- if (packet->header.size > (size_t) (p - buf) && +- (len = php_mysqlnd_net_field_length(&p)) && +- len != MYSQLND_NULL_LENGTH) ++ /* COM_FIELD_LIST is no longer supported so def should not be present */ ++ len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)); ++ if (len < MYSQLND_INVALID_NET_FIELD_LENGTH) + { +- BAIL_IF_NO_MORE_DATA; +- DBG_INF_FMT("Def found, length %lu", len); +- meta->def = packet->memory_pool->get_chunk(packet->memory_pool, len + 1); +- memcpy(meta->def, p, len); +- meta->def[len] = '\0'; +- meta->def_length = len; +- p += len; ++ DBG_ERR_FMT("Protocol error. Server sent default for unsupported field list"); ++ php_error_docref(NULL, E_WARNING, ++ "Protocol error. Server sent default for unsupported field list (mysqlnd_wireprotocol.c:%u)", ++ __LINE__); ++ DBG_RETURN(FAIL); + } + + root_ptr = meta->root = packet->memory_pool->get_chunk(packet->memory_pool, total_len); +@@ -1349,9 +1453,8 @@ faulty_or_fake: + " The server is faulty"); + DBG_RETURN(FAIL); + premature_end: +- DBG_ERR_FMT("RSET field packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "Result set field packet "MYSQLND_SZ_T_SPEC" bytes " +- "shorter than expected", p - begin - packet->header.size); ++ DBG_ERR_FMT("RSET field packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "Result set field packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -1462,8 +1565,10 @@ php_mysqlnd_rowp_read_binary_protocol(MYSQLND_ROW_BUFFER * row_buffer, zval * fi + const unsigned int field_count, const MYSQLND_FIELD * const fields_metadata, + const zend_bool as_int_or_float, MYSQLND_STATS * const stats) + { +- unsigned int i; +- const zend_uchar * p = row_buffer->ptr; ++ unsigned int i, j; ++ size_t rbs = row_buffer->size; ++ const zend_uchar * rbp = row_buffer->ptr; ++ const zend_uchar * p = rbp; + const zend_uchar * null_ptr; + zend_uchar bit; + zval *current_field, *end_field, *start_field; +@@ -1496,7 +1601,21 @@ php_mysqlnd_rowp_read_binary_protocol(MYSQLND_ROW_BUFFER * row_buffer, zval * fi + statistic = STAT_BINARY_TYPE_FETCHED_NULL; + } else { + enum_mysqlnd_field_types type = fields_metadata[i].type; +- mysqlnd_ps_fetch_functions[type].func(current_field, &fields_metadata[i], 0, &p); ++ size_t row_position = p - rbp; ++ if (rbs <= row_position) { ++ for (j = 0, current_field = start_field; j < i; current_field++, j++) { ++ zval_ptr_dtor(current_field); ++ } ++ php_error_docref(NULL, E_WARNING, "Malformed server packet. No packet space left for the field"); ++ DBG_RETURN(FAIL); ++ } ++ mysqlnd_ps_fetch_functions[type].func(current_field, &fields_metadata[i], rbs - row_position, &p); ++ if (p == NULL) { ++ for (j = 0, current_field = start_field; j < i; current_field++, j++) { ++ zval_ptr_dtor(current_field); ++ } ++ DBG_RETURN(FAIL); ++ } + + if (MYSQLND_G(collect_statistics)) { + switch (fields_metadata[i].type) { +@@ -1553,7 +1672,7 @@ php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_ROW_BUFFER * row_buffer, zval * + unsigned int field_count, const MYSQLND_FIELD * fields_metadata, + zend_bool as_int_or_float, MYSQLND_STATS * stats) + { +- unsigned int i; ++ unsigned int i, j; + zval *current_field, *end_field, *start_field; + zend_uchar * p = row_buffer->ptr; + const size_t data_size = row_buffer->size; +@@ -1569,14 +1688,16 @@ php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_ROW_BUFFER * row_buffer, zval * + + for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) { + /* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */ +- const zend_ulong len = php_mysqlnd_net_field_length((const zend_uchar **) &p); ++ zend_ulong len = php_mysqlnd_net_field_length((const zend_uchar **) &p, packet_end - p); + + /* NULL or NOT NULL, this is the question! */ + if (len == MYSQLND_NULL_LENGTH) { + ZVAL_NULL(current_field); +- } else if ((p + len) > packet_end) { +- php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing "MYSQLND_SZ_T_SPEC +- " bytes after end of packet", (p + len) - packet_end - 1); ++ } else if (len > packet_end - p) { ++ php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing after end of packet"); ++ for (j = 0, current_field = start_field; j < i; current_field++, j++) { ++ zval_ptr_dtor(current_field); ++ } + DBG_RETURN(FAIL); + } else { + #if defined(MYSQLND_STRING_TO_INT_CONVERSION) +@@ -1786,7 +1907,8 @@ php_mysqlnd_rowp_read(MYSQLND_CONN_DATA * conn, void * _packet) + } else if (EODATA_MARKER == *p && data_size < 8) { /* EOF */ + packet->eof = TRUE; + p++; +- if (data_size > 1) { ++ /* the marker is followed by 2 bytes of warnings and 2 bytes of status */ ++ if (data_size >= 5) { + packet->warning_count = uint2korr(p); + p += 2; + packet->server_status = uint2korr(p); +@@ -1921,12 +2043,12 @@ php_mysqlnd_prepare_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "prepare", PROT_PREPARE_RESP_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + data_size = packet->header.size; + packet->error_code = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->error_code) { + php_mysqlnd_read_error_from_line(p, data_size - 1, +@@ -1946,23 +2068,23 @@ php_mysqlnd_prepare_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_RETURN(FAIL); + } + ++ BAIL_IF_NOT_ENOUGH_DATA_EX(8); ++ + packet->stmt_id = uint4korr(p); + p += 4; +- BAIL_IF_NO_MORE_DATA; + + /* Number of columns in result set */ + packet->field_count = uint2korr(p); + p += 2; +- BAIL_IF_NO_MORE_DATA; + + packet->param_count = uint2korr(p); + p += 2; +- BAIL_IF_NO_MORE_DATA; + + if (data_size > 9) { ++ BAIL_IF_NOT_ENOUGH_DATA_EX(3); ++ + /* 0x0 filler sent by the server for 5.0+ clients */ + p++; +- BAIL_IF_NO_MORE_DATA; + + packet->warning_count = uint2korr(p); + } +@@ -1970,13 +2092,10 @@ php_mysqlnd_prepare_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_INF_FMT("Prepare packet read: stmt_id=%u fields=%u params=%u", + packet->stmt_id, packet->field_count, packet->param_count); + +- BAIL_IF_NO_MORE_DATA; +- + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("PREPARE packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "PREPARE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("PREPARE packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "PREPARE packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -2003,7 +2122,7 @@ php_mysqlnd_chg_user_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, buf_len, "change user response", PROT_CHG_USER_RESP_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + /* + Don't increment. First byte is ERROR_MARKER on error, but otherwise is starting byte +@@ -2028,11 +2147,16 @@ php_mysqlnd_chg_user_read(MYSQLND_CONN_DATA * conn, void * _packet) + packet->error_info.sqlstate + ); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + if (packet->response_code == 0xFE && packet->header.size > (size_t) (p - buf)) { +- packet->new_auth_protocol = mnd_pestrdup((char *)p, FALSE); +- packet->new_auth_protocol_len = strlen(packet->new_auth_protocol); +- p+= packet->new_auth_protocol_len + 1; /* +1 for the \0 */ ++ /* The plugin name MUST be NUL terminated, search for a NUL byte in the remaining space. */ ++ const char *auth_protocol_nul_byte = memchr(p, '\0', packet->header.size - (p - buf)); ++ if (!auth_protocol_nul_byte) { ++ BAIL_PREMATURE_END; ++ } ++ packet->new_auth_protocol_len = auth_protocol_nul_byte - (const char *) p; ++ packet->new_auth_protocol = mnd_pestrndup((char *) p, packet->new_auth_protocol_len, FALSE); ++ p = (zend_uchar *) auth_protocol_nul_byte + 1; /* eat the '\0' */ + packet->new_auth_protocol_data_len = packet->header.size - (size_t) (p - buf); + if (packet->new_auth_protocol_data_len) { + packet->new_auth_protocol_data = mnd_emalloc(packet->new_auth_protocol_data_len); +@@ -2044,9 +2168,8 @@ php_mysqlnd_chg_user_read(MYSQLND_CONN_DATA * conn, void * _packet) + + DBG_RETURN(PASS); + premature_end: +- DBG_ERR_FMT("CHANGE_USER packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "CHANGE_USER packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("CHANGE_USER packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "CHANGE_USER packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -2116,10 +2239,10 @@ php_mysqlnd_sha256_pk_request_response_read(MYSQLND_CONN_DATA * conn, void * _pa + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, sizeof(buf), "SHA256_PK_REQUEST_RESPONSE", PROT_SHA256_PK_REQUEST_RESPONSE_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + packet->public_key_len = packet->header.size - (p - buf); + packet->public_key = mnd_emalloc(packet->public_key_len + 1); +@@ -2129,9 +2252,8 @@ php_mysqlnd_sha256_pk_request_response_read(MYSQLND_CONN_DATA * conn, void * _pa + DBG_RETURN(PASS); + + premature_end: +- DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("OK packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet shorter than expected"); + DBG_RETURN(FAIL); + } + /* }}} */ +@@ -2193,11 +2315,11 @@ php_mysqlnd_cached_sha2_result_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (FAIL == mysqlnd_read_packet_header_and_body(&(packet->header), pfc, vio, stats, error_info, connection_state, buf, sizeof(buf), "PROT_CACHED_SHA2_RESULT_PACKET", PROT_CACHED_SHA2_RESULT_PACKET)) { + DBG_RETURN(FAIL); + } +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + packet->response_code = uint1korr(p); + p++; +- BAIL_IF_NO_MORE_DATA; ++ BAIL_IF_NOT_ENOUGH_DATA; + + if (ERROR_MARKER == packet->response_code) { + php_mysqlnd_read_error_from_line(p, packet->header.size - 1, +@@ -2209,9 +2331,14 @@ php_mysqlnd_cached_sha2_result_read(MYSQLND_CONN_DATA * conn, void * _packet) + if (0xFE == packet->response_code) { + /* Authentication Switch Response */ + if (packet->header.size > (size_t) (p - buf)) { +- packet->new_auth_protocol = mnd_pestrdup((char *)p, FALSE); +- packet->new_auth_protocol_len = strlen(packet->new_auth_protocol); +- p+= packet->new_auth_protocol_len + 1; /* +1 for the \0 */ ++ /* The plugin name MUST be NUL terminated, search for a NUL byte in the remaining space. */ ++ const char *auth_protocol_nul_byte = memchr(p, '\0', packet->header.size - (p - buf)); ++ if (!auth_protocol_nul_byte) { ++ BAIL_PREMATURE_END; ++ } ++ packet->new_auth_protocol_len = auth_protocol_nul_byte - (const char *) p; ++ packet->new_auth_protocol = mnd_pestrndup((char *) p, packet->new_auth_protocol_len, FALSE); ++ p = (zend_uchar *) auth_protocol_nul_byte + 1; /* eat the '\0' */ + + packet->new_auth_protocol_data_len = packet->header.size - (size_t) (p - buf); + if (packet->new_auth_protocol_data_len) { +@@ -2228,20 +2355,27 @@ php_mysqlnd_cached_sha2_result_read(MYSQLND_CONN_DATA * conn, void * _packet) + DBG_ERR_FMT("Unexpected response code %d", packet->response_code); + } + +- /* This is not really the response code, but we reuse the field. */ ++ BAIL_IF_NOT_ENOUGH_DATA; ++ ++ /* This is not really the response code, but we reuse the field. This should be either 0x03 if ++ * fast auth is used or 0x04 if full auth should be done. */ + packet->response_code = uint1korr(p); +- p++; +- BAIL_IF_NO_MORE_DATA; + +- packet->result = uint1korr(p); +- BAIL_IF_NO_MORE_DATA; ++ /* This should be removed in master and it is really kept for just in case scenario that should ++ * never happen because mysql-server sends only byte that is stored above. The result seems not ++ * to be used so there is not much point to set it in any case. */ ++ if (UNEXPECTED((size_t)(p - begin) + 2 <= packet->header.size)) { ++ p++; ++ packet->result = uint1korr(p); ++ } else { ++ packet->result = 0; ++ } + + DBG_RETURN(PASS); + + premature_end: +- DBG_ERR_FMT("OK packet %d bytes shorter than expected", p - begin - packet->header.size); +- php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet "MYSQLND_SZ_T_SPEC" bytes shorter than expected", +- p - begin - packet->header.size); ++ DBG_ERR_FMT("OK packet shorter than expected"); ++ php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet shorter than expected"); + DBG_RETURN(FAIL); + } + +diff --git a/ext/mysqlnd/mysqlnd_wireprotocol.h b/ext/mysqlnd/mysqlnd_wireprotocol.h +index c4ef4c3..98a73c0 100644 +--- a/ext/mysqlnd/mysqlnd_wireprotocol.h ++++ b/ext/mysqlnd/mysqlnd_wireprotocol.h +@@ -299,9 +299,19 @@ typedef struct st_mysqlnd_packet_cached_sha2_result { + unsigned int error_no; + } MYSQLND_PACKET_CACHED_SHA2_RESULT; + ++/* The following structure implements an optional value, ++ * which forces the caller to check if the value was correctly read, for safety reasons. */ + ++typedef struct st_mysqlnd_optional_uint64_t { ++ uint64_t value; ++ zend_bool has_value; ++} MYSQLND_OPTIONAL_UINT64_T; + +-zend_ulong php_mysqlnd_net_field_length(const zend_uchar **packet); ++/* must not be equal to MYSQLND_NULL_LENGTH, but larger than 2**24 */ ++#define MYSQLND_INVALID_NET_FIELD_LENGTH ((zend_ulong) -2) ++ ++/* Returns MYSQLND_INVALID_NET_FIELD_LENGTH on error */ ++zend_ulong php_mysqlnd_net_field_length(const zend_uchar **packet, size_t remaining_size); + zend_uchar * php_mysqlnd_net_store_length(zend_uchar *packet, const uint64_t length); + size_t php_mysqlnd_net_store_length_size(uint64_t length); + +diff --git a/ext/openssl/openssl.c b/ext/openssl/openssl.c +index 9866bf5..021ee64 100644 +--- a/ext/openssl/openssl.c ++++ b/ext/openssl/openssl.c +@@ -6669,6 +6669,7 @@ static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type, + char *aad, size_t aad_len, int enc) /* {{{ */ + { + int i = 0; ++ size_t outlen = data_len + EVP_CIPHER_block_size(cipher_type); + + if (mode->is_single_run_aead && !EVP_CipherUpdate(cipher_ctx, NULL, &i, NULL, (int)data_len)) { + php_openssl_store_errors(); +@@ -6682,7 +6683,19 @@ static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type, + return FAILURE; + } + +- *poutbuf = zend_string_alloc((int)data_len + EVP_CIPHER_block_size(cipher_type), 0); ++#ifdef EVP_CIPH_WRAP_MODE ++ if ((EVP_CIPHER_mode(cipher_type)) == EVP_CIPH_WRAP_MODE) { ++ /* ++ * RFC 5649 wrap-with-padding rounds the input up to the block size ++ * and prepends an integrity block, we reserve one extra block. ++ * See EVP_EncryptUpdate(3): wrap mode may write up to ++ * inl + cipher_block_size bytes. ++ */ ++ outlen += EVP_CIPHER_block_size(cipher_type); ++ } ++#endif ++ ++ *poutbuf = zend_string_alloc(outlen, 0); + + if (!EVP_CipherUpdate(cipher_ctx, (unsigned char*)ZSTR_VAL(*poutbuf), + &i, (unsigned char *)data, (int)data_len)) { +diff --git a/ext/openssl/tests/GHSA-xr7j-rvgx-xq5p.phpt b/ext/openssl/tests/GHSA-xr7j-rvgx-xq5p.phpt +new file mode 100644 +index 0000000..972fe4d +--- /dev/null ++++ b/ext/openssl/tests/GHSA-xr7j-rvgx-xq5p.phpt +@@ -0,0 +1,68 @@ ++--TEST-- ++GHSA-xr7j-rvgx-xq5p: OOB read in php_openssl_matches_wildcard_name() with overlapping wildcard prefix and suffix ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'local_cert' => '%s', ++ ]]); ++ ++ $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); ++ phpt_notify(); ++ ++ @stream_socket_accept($server, 1); ++ @stream_socket_accept($server, 1); ++CODE; ++$serverCode = sprintf($serverCode, $certFile); ++ ++$clientCode = <<<'CODE' ++ $serverUri = "ssl://127.0.0.1:64321"; ++ $clientFlags = STREAM_CLIENT_CONNECT; ++ $clientCtx = stream_context_create(['ssl' => [ ++ 'verify_peer' => false, ++ ]]); ++ ++ phpt_wait(); ++ ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'aaaa'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++ ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'www.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++CODE; ++ ++include 'CertificateGenerator.inc'; ++$certificateGenerator = new CertificateGenerator(); ++$certificateGenerator->saveNewCertAsFileWithKey('a*aaaa', $certFile, null, $san); ++ ++include 'ServerClientTestCase.inc'; ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `aaaa' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) ++ ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `www.example.org' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) +diff --git a/ext/openssl/tests/bug79589.phpt b/ext/openssl/tests/bug79589.phpt +new file mode 100644 +index 0000000..5d277e8 +--- /dev/null ++++ b/ext/openssl/tests/bug79589.phpt +@@ -0,0 +1,21 @@ ++--TEST-- ++Bug #65538: TLS unexpected EOF failure ++--EXTENSIONS-- ++openssl ++--SKIPIF-- ++ ++--FILE-- ++ ['verify_peer'=> false]]) ++); ++echo gettype($release); ++ ++?> ++--EXPECT-- ++string +diff --git a/ext/openssl/tests/gh22186.phpt b/ext/openssl/tests/gh22186.phpt +new file mode 100644 +index 0000000..8f28e6c +--- /dev/null ++++ b/ext/openssl/tests/gh22186.phpt +@@ -0,0 +1,32 @@ ++--TEST-- ++GH-22186 (Heap buffer overflow in openssl_encrypt with AES-WRAP-PAD) ++--EXTENSIONS-- ++openssl ++--SKIPIF-- ++ ++--FILE-- ++ ++--EXPECT-- ++done +diff --git a/ext/openssl/tests/san_absent_cn_fallback.phpt b/ext/openssl/tests/san_absent_cn_fallback.phpt +new file mode 100644 +index 0000000..fd17d86 +--- /dev/null ++++ b/ext/openssl/tests/san_absent_cn_fallback.phpt +@@ -0,0 +1,62 @@ ++--TEST-- ++Peer verification falls back to CN when the certificate has no SAN ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'local_cert' => '%s', ++ ]]); ++ ++ $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); ++ phpt_notify(); ++ ++ @stream_socket_accept($server, 1); ++ @stream_socket_accept($server, 1); ++CODE; ++$serverCode = sprintf($serverCode, $certFile); ++ ++$clientCode = <<<'CODE' ++ $serverUri = "ssl://127.0.0.1:64321"; ++ $clientFlags = STREAM_CLIENT_CONNECT; ++ $clientCtx = stream_context_create(['ssl' => [ ++ 'verify_peer' => false, ++ ]]); ++ ++ phpt_wait(); ++ ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'cn.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++ ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'other.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++CODE; ++ ++include 'CertificateGenerator.inc'; ++$certificateGenerator = new CertificateGenerator(); ++$certificateGenerator->saveNewCertAsFileWithKey('cn.example.org', $certFile); ++ ++include 'ServerClientTestCase.inc'; ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++resource(%d) of type (stream) ++ ++Warning: stream_socket_client(): Peer certificate CN=`cn.example.org' did not match expected CN=`other.example.org' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) +diff --git a/ext/openssl/tests/san_no_cn_fallback.phpt b/ext/openssl/tests/san_no_cn_fallback.phpt +new file mode 100644 +index 0000000..c28980a +--- /dev/null ++++ b/ext/openssl/tests/san_no_cn_fallback.phpt +@@ -0,0 +1,65 @@ ++--TEST-- ++Peer verification does not fall back to CN when the certificate has a SAN ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'local_cert' => '%s', ++ ]]); ++ ++ $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); ++ phpt_notify(); ++ ++ @stream_socket_accept($server, 1); ++ @stream_socket_accept($server, 1); ++CODE; ++$serverCode = sprintf($serverCode, $certFile); ++ ++$clientCode = <<<'CODE' ++ $serverUri = "ssl://127.0.0.1:64321"; ++ $clientFlags = STREAM_CLIENT_CONNECT; ++ $clientCtx = stream_context_create(['ssl' => [ ++ 'verify_peer' => false, ++ ]]); ++ ++ phpt_wait(); ++ ++ // The SAN entry is matched as usual. ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'san.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++ ++ // The CN must not be considered because the certificate presents a SAN. ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'cn.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++CODE; ++ ++include 'CertificateGenerator.inc'; ++$certificateGenerator = new CertificateGenerator(); ++$certificateGenerator->saveNewCertAsFileWithKey( ++ 'cn.example.org', $certFile, null, 'DNS:san.example.org'); ++ ++include 'ServerClientTestCase.inc'; ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++resource(%d) of type (stream) ++ ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `cn.example.org' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) +diff --git a/ext/openssl/tests/san_peer_matching.phpt b/ext/openssl/tests/san_peer_matching.phpt +index 6b2c4e4..b1a48f1 100644 +--- a/ext/openssl/tests/san_peer_matching.phpt ++++ b/ext/openssl/tests/san_peer_matching.phpt +@@ -55,7 +55,7 @@ ServerClientTestCase::getInstance()->run($clientCode, $serverCode); + --EXPECTF-- + resource(%d) of type (stream) + +-Warning: stream_socket_client(): Unable to locate peer certificate CN in %s on line %d ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `moar.example.org' in %s on line %d + + Warning: stream_socket_client(): Failed to enable crypto in %s on line %d + +diff --git a/ext/openssl/tests/san_srv_no_cn_fallback.phpt b/ext/openssl/tests/san_srv_no_cn_fallback.phpt +new file mode 100644 +index 0000000..40529a6 +--- /dev/null ++++ b/ext/openssl/tests/san_srv_no_cn_fallback.phpt +@@ -0,0 +1,58 @@ ++--TEST-- ++Peer verification does not fall back to CN when the certificate has an SRV-ID ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'local_cert' => '%s', ++ ]]); ++ ++ $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); ++ phpt_notify(); ++ ++ @stream_socket_accept($server, 1); ++CODE; ++$serverCode = sprintf($serverCode, $certFile); ++ ++$clientCode = <<<'CODE' ++ $serverUri = "ssl://127.0.0.1:64321"; ++ $clientFlags = STREAM_CLIENT_CONNECT; ++ $clientCtx = stream_context_create(['ssl' => [ ++ 'verify_peer' => false, ++ ]]); ++ ++ phpt_wait(); ++ ++ // The CN must not be considered because the certificate presents an SRV-ID. ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'cn.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++CODE; ++ ++include 'CertificateGenerator.inc'; ++$certificateGenerator = new CertificateGenerator(); ++$certificateGenerator->saveNewCertAsFileWithKey( ++ 'cn.example.org', $certFile, null, 'otherName:1.3.6.1.5.5.7.8.7;IA5STRING:_https.san.example.org'); ++ ++include 'ServerClientTestCase.inc'; ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `cn.example.org' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) +diff --git a/ext/openssl/tests/san_uri_no_cn_fallback.phpt b/ext/openssl/tests/san_uri_no_cn_fallback.phpt +new file mode 100644 +index 0000000..c409246 +--- /dev/null ++++ b/ext/openssl/tests/san_uri_no_cn_fallback.phpt +@@ -0,0 +1,58 @@ ++--TEST-- ++Peer verification does not fall back to CN when the certificate has a URI-ID ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'local_cert' => '%s', ++ ]]); ++ ++ $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); ++ phpt_notify(); ++ ++ @stream_socket_accept($server, 1); ++CODE; ++$serverCode = sprintf($serverCode, $certFile); ++ ++$clientCode = <<<'CODE' ++ $serverUri = "ssl://127.0.0.1:64321"; ++ $clientFlags = STREAM_CLIENT_CONNECT; ++ $clientCtx = stream_context_create(['ssl' => [ ++ 'verify_peer' => false, ++ ]]); ++ ++ phpt_wait(); ++ ++ // The CN must not be considered because the certificate presents a URI-ID. ++ stream_context_set_option($clientCtx, 'ssl', 'peer_name', 'cn.example.org'); ++ var_dump(stream_socket_client($serverUri, $errno, $errstr, 1, $clientFlags, $clientCtx)); ++CODE; ++ ++include 'CertificateGenerator.inc'; ++$certificateGenerator = new CertificateGenerator(); ++$certificateGenerator->saveNewCertAsFileWithKey( ++ 'cn.example.org', $certFile, null, 'URI:https://san.example.org/x'); ++ ++include 'ServerClientTestCase.inc'; ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `cn.example.org' in %s on line %d ++ ++Warning: stream_socket_client(): Failed to enable crypto in %s on line %d ++ ++Warning: stream_socket_client(): unable to connect to ssl://127.0.0.1:%d (Unknown error) in %s on line %d ++bool(false) +diff --git a/ext/openssl/xp_ssl.c b/ext/openssl/xp_ssl.c +index 9710e44..4571ab5 100644 +--- a/ext/openssl/xp_ssl.c ++++ b/ext/openssl/xp_ssl.c +@@ -389,8 +389,7 @@ static zend_bool php_openssl_x509_fingerprint_match(X509 *peer, zval *val) + static zend_bool php_openssl_matches_wildcard_name(const char *subjectname, const char *certname) /* {{{ */ + { + char *wildcard = NULL; +- ptrdiff_t prefix_len; +- size_t suffix_len, subject_len; ++ size_t prefix_len, suffix_len, subject_len; + + if (strcasecmp(subjectname, certname) == 0) { + return 1; +@@ -409,7 +408,7 @@ static zend_bool php_openssl_matches_wildcard_name(const char *subjectname, cons + + suffix_len = strlen(wildcard + 1); + subject_len = strlen(subjectname); +- if (suffix_len <= subject_len) { ++ if (suffix_len + prefix_len <= subject_len) { + /* 2) suffix must match + * 3) no . between prefix and suffix + **/ +@@ -421,7 +420,8 @@ static zend_bool php_openssl_matches_wildcard_name(const char *subjectname, cons + } + /* }}} */ + +-static zend_bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) /* {{{ */ ++static zend_bool php_openssl_matches_san_list( ++ X509 *peer, const char *subject_name, zend_bool *has_service_id) + { + int i, len; + unsigned char *cert_name = NULL; +@@ -430,10 +430,14 @@ static zend_bool php_openssl_matches_san_list(X509 *peer, const char *subject_na + GENERAL_NAMES *alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, 0, 0); + int alt_name_count = sk_GENERAL_NAME_num(alt_names); + ++ *has_service_id = 0; ++ + for (i = 0; i < alt_name_count; i++) { + GENERAL_NAME *san = sk_GENERAL_NAME_value(alt_names, i); + + if (san->type == GEN_DNS) { ++ *has_service_id = 1; ++ + ASN1_STRING_to_UTF8(&cert_name, san->d.dNSName); + if ((size_t)ASN1_STRING_length(san->d.dNSName) != strlen((const char*)cert_name)) { + OPENSSL_free(cert_name); +@@ -472,6 +476,16 @@ static zend_bool php_openssl_matches_san_list(X509 *peer, const char *subject_na + * Because IP SAN names are officially deprecated and are + * not allowed by CAs starting in 2015. Deal with it. + */ ++ } else if (san->type == GEN_URI) { ++ *has_service_id = 1; ++ } else if (san->type == GEN_OTHERNAME) { ++ char oid[32]; ++ ++ /* SRV-ID, matched by OID because NID_SRVName needs OpenSSL 3.0 */ ++ if (OBJ_obj2txt(oid, sizeof(oid), san->d.otherName->type_id, 1) > 0 ++ && strcmp(oid, "1.3.6.1.5.5.7.8.7") == 0) { ++ *has_service_id = 1; ++ } + } + } + +@@ -479,7 +493,6 @@ static zend_bool php_openssl_matches_san_list(X509 *peer, const char *subject_na + + return 0; + } +-/* }}} */ + + static zend_bool php_openssl_matches_common_name(X509 *peer, const char *subject_name) /* {{{ */ + { +@@ -585,8 +598,16 @@ static int php_openssl_apply_peer_verification_policy(SSL *ssl, X509 *peer, php_ + } + + if (peer_name) { +- if (php_openssl_matches_san_list(peer, peer_name)) { ++ zend_bool has_service_id = 0; ++ ++ if (php_openssl_matches_san_list(peer, peer_name, &has_service_id)) { + return SUCCESS; ++ } else if (has_service_id) { ++ /* CN must be ignored if the certificate presents a service identity. */ ++ php_error_docref(NULL, E_WARNING, ++ "Peer certificate subjectAltName did not match expected name `%s'", ++ peer_name); ++ return FAILURE; + } else if (php_openssl_matches_common_name(peer, peer_name)) { + return SUCCESS; + } else { +@@ -1640,6 +1661,11 @@ int php_openssl_setup_crypto(php_stream *stream, + + ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + ++#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF ++ /* Only for OpenSSL 3+ to keep OpenSSL 1.1.1 behavior */ ++ ssl_ctx_options |= SSL_OP_IGNORE_UNEXPECTED_EOF; ++#endif ++ + if (!GET_VER_OPT("disable_compression") || zend_is_true(val)) { + ssl_ctx_options |= SSL_OP_NO_COMPRESSION; + } +diff --git a/ext/pcre/php_pcre.c b/ext/pcre/php_pcre.c +index a93b35c..aacdf2b 100644 +--- a/ext/pcre/php_pcre.c ++++ b/ext/pcre/php_pcre.c +@@ -622,7 +622,7 @@ PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache_ex(zend_string *regex, in + + /* Parse through the leading whitespace, and display a warning if we + get to the end without encountering a delimiter. */ +- while (isspace((int)*(unsigned char *)p)) p++; ++ while (isspace((unsigned char)*p)) p++; + if (*p == 0) { + if (key != regex) { + zend_string_release_ex(key, 0); +@@ -636,7 +636,7 @@ PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache_ex(zend_string *regex, in + /* Get the delimiter and display a warning if it is alphanumeric + or a backslash. */ + delimiter = *p++; +- if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') { ++ if (isalnum((unsigned char)delimiter) || delimiter == '\\') { + if (key != regex) { + zend_string_release_ex(key, 0); + } +diff --git a/ext/pdo/pdo.c b/ext/pdo/pdo.c +index 88839bf..b3953aa 100644 +--- a/ext/pdo/pdo.c ++++ b/ext/pdo/pdo.c +@@ -262,7 +262,7 @@ PDO_API int php_pdo_parse_data_source(const char *data_source, zend_ulong data_s + } + } + +- while (i < data_source_len && isspace(data_source[i])) { ++ while (i < data_source_len && isspace((unsigned char)data_source[i])) { + i++; + } + +diff --git a/ext/pdo/pdo_sql_parser.re b/ext/pdo/pdo_sql_parser.re +index 71d4100..b077c52 100644 +--- a/ext/pdo/pdo_sql_parser.re ++++ b/ext/pdo/pdo_sql_parser.re +@@ -111,7 +111,7 @@ PDO_API int pdo_parse_params(pdo_stmt_t *stmt, char *inquery, size_t inquery_len + + if (t == PDO_PARSER_BIND) { + ptrdiff_t len = s.cur - s.tok; +- if ((inquery < (s.cur - len)) && isalnum(*(s.cur - len - 1))) { ++ if ((inquery < (s.cur - len)) && isalnum((unsigned char)s.cur[-len - 1])) { + continue; + } + query_type |= PDO_PLACEHOLDER_NAMED; +diff --git a/ext/pdo/pdo_stmt.c b/ext/pdo/pdo_stmt.c +index adc921b..0181c1c 100644 +--- a/ext/pdo/pdo_stmt.c ++++ b/ext/pdo/pdo_stmt.c +@@ -210,7 +210,7 @@ int pdo_stmt_describe_columns(pdo_stmt_t *stmt) /* {{{ */ + switch (stmt->dbh->desired_case) { + case PDO_CASE_UPPER: + while (*s != '\0') { +- *s = toupper(*s); ++ *s = toupper((unsigned char)*s); + s++; + } + break; +diff --git a/ext/pdo_dblib/dblib_driver.c b/ext/pdo_dblib/dblib_driver.c +index f36451a..1dc75a4 100644 +--- a/ext/pdo_dblib/dblib_driver.c ++++ b/ext/pdo_dblib/dblib_driver.c +@@ -154,6 +154,7 @@ static int dblib_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unqu + + size_t i; + char * q; ++ size_t extralen = 0; + *quotedlen = 0; + + if (H->assume_national_character_set_strings) { +@@ -168,7 +169,7 @@ static int dblib_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unqu + + /* Detect quoted length, adding extra char for doubled single quotes */ + for (i = 0; i < unquotedlen; i++) { +- if (unquoted[i] == '\'') ++*quotedlen; ++ if (unquoted[i] == '\'') ++extralen; + ++*quotedlen; + } + +@@ -176,6 +177,11 @@ static int dblib_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unqu + if (use_national_character_set) { + ++*quotedlen; /* N prefix */ + } ++ if (UNEXPECTED(*quotedlen > ZSTR_MAX_LEN - extralen)) { ++ return 0; ++ } ++ ++ *quotedlen += extralen; + q = *quoted = emalloc(*quotedlen + 1); /* Add byte for terminal null */ + if (use_national_character_set) { + *q++ = 'N'; +diff --git a/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt b/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt +new file mode 100644 +index 0000000..431c619 +--- /dev/null ++++ b/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt +@@ -0,0 +1,24 @@ ++--TEST-- ++GHSA-5hqh-c84r-qjcv (Integer overflow in the dblib quoter causing OOB writes) ++--EXTENSIONS-- ++pdo_dblib ++--SKIPIF-- ++ ++--INI-- ++memory_limit=-1 ++--FILE-- ++quote(str_repeat("'", 2147483646))); ++ ++?> ++--EXPECT-- ++bool(false) +diff --git a/ext/pdo_firebird/firebird_driver.c b/ext/pdo_firebird/firebird_driver.c +index 3e403af..5b74290 100644 +--- a/ext/pdo_firebird/firebird_driver.c ++++ b/ext/pdo_firebird/firebird_driver.c +@@ -243,7 +243,7 @@ free_statement: + static int firebird_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unquotedlen, /* {{{ */ + char **quoted, size_t *quotedlen, enum pdo_param_type paramtype) + { +- int qcount = 0; ++ size_t qcount = 0; + char const *co, *l, *r; + char *c; + +@@ -258,6 +258,10 @@ static int firebird_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t u + /* count the number of ' characters */ + for (co = unquoted; (co = strchr(co,'\'')); qcount++, co++); + ++ if (UNEXPECTED(unquotedlen + 2 > ZSTR_MAX_LEN - qcount)) { ++ return 0; ++ } ++ + *quotedlen = unquotedlen + qcount + 2; + *quoted = c = emalloc(*quotedlen+1); + *c++ = '\''; +diff --git a/ext/pdo_pgsql/pgsql_driver.c b/ext/pdo_pgsql/pgsql_driver.c +index e578bbc..021471c 100644 +--- a/ext/pdo_pgsql/pgsql_driver.c ++++ b/ext/pdo_pgsql/pgsql_driver.c +@@ -323,11 +323,15 @@ static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unqu + unsigned char *escaped; + pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; + size_t tmp_len; ++ int err; + + switch (paramtype) { + case PDO_PARAM_LOB: + /* escapedlen returned by PQescapeBytea() accounts for trailing 0 */ + escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, unquotedlen, &tmp_len); ++ if (escaped == NULL) { ++ return 0; ++ } + *quotedlen = tmp_len + 1; + *quoted = emalloc(*quotedlen + 1); + memcpy((*quoted)+1, escaped, *quotedlen-2); +@@ -339,7 +343,11 @@ static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unqu + default: + *quoted = safe_emalloc(2, unquotedlen, 3); + (*quoted)[0] = '\''; +- *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, unquotedlen, NULL); ++ *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, unquotedlen, &err); ++ if (err) { ++ efree(*quoted); ++ return 0; ++ } + (*quoted)[*quotedlen + 1] = '\''; + (*quoted)[*quotedlen + 2] = '\0'; + *quotedlen += 2; +diff --git a/ext/pdo_pgsql/tests/ghsa-8xr5-qppj-gvwj.phpt b/ext/pdo_pgsql/tests/ghsa-8xr5-qppj-gvwj.phpt +new file mode 100644 +index 0000000..019a02c +--- /dev/null ++++ b/ext/pdo_pgsql/tests/ghsa-8xr5-qppj-gvwj.phpt +@@ -0,0 +1,26 @@ ++--TEST-- ++#GHSA-8xr5-qppj-gvwj: NULL Pointer Derefernce for failed user input quoting ++--SKIPIF-- ++ ++--FILE-- ++setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ++$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); ++ ++$sql = "SELECT * FROM users where username = :username"; ++$stmt = $db->prepare($sql); ++ ++$p1 = "alice\x99"; ++var_dump($stmt->execute(['username' => $p1])); ++ ++?> ++--EXPECT-- ++bool(false) +diff --git a/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt b/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt +new file mode 100644 +index 0000000..60e1361 +--- /dev/null ++++ b/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt +@@ -0,0 +1,22 @@ ++--TEST-- ++#GHSA-hrwm-9436-5mv3: pdo_pgsql extension does not check for errors during escaping ++--SKIPIF-- ++ ++--FILE-- ++setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ++ ++$invalid = "ABC\xff\x30';"; ++var_dump($db->quote($invalid)); ++ ++?> ++--EXPECT-- ++bool(false) +diff --git a/ext/pdo_sqlite/sqlite_driver.c b/ext/pdo_sqlite/sqlite_driver.c +index 0595bd0..54f9d05 100644 +--- a/ext/pdo_sqlite/sqlite_driver.c ++++ b/ext/pdo_sqlite/sqlite_driver.c +@@ -233,6 +233,9 @@ static char *pdo_sqlite_last_insert_id(pdo_dbh_t *dbh, const char *name, size_t + /* NB: doesn't handle binary strings... use prepared stmts for that */ + static int sqlite_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unquotedlen, char **quoted, size_t *quotedlen, enum pdo_param_type paramtype ) + { ++ if (unquotedlen > (INT_MAX - 3) / 2) { ++ return 0; ++ } + *quoted = safe_emalloc(2, unquotedlen, 3); + sqlite3_snprintf(2*unquotedlen + 3, *quoted, "'%q'", unquoted); + *quotedlen = strlen(*quoted); +diff --git a/ext/pdo_sqlite/tests/bug81740.phpt b/ext/pdo_sqlite/tests/bug81740.phpt +new file mode 100644 +index 0000000..99fb07c +--- /dev/null ++++ b/ext/pdo_sqlite/tests/bug81740.phpt +@@ -0,0 +1,17 @@ ++--TEST-- ++Bug #81740 (PDO::quote() may return unquoted string) ++--SKIPIF-- ++ ++--INI-- ++memory_limit=-1 ++--FILE-- ++quote($string)); ++?> ++--EXPECT-- ++bool(false) +diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c +index 7dcd56c..37e6fae 100644 +--- a/ext/pgsql/pgsql.c ++++ b/ext/pgsql/pgsql.c +@@ -4393,10 +4393,16 @@ PHP_FUNCTION(pg_escape_string) + to = zend_string_safe_alloc(ZSTR_LEN(from), 2, 0, 0); + #ifdef HAVE_PQESCAPE_CONN + if (link) { ++ int err; + if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { + RETURN_FALSE; + } +- ZSTR_LEN(to) = PQescapeStringConn(pgsql, ZSTR_VAL(to), ZSTR_VAL(from), ZSTR_LEN(from), NULL); ++ ZSTR_LEN(to) = PQescapeStringConn(pgsql, ZSTR_VAL(to), ZSTR_VAL(from), ZSTR_LEN(from), &err); ++ if (err) { ++ zend_throw_exception(zend_ce_exception, "Escaping string failed", 0); ++ zend_string_efree(to); ++ return; ++ } + } else + #endif + { +@@ -4445,6 +4451,10 @@ PHP_FUNCTION(pg_escape_bytea) + } else + #endif + to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len); ++ if (to == NULL) { ++ zend_throw_exception(zend_ce_exception, "Escape failure", 0); ++ return; ++ } + + RETVAL_STRINGL(to, to_len-1); /* to_len includes additional '\0' */ + PQfreemem(to); +@@ -5529,7 +5539,7 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z + char *escaped; + smart_str querystr = {0}; + size_t new_len; +- int i, num_rows; ++ int i, num_rows, err; + zval elem; + + if (!*table_name) { +@@ -5570,7 +5580,14 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z + "WHERE a.attnum > 0 AND c.relname = '"); + } + escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1); +- new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL); ++ new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), &err); ++ if (err) { ++ php_error_docref(NULL, E_WARNING, "Escaping table name '%s' failed", table_name); ++ efree(src); ++ efree(escaped); ++ smart_str_free(&querystr); ++ return FAILURE; ++ } + if (new_len) { + smart_str_appendl(&querystr, escaped, new_len); + } +@@ -5578,7 +5595,14 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z + + smart_str_appends(&querystr, "' AND n.nspname = '"); + escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1); +- new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL); ++ new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), &err); ++ if (err) { ++ php_error_docref(NULL, E_WARNING, "Escaping table namespace '%s' failed", table_name); ++ efree(src); ++ efree(escaped); ++ smart_str_free(&querystr); ++ return FAILURE; ++ } + if (new_len) { + smart_str_appendl(&querystr, escaped, new_len); + } +@@ -5814,7 +5838,6 @@ static int php_pgsql_add_quotes(zval *src, zend_bool should_free) + assert(Z_TYPE_P(src) == IS_STRING); + assert(should_free == 1 || should_free == 0); + +- smart_str_appendc(&str, 'E'); + smart_str_appendc(&str, '\''); + smart_str_appendl(&str, Z_STRVAL_P(src), Z_STRLEN_P(src)); + smart_str_appendc(&str, '\''); +@@ -5850,7 +5873,7 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con + { + zend_string *field = NULL; + zval meta, *def, *type, *not_null, *has_default, *is_enum, *val, new_val; +- int err = 0, skip_field; ++ int err = 0, escape_err = 0, skip_field; + php_pgsql_data_type data_type; + + assert(pg_link != NULL); +@@ -6100,11 +6123,15 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con + zend_string *str; + /* PostgreSQL ignores \0 */ + str = zend_string_alloc(Z_STRLEN_P(val) * 2, 0); +- /* better to use PGSQLescapeLiteral since PGescapeStringConn does not handle special \ */ +- ZSTR_LEN(str) = PQescapeStringConn(pg_link, ZSTR_VAL(str), Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); +- str = zend_string_truncate(str, ZSTR_LEN(str), 0); +- ZVAL_NEW_STR(&new_val, str); +- php_pgsql_add_quotes(&new_val, 1); ++ ZSTR_LEN(str) = PQescapeStringConn(pg_link, ZSTR_VAL(str), ++ Z_STRVAL_P(val), Z_STRLEN_P(val), &escape_err); ++ if (escape_err) { ++ err = 1; ++ } else { ++ str = zend_string_truncate(str, ZSTR_LEN(str), 0); ++ ZVAL_NEW_STR(&new_val, str); ++ php_pgsql_add_quotes(&new_val, 1); ++ } + } + break; + +@@ -6126,7 +6153,15 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con + } + PGSQL_CONV_CHECK_IGNORE(); + if (err) { +- php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); ++ if (escape_err) { ++ php_error_docref(NULL, E_NOTICE, ++ "String value escaping failed for PostgreSQL '%s' (%s)", ++ Z_STRVAL_P(type), ZSTR_VAL(field)); ++ } else { ++ php_error_docref(NULL, E_NOTICE, ++ "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", ++ Z_STRVAL_P(type), ZSTR_VAL(field)); ++ } + } + break; + +@@ -6406,6 +6441,11 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con + #else + tmp = PQescapeBytea(Z_STRVAL_P(val), (unsigned char *)Z_STRLEN_P(val), &to_len); + #endif ++ if (tmp == NULL) { ++ php_error_docref(NULL, E_NOTICE, "Escaping value failed for %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); ++ err = 1; ++ break; ++ } + ZVAL_STRINGL(&new_val, (char *)tmp, to_len - 1); /* PQescapeBytea's to_len includes additional '\0' */ + PQfreemem(tmp); + php_pgsql_add_quotes(&new_val, 1); +@@ -6488,6 +6528,12 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con + zend_hash_update(Z_ARRVAL_P(result), field, &new_val); + } else { + char *escaped = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(field), ZSTR_LEN(field)); ++ if (escaped == NULL) { ++ /* This cannot fail because of invalid string but only due to failed memory allocation */ ++ php_error_docref(NULL, E_NOTICE, "Escaping field '%s' failed", ZSTR_VAL(field)); ++ err = 1; ++ break; ++ } + add_assoc_zval(result, escaped, &new_val); + PGSQLfree(escaped); + } +@@ -6566,7 +6612,7 @@ static int do_exec(smart_str *querystr, ExecStatusType expect, PGconn *pg_link, + } + /* }}} */ + +-static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */ ++static inline int build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */ + { + size_t table_len = strlen(table); + +@@ -6577,6 +6623,10 @@ static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const c + smart_str_appendl(querystr, table, len); + } else { + char *escaped = PGSQLescapeIdentifier(pg_link, table, len); ++ if (escaped == NULL) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape table name '%s'", table); ++ return FAILURE; ++ } + smart_str_appends(querystr, escaped); + PGSQLfree(escaped); + } +@@ -6589,11 +6639,17 @@ static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const c + smart_str_appendl(querystr, after_dot, len); + } else { + char *escaped = PGSQLescapeIdentifier(pg_link, after_dot, len); ++ if (escaped == NULL) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape table name '%s'", table); ++ return FAILURE; ++ } + smart_str_appendc(querystr, '.'); + smart_str_appends(querystr, escaped); + PGSQLfree(escaped); + } + } ++ ++ return SUCCESS; + } + /* }}} */ + +@@ -6615,7 +6671,9 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var + ZVAL_UNDEF(&converted); + if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0) { + smart_str_appends(&querystr, "INSERT INTO "); +- build_tablename(&querystr, pg_link, table); ++ if (build_tablename(&querystr, pg_link, table) == FAILURE) { ++ goto cleanup; ++ } + smart_str_appends(&querystr, " DEFAULT VALUES"); + + goto no_values; +@@ -6631,7 +6689,9 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var + } + + smart_str_appends(&querystr, "INSERT INTO "); +- build_tablename(&querystr, pg_link, table); ++ if (build_tablename(&querystr, pg_link, table) == FAILURE) { ++ goto cleanup; ++ } + smart_str_appends(&querystr, " ("); + + ZEND_HASH_FOREACH_STR_KEY(Z_ARRVAL_P(var_array), fld) { +@@ -6641,6 +6701,10 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var + } + if (opt & PGSQL_DML_ESCAPE) { + tmp = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(fld), ZSTR_LEN(fld) + 1); ++ if (tmp == NULL) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape field '%s'", ZSTR_VAL(fld)); ++ goto cleanup; ++ } + smart_str_appends(&querystr, tmp); + PGSQLfree(tmp); + } else { +@@ -6652,15 +6716,19 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var + smart_str_appends(&querystr, ") VALUES ("); + + /* make values string */ +- ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(var_array), val) { ++ ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(var_array), fld, val) { + /* we can avoid the key_type check here, because we tested it in the other loop */ + switch (Z_TYPE_P(val)) { + case IS_STRING: + if (opt & PGSQL_DML_ESCAPE) { +- size_t new_len; +- char *tmp; +- tmp = (char *)safe_emalloc(Z_STRLEN_P(val), 2, 1); +- new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); ++ int error; ++ char *tmp = safe_emalloc(Z_STRLEN_P(val), 2, 1); ++ size_t new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), &error); ++ if (error) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape field '%s' value", ZSTR_VAL(fld)); ++ efree(tmp); ++ goto cleanup; ++ } + smart_str_appendc(&querystr, '\''); + smart_str_appendl(&querystr, tmp, new_len); + smart_str_appendc(&querystr, '\''); +@@ -6810,6 +6878,10 @@ static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr, + } + if (opt & PGSQL_DML_ESCAPE) { + char *tmp = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(fld), ZSTR_LEN(fld) + 1); ++ if (tmp == NULL) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape field '%s'", ZSTR_VAL(fld)); ++ return -1; ++ } + smart_str_appends(querystr, tmp); + PGSQLfree(tmp); + } else { +@@ -6824,8 +6896,14 @@ static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr, + switch (Z_TYPE_P(val)) { + case IS_STRING: + if (opt & PGSQL_DML_ESCAPE) { ++ int error; + char *tmp = (char *)safe_emalloc(Z_STRLEN_P(val), 2, 1); +- size_t new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); ++ size_t new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), &error); ++ if (error) { ++ php_error_docref(NULL, E_NOTICE, "Failed to escape field '%s' value", ZSTR_VAL(fld)); ++ efree(tmp); ++ return -1; ++ } + smart_str_appendc(querystr, '\''); + smart_str_appendl(querystr, tmp, new_len); + smart_str_appendc(querystr, '\''); +@@ -6894,7 +6972,9 @@ PHP_PGSQL_API int php_pgsql_update(PGconn *pg_link, const char *table, zval *var + } + + smart_str_appends(&querystr, "UPDATE "); +- build_tablename(&querystr, pg_link, table); ++ if (build_tablename(&querystr, pg_link, table) == FAILURE) { ++ goto cleanup; ++ } + smart_str_appends(&querystr, " SET "); + + if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(var_array), 0, ",", 1, opt)) +@@ -6992,7 +7072,9 @@ PHP_PGSQL_API int php_pgsql_delete(PGconn *pg_link, const char *table, zval *ids + } + + smart_str_appends(&querystr, "DELETE FROM "); +- build_tablename(&querystr, pg_link, table); ++ if (build_tablename(&querystr, pg_link, table) == FAILURE) { ++ goto cleanup; ++ } + smart_str_appends(&querystr, " WHERE "); + + if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt)) +@@ -7130,7 +7212,9 @@ PHP_PGSQL_API int php_pgsql_result2array(PGresult *pg_result, zval *ret_array, l + } + + smart_str_appends(&querystr, "SELECT * FROM "); +- build_tablename(&querystr, pg_link, table); ++ if (build_tablename(&querystr, pg_link, table) == FAILURE) { ++ goto cleanup; ++ } + smart_str_appends(&querystr, " WHERE "); + + if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt)) +diff --git a/ext/pgsql/tests/10pg_convert_9.phpt b/ext/pgsql/tests/10pg_convert_9.phpt +index a839531..d956552 100644 +--- a/ext/pgsql/tests/10pg_convert_9.phpt ++++ b/ext/pgsql/tests/10pg_convert_9.phpt +@@ -24,7 +24,7 @@ array(3) { + [""num""]=> + string(4) "1234" + [""str""]=> +- string(6) "E'AAA'" ++ string(5) "'AAA'" + [""bin""]=> +- string(12) "E'\\x424242'" ++ string(11) "'\\x424242'" + } +diff --git a/ext/pgsql/tests/10pg_convert_json_array.phpt b/ext/pgsql/tests/10pg_convert_json_array.phpt +index 960cfd6..711d0df 100644 +--- a/ext/pgsql/tests/10pg_convert_json_array.phpt ++++ b/ext/pgsql/tests/10pg_convert_json_array.phpt +@@ -30,8 +30,8 @@ if (!pg_insert($db, $table_name_92, $fields)) { + --EXPECT-- + array(2) { + [""textary""]=> +- string(51) "E'{"meeting", "lunch", "training", "presentation"}'" ++ string(50) "'{"meeting", "lunch", "training", "presentation"}'" + [""jsn""]=> +- string(22) "E'{"f1":1,"f2":"foo"}'" ++ string(21) "'{"f1":1,"f2":"foo"}'" + } + OK +diff --git a/ext/pgsql/tests/12pg_insert_9.phpt b/ext/pgsql/tests/12pg_insert_9.phpt +index 275afc5..c7e7a98 100644 +--- a/ext/pgsql/tests/12pg_insert_9.phpt ++++ b/ext/pgsql/tests/12pg_insert_9.phpt +@@ -24,7 +24,7 @@ var_dump( pg_insert($db, $table_name, $fields, PGSQL_DML_EXEC) ); // Return reso + echo "Ok\n"; + ?> + --EXPECTF-- +-INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,E'AAA',E'\\x424242'); ++INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,'AAA','\\x424242'); + INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES ('1234','AAA','BBB'); + resource(%d) of type (pgsql result) + Ok +diff --git a/ext/pgsql/tests/14pg_update_9.phpt b/ext/pgsql/tests/14pg_update_9.phpt +index e3e802b..1e2ae37 100644 +--- a/ext/pgsql/tests/14pg_update_9.phpt ++++ b/ext/pgsql/tests/14pg_update_9.phpt +@@ -24,6 +24,6 @@ echo pg_update($db, $table_name, $fields, $ids, PGSQL_DML_STRING|PGSQL_DML_ESCAP + echo "Ok\n"; + ?> + --EXPECT-- +-UPDATE "php_pgsql_test" SET "num"=1234,"str"=E'ABC',"bin"=E'\\x58595a' WHERE "num"=1234; ++UPDATE "php_pgsql_test" SET "num"=1234,"str"='ABC',"bin"='\\x58595a' WHERE "num"=1234; + UPDATE "php_pgsql_test" SET "num"='1234',"str"='ABC',"bin"='XYZ' WHERE "num"='1234'; + Ok +diff --git a/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt b/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt +new file mode 100644 +index 0000000..f7f0dc8 +--- /dev/null ++++ b/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++GHSA-7qpv-r5mr-78m4: SQL injection via E'...' backslash breakout ++--CREDITS-- ++expatch.llc ++--SKIPIF-- ++ ++--FILE-- ++ "zzz' OR 1=1 --"]; ++var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params)); ++ ++$params = ['name' => "zzz\\' OR 1=1 --"]; ++var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params)); ++ ++$params = ['name' => "john\\', true) --", 'admin' => 'false']; ++echo pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_STRING) . "\n"; ++pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params); ++var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', ['id' => 3])[0]['admin']); ++ ++$params = ['name' => "jake\\', true) --", 'admin' => 'f']; ++echo pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_ESCAPE|PGSQL_DML_STRING) . "\n"; ++pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_EXEC|PGSQL_DML_ESCAPE); ++var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', ['id' => 4])[0]['admin']); ++ ++?> ++--EXPECT-- ++bool(false) ++bool(false) ++INSERT INTO "ghsa_7qpv_r5mr_78m4" ("name","admin") VALUES ('john\'', true) --','f'); ++string(1) "f" ++INSERT INTO "ghsa_7qpv_r5mr_78m4" ("name","admin") VALUES ('jake\'', true) --','f'); ++string(1) "f" ++--CLEAN-- ++ +diff --git a/ext/pgsql/tests/bug64609.phpt b/ext/pgsql/tests/bug64609.phpt +index e31ec8e..03cee4a 100644 +--- a/ext/pgsql/tests/bug64609.phpt ++++ b/ext/pgsql/tests/bug64609.phpt +@@ -26,5 +26,5 @@ var_dump($converted); + --EXPECT-- + array(1) { + [""a""]=> +- string(5) "E'ok'" ++ string(4) "'ok'" + } +diff --git a/ext/pgsql/tests/bug68638.phpt b/ext/pgsql/tests/bug68638.phpt +index e0701a7..336438c 100644 +--- a/ext/pgsql/tests/bug68638.phpt ++++ b/ext/pgsql/tests/bug68638.phpt +@@ -32,7 +32,7 @@ pg_query("DROP TABLE $table"); + + ?> + --EXPECT-- +-string(52) "UPDATE "test_68638" SET "value"=E'inf' WHERE "id"=1;" ++string(51) "UPDATE "test_68638" SET "value"='inf' WHERE "id"=1;" + array(2) { + ["id"]=> + string(1) "1" +diff --git a/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt b/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt +new file mode 100644 +index 0000000..c1c5e05 +--- /dev/null ++++ b/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt +@@ -0,0 +1,64 @@ ++--TEST-- ++#GHSA-hrwm-9436-5mv3: pgsql extension does not check for errors during escaping ++--EXTENSIONS-- ++pgsql ++--SKIPIF-- ++ ++--FILE-- ++ 'test'])); // table name str escape in php_pgsql_meta_data ++var_dump(pg_insert($db, "$invalid.tbl", ['bar' => 'test'])); // schema name str escape in php_pgsql_meta_data ++var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', ['bar' => $invalid])); // converted value str escape in php_pgsql_convert ++var_dump(pg_insert($db, $invalid, [])); // ident escape in build_tablename ++var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', [$invalid => 'foo'], $flags)); // ident escape for field php_pgsql_insert ++var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', ['bar' => $invalid], $flags)); // str escape for field value in php_pgsql_insert ++var_dump(pg_update($db, 'ghsa_hrmw_9436_5mv3', ['bar' => 'val'], [$invalid => 'test'], $flags)); // ident escape in build_assignment_string ++var_dump(pg_update($db, 'ghsa_hrmw_9436_5mv3', ['bar' => 'val'], ['bar' => $invalid], $flags)); // invalid str escape in build_assignment_string ++var_dump(pg_escape_literal($db, $invalid)); // pg_escape_literal escape ++var_dump(pg_escape_identifier($db, $invalid)); // pg_escape_identifier escape ++ ++?> ++--EXPECTF-- ++ ++Warning: pg_insert(): Escaping table name 'ABC%s';' failed in %s on line %d ++bool(false) ++ ++Warning: pg_insert(): Escaping table namespace 'ABC%s';.tbl' failed in %s on line %d ++bool(false) ++ ++Notice: pg_insert(): String value escaping failed for PostgreSQL 'text' (bar) in %s on line %d ++bool(false) ++ ++Notice: pg_insert(): Failed to escape table name 'ABC%s';' in %s on line %d ++bool(false) ++ ++Notice: pg_insert(): Failed to escape field 'ABC%s';' in %s on line %d ++bool(false) ++ ++Notice: pg_insert(): Failed to escape field 'bar' value in %s on line %d ++bool(false) ++ ++Notice: pg_update(): Failed to escape field 'ABC%s';' in %s on line %d ++bool(false) ++ ++Notice: pg_update(): Failed to escape field 'bar' value in %s on line %d ++bool(false) ++ ++Warning: pg_escape_literal(): Failed to escape in %s on line %d ++bool(false) ++ ++Warning: pg_escape_identifier(): Failed to escape in %s on line %d ++bool(false) +diff --git a/ext/phar/dirstream.c b/ext/phar/dirstream.c +index 4710703..490b145 100644 +--- a/ext/phar/dirstream.c ++++ b/ext/phar/dirstream.c +@@ -91,25 +91,28 @@ static int phar_dir_seek(php_stream *stream, zend_off_t offset, int whence, zend + */ + static ssize_t phar_dir_read(php_stream *stream, char *buf, size_t count) /* {{{ */ + { +- size_t to_read; + HashTable *data = (HashTable *)stream->abstract; + zend_string *str_key; + zend_ulong unused; + ++ if (count != sizeof(php_stream_dirent)) { ++ return -1; ++ } ++ + if (HASH_KEY_NON_EXISTENT == zend_hash_get_current_key(data, &str_key, &unused)) { + return 0; + } + + zend_hash_move_forward(data); +- to_read = MIN(ZSTR_LEN(str_key), count); + +- if (to_read == 0 || count < ZSTR_LEN(str_key)) { ++ php_stream_dirent *dirent = (php_stream_dirent *) buf; ++ ++ if (sizeof(dirent->d_name) <= ZSTR_LEN(str_key)) { + return 0; + } + +- memset(buf, 0, sizeof(php_stream_dirent)); +- memcpy(((php_stream_dirent *) buf)->d_name, ZSTR_VAL(str_key), to_read); +- ((php_stream_dirent *) buf)->d_name[to_read + 1] = '\0'; ++ memset(dirent, 0, sizeof(php_stream_dirent)); ++ PHP_STRLCPY(dirent->d_name, ZSTR_VAL(str_key), sizeof(dirent->d_name), ZSTR_LEN(str_key)); + + return sizeof(php_stream_dirent); + } +diff --git a/ext/phar/phar_internal.h b/ext/phar/phar_internal.h +index e999d9d..f0bd0ec 100644 +--- a/ext/phar/phar_internal.h ++++ b/ext/phar/phar_internal.h +@@ -113,8 +113,13 @@ + #define TAR_FILE '0' + #define TAR_LINK '1' + #define TAR_SYMLINK '2' ++#define TAR_CHAR '3' ++#define TAR_BLOCK '4' + #define TAR_DIR '5' ++#define TAR_FIFO '6' + #define TAR_NEW '8' ++#define TAR_LONGLINK 'K' ++#define TAR_LONGNAME 'L' + #define TAR_GLOBAL_HDR 'g' + #define TAR_FILE_HDR 'x' + +diff --git a/ext/phar/tar.c b/ext/phar/tar.c +index 03e6dd4..abb5d52 100644 +--- a/ext/phar/tar.c ++++ b/ext/phar/tar.c +@@ -37,6 +37,52 @@ static uint32_t phar_tar_number(char *buf, size_t len) /* {{{ */ + } + /* }}} */ + ++static zend_bool phar_tar_type_has_data(char typeflag) ++{ ++ switch (typeflag) { ++ case TAR_LINK: ++ case TAR_SYMLINK: ++ case TAR_CHAR: ++ case TAR_BLOCK: ++ case TAR_DIR: ++ case TAR_FIFO: ++ return 0; ++ default: ++ return 1; ++ } ++} ++ ++static zend_bool phar_tar_size(const char *buf, size_t len, uint32_t *result) ++{ ++ uint64_t num = 0; ++ size_t i = 0; ++ ++ while (i < len && buf[i] == ' ') { ++ ++i; ++ } ++ ++ /* GNU base-256 encoding is only used for sizes that do not fit the octal field */ ++ if (i < len && (((unsigned char) buf[i]) & 0x80)) { ++ return 0; ++ } ++ ++ while (i < len && buf[i] >= '0' && buf[i] <= '7') { ++ num = num * 8 + (buf[i] - '0'); ++ ++i; ++ } ++ ++ while (i < len && (buf[i] == ' ' || buf[i] == '\0')) { ++ ++i; ++ } ++ ++ if (i != len || num > UINT32_MAX - 511) { ++ return 0; ++ } ++ ++ *result = (uint32_t) num; ++ return 1; ++} ++ + /* adapted from format_octal() in libarchive + * + * Copyright (c) 2003-2009 Tim Kientzle +@@ -280,8 +326,32 @@ int phar_parse_tarfile(php_stream* fp, char *fname, size_t fname_len, char *alia + } + } + +- size = entry.uncompressed_filesize = entry.compressed_filesize = +- phar_tar_number(hdr->size, sizeof(hdr->size)); ++ if (!phar_tar_size(hdr->size, sizeof(hdr->size), &size)) { ++ if (error) { ++ spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname); ++ } ++ if (last_was_longlink) { ++ pefree(entry.filename, myphar->is_persistent); ++ } ++ php_stream_close(fp); ++ phar_destroy_phar_data(myphar); ++ return FAILURE; ++ } ++ entry.uncompressed_filesize = entry.compressed_filesize = size; ++ ++ /* GNU long link names are not supported, so refuse the record instead of ++ * registering it as an entry and dropping the link target of the entry that follows */ ++ if (hdr->typeflag == TAR_LONGLINK) { ++ if (error) { ++ spprintf(error, 4096, "phar error: \"%s\" is a tar file with an unsupported GNU long link entry", fname); ++ } ++ if (last_was_longlink) { ++ pefree(entry.filename, myphar->is_persistent); ++ } ++ php_stream_close(fp); ++ phar_destroy_phar_data(myphar); ++ return FAILURE; ++ } + + /* skip global/file headers (pax) */ + if (!old && (hdr->typeflag == TAR_GLOBAL_HDR || hdr->typeflag == TAR_FILE_HDR)) { +@@ -369,13 +439,13 @@ bail: + goto bail; + } + +- if (!last_was_longlink && hdr->typeflag == 'L') { ++ if (!last_was_longlink && hdr->typeflag == TAR_LONGNAME) { + last_was_longlink = 1; + /* support the ././@LongLink system for storing long filenames */ + entry.filename_len = entry.uncompressed_filesize; + + /* Check for overflow - bug 61065 */ +- if (entry.filename_len == UINT_MAX || entry.filename_len == 0) { ++ if (entry.filename_len == 0 || entry.filename_len > totalsize) { + if (error) { + spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname); + } +@@ -585,7 +655,7 @@ bail: + + size = (size+511)&~511; + +- if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { ++ if (phar_tar_type_has_data(hdr->typeflag) && size > 0) { + next: + /* this is not good enough - seek succeeds even on truncated tars */ + php_stream_seek(fp, size, SEEK_CUR); +diff --git a/ext/phar/tests/GHSA-jqcx-ccgc-xwhv.phpt b/ext/phar/tests/GHSA-jqcx-ccgc-xwhv.phpt +new file mode 100644 +index 0000000..4e12f05 +--- /dev/null ++++ b/ext/phar/tests/GHSA-jqcx-ccgc-xwhv.phpt +@@ -0,0 +1,27 @@ ++--TEST-- ++GHSA-jqcx-ccgc-xwhv (Buffer overflow and overread in phar_dir_read()) ++--SKIPIF-- ++ ++--INI-- ++phar.readonly=0 ++--FILE-- ++startBuffering(); ++$phar->addFromString(str_repeat('A', PHP_MAXPATHLEN - 1), 'This is the content of file 1.'); ++$phar->addFromString(str_repeat('B', PHP_MAXPATHLEN - 1).'C', 'This is the content of file 2.'); ++$phar->stopBuffering(); ++ ++$handle = opendir('phar://' . __DIR__ . '/GHSA-jqcx-ccgc-xwhv.phar'); ++var_dump(strlen(readdir($handle))); ++// Must not be a string of length PHP_MAXPATHLEN+1 ++var_dump(readdir($handle)); ++closedir($handle); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++int(%d) ++bool(false) +diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt +new file mode 100644 +index 0000000..b0e1f26 +--- /dev/null ++++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt +@@ -0,0 +1,50 @@ ++--TEST-- ++GHSA-j3wh-g957-2m85 (././@LongLink name longer than the archive) ++--SKIPIF-- ++ ++--INI-- ++phar.require_hash=0 ++--FILE-- ++= 148 && $i < 156) ? 0x20 : ord($header[$i]); ++ } ++ ++ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8); ++} ++ ++$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.tar'; ++ ++/* 2 GB of file name announced by a 2 KB archive */ ++$tar = tar_header('././@LongLink', "20000000000\0", 'L'); ++$tar .= str_pad('long.txt', 512, "\0"); ++$tar .= tar_header('short.txt', sprintf("%011o\0", 3)) . str_pad('abc', 512, "\0"); ++$tar .= str_repeat("\0", 1024); ++file_put_contents($fname, $tar); ++ ++try { ++ new PharData($fname); ++} catch (UnexpectedValueException $e) { ++ echo $e->getMessage(), "\n"; ++} ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++phar error: "%s" is a corrupted tar file (invalid entry size) +diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt +new file mode 100644 +index 0000000..4dd5eca +--- /dev/null ++++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt +@@ -0,0 +1,92 @@ ++--TEST-- ++GHSA-j3wh-g957-2m85 (tar entry injection via invalid entry size) ++--SKIPIF-- ++ ++--INI-- ++phar.require_hash=0 ++--FILE-- ++= 148 && $i < 156) ? 0x20 : ord($header[$i]); ++ } ++ ++ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8); ++} ++ ++function tar_dump(string $fname): void ++{ ++ try { ++ $phar = new PharData($fname); ++ $names = []; ++ foreach (new RecursiveIteratorIterator($phar) as $file) { ++ $names[] = $file->getFilename(); ++ } ++ sort($names); ++ echo implode(', ', $names), "\n"; ++ } catch (UnexpectedValueException $e) { ++ echo $e->getMessage(), "\n"; ++ } ++} ++ ++$base = __DIR__ . '/' . basename(__FILE__, '.php'); ++ ++/* the entry after the carrier is never reached by a conforming tar reader */ ++$sizes = [ ++ 'octal overflow to 0' => "40000000000\0", ++ 'octal overflow to 1' => "40000000001\0", ++ 'octal padding overflow' => "37777777400\0", ++ 'GNU base-256' => "\x80" . str_repeat("\0", 9) . "\x02\x00", ++ 'non-octal digits' => "99999999999\0", ++ 'trailing garbage' => "0000000001XX", ++]; ++ ++$i = 0; ++foreach ($sizes as $label => $size) { ++ $fname = $base . '.' . $i++ . '.tar'; ++ $tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0"); ++ $tar .= tar_header('carrier.bin', $size); ++ $tar .= tar_header('injected.txt', sprintf("%011o\0", 8)) . str_pad('INJECTED', 512, "\0"); ++ $tar .= str_repeat("\0", 1024); ++ file_put_contents($fname, $tar); ++ ++ echo $label, ': '; ++ tar_dump($fname); ++} ++ ++$fname = $base . '.valid.tar'; ++$tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0"); ++$tar .= tar_header('second.txt', sprintf("%011o\0", 8)) . str_pad('SECOND__', 512, "\0"); ++$tar .= str_repeat("\0", 1024); ++file_put_contents($fname, $tar); ++ ++echo 'valid archive: '; ++tar_dump($fname); ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++octal overflow to 0: phar error: "%s" is a corrupted tar file (invalid entry size) ++octal overflow to 1: phar error: "%s" is a corrupted tar file (invalid entry size) ++octal padding overflow: phar error: "%s" is a corrupted tar file (invalid entry size) ++GNU base-256: phar error: "%s" is a corrupted tar file (invalid entry size) ++non-octal digits: phar error: "%s" is a corrupted tar file (invalid entry size) ++trailing garbage: phar error: "%s" is a corrupted tar file (invalid entry size) ++valid archive: normal.txt, second.txt +diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt +new file mode 100644 +index 0000000..16a2d46 +--- /dev/null ++++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt +@@ -0,0 +1,79 @@ ++--TEST-- ++GHSA-j3wh-g957-2m85 (tar entry injection via entry types that carry data) ++--SKIPIF-- ++ ++--INI-- ++phar.require_hash=0 ++--FILE-- ++= 148 && $i < 156) ? 0x20 : ord($header[$i]); ++ } ++ ++ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8); ++} ++ ++$base = __DIR__ . '/' . basename(__FILE__, '.php'); ++ ++/* '5' and the other types below carry no data in any tar reader, so the ++ * injected header stays visible to all of them and is not hidden from ++ * anything that inspects the archive with a different implementation. ++ * 'K' is a GNU metadata record that is not supported and is refused. */ ++$typeflags = [ ++ 'contiguous file' => '7', ++ 'unknown type' => 'Z', ++ 'GNU long link' => 'K', ++ 'directory' => '5', ++ 'fifo' => '6', ++]; ++ ++$i = 0; ++foreach ($typeflags as $label => $typeflag) { ++ $fname = $base . '.' . $i++ . '.tar'; ++ $tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0"); ++ $tar .= tar_header('carrier.bin', sprintf("%011o\0", 512), $typeflag); ++ /* the carrier's only data block is a tar header a conforming reader skips */ ++ $tar .= tar_header('injected.txt', sprintf("%011o\0", 0)); ++ $tar .= str_repeat("\0", 1024); ++ file_put_contents($fname, $tar); ++ ++ echo $label, ': '; ++ try { ++ $phar = new PharData($fname); ++ $names = []; ++ foreach (new RecursiveIteratorIterator($phar) as $file) { ++ $names[] = $file->getFilename(); ++ } ++ sort($names); ++ echo implode(', ', $names), "\n"; ++ } catch (UnexpectedValueException $e) { ++ echo $e->getMessage(), "\n"; ++ } ++} ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++contiguous file: carrier.bin, normal.txt ++unknown type: carrier.bin, normal.txt ++GNU long link: phar error: "%s" is a tar file with an unsupported GNU long link entry ++directory: injected.txt, normal.txt ++fifo: carrier.bin, injected.txt, normal.txt +diff --git a/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt b/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt +new file mode 100644 +index 0000000..5d397b5 +--- /dev/null ++++ b/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt +@@ -0,0 +1,27 @@ ++--TEST-- ++GHSA-vc5h-9ppw-p5f3 (circular symlinks in tar should not cause stack overflow) ++--CREDITS-- ++Calvin Young - eWalker Consulting (HK) Limited ++Enoch Chow - Isomorph Cyber ++--SKIPIF-- ++ ++--FILE-- ++getContent() === ''); ++ ++// rho-shaped cycle (tail leading into a loop) ++$phar = new PharData($base . '/files/circular_symlinks_rho.tar'); ++var_dump($phar['file_a']->getContent() === ''); ++ ++// long cycle (400 entries) ++$phar = new PharData($base . '/files/circular_symlinks_long.tar'); ++var_dump($phar['link_0']->getContent() === ''); ++?> ++--EXPECT-- ++bool(true) ++bool(true) ++bool(true) +diff --git a/ext/phar/util.c b/ext/phar/util.c +index 354f0db..639f091 100644 +--- a/ext/phar/util.c ++++ b/ext/phar/util.c +@@ -57,30 +57,59 @@ static char *phar_get_link_location(phar_entry_info *entry) /* {{{ */ + } + /* }}} */ + +-phar_entry_info *phar_get_link_source(phar_entry_info *entry) /* {{{ */ ++static phar_entry_info *phar_follow_one_link(phar_entry_info *entry) + { + phar_entry_info *link_entry; + char *link; + +- if (!entry->link) { +- return entry; +- } +- + link = phar_get_link_location(entry); + if (NULL != (link_entry = zend_hash_str_find_ptr(&(entry->phar->manifest), entry->link, strlen(entry->link))) || + NULL != (link_entry = zend_hash_str_find_ptr(&(entry->phar->manifest), link, strlen(link)))) { + if (link != entry->link) { + efree(link); + } +- return phar_get_link_source(link_entry); +- } else { +- if (link != entry->link) { +- efree(link); ++ return link_entry; ++ } ++ ++ if (link != entry->link) { ++ efree(link); ++ } ++ return NULL; ++} ++ ++phar_entry_info *phar_get_link_source(phar_entry_info *entry) ++{ ++ phar_entry_info *slow, *fast; ++ ++ if (!entry->link) { ++ return entry; ++ } ++ ++ /* ++ * Use Floyd's cycle detection algorithm to follow the symlink chain without unbounded ++ * recursion. Each entry has at most one outgoing link, so if a cycle exists the fast pointer ++ * will eventually meet the slow one. Otherwise the fast pointer reaches the end first. ++ */ ++ slow = fast = entry; ++ while (1) { ++ fast = phar_follow_one_link(fast); ++ if (!fast || !fast->link) { ++ return fast; ++ } ++ fast = phar_follow_one_link(fast); ++ if (!fast || !fast->link) { ++ return fast; ++ } ++ ++ /* no need to check slow as it's always behind */ ++ slow = phar_follow_one_link(slow); ++ ++ if (slow == fast) { ++ /* circular symlink chain */ ++ return NULL; + } +- return NULL; + } + } +-/* }}} */ + + /* retrieve a phar_entry_info's current file pointer for reading contents */ + php_stream *phar_get_efp(phar_entry_info *entry, int follow_links) /* {{{ */ +diff --git a/ext/simplexml/simplexml.c b/ext/simplexml/simplexml.c +index 2cdff0e..101a9d8 100644 +--- a/ext/simplexml/simplexml.c ++++ b/ext/simplexml/simplexml.c +@@ -2194,7 +2194,9 @@ PHP_FUNCTION(simplexml_load_file) + RETURN_FALSE; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(read_file); + docp = xmlReadFile(filename, NULL, (int)options); ++ PHP_LIBXML_RESTORE_GLOBALS(read_file); + + if (!docp) { + RETURN_FALSE; +@@ -2248,7 +2250,9 @@ PHP_FUNCTION(simplexml_load_string) + RETURN_FALSE; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(read_memory); + docp = xmlReadMemory(data, (int)data_len, NULL, NULL, (int)options); ++ PHP_LIBXML_RESTORE_GLOBALS(read_memory); + + if (!docp) { + RETURN_FALSE; +@@ -2298,7 +2302,9 @@ SXE_METHOD(__construct) + return; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(read_file_or_memory); + docp = is_url ? xmlReadFile(data, NULL, (int)options) : xmlReadMemory(data, (int)data_len, NULL, NULL, (int)options); ++ PHP_LIBXML_RESTORE_GLOBALS(read_file_or_memory); + + if (!docp) { + ((php_libxml_node_object *)sxe)->document = NULL; +diff --git a/ext/simplexml/tests/libxml_global_state_entity_loader_bypass.phpt b/ext/simplexml/tests/libxml_global_state_entity_loader_bypass.phpt +new file mode 100644 +index 0000000..54f9d49 +--- /dev/null ++++ b/ext/simplexml/tests/libxml_global_state_entity_loader_bypass.phpt +@@ -0,0 +1,37 @@ ++--TEST-- ++GHSA-3qrf-m4j2-pcrr (libxml global state entity loader bypass) ++--SKIPIF-- ++ ++--FILE-- ++ %bork;]>"; ++ ++libxml_use_internal_errors(true); ++zend_test_override_libxml_global_state(); ++ ++echo "--- String test ---\n"; ++simplexml_load_string($xml); ++echo "--- Constructor test ---\n"; ++new SimpleXMLElement($xml); ++echo "--- File test ---\n"; ++file_put_contents("libxml_global_state_entity_loader_bypass.tmp", $xml); ++simplexml_load_file("libxml_global_state_entity_loader_bypass.tmp"); ++ ++echo "Done\n"; ++ ++?> ++--CLEAN-- ++ ++--EXPECT-- ++--- String test --- ++--- Constructor test --- ++--- File test --- ++Done +diff --git a/ext/soap/php_encoding.c b/ext/soap/php_encoding.c +index e0cf63d..75fa1f4 100644 +--- a/ext/soap/php_encoding.c ++++ b/ext/soap/php_encoding.c +@@ -367,6 +367,7 @@ static zend_bool soap_check_xml_ref(zval *data, xmlNodePtr node) + static void soap_add_xml_ref(zval *data, xmlNodePtr node) + { + if (SOAP_GLOBAL(ref_map)) { ++ Z_TRY_ADDREF_P(data); + zend_hash_index_update(SOAP_GLOBAL(ref_map), (zend_ulong)node, data); + } + } +@@ -557,7 +558,12 @@ static zval *master_to_zval_int(zval *ret, encodePtr encode, xmlNodePtr data) + } + } + if (encode->to_zval) { ++ if (SOAP_GLOBAL(decode_depth) >= SOAP_MAX_DECODE_DEPTH) { ++ soap_error0(E_ERROR, "Encoding: Nesting level too deep"); ++ } ++ SOAP_GLOBAL(decode_depth)++; + ret = encode->to_zval(ret, &encode->details, data); ++ SOAP_GLOBAL(decode_depth)--; + } + return ret; + } +@@ -2705,7 +2711,7 @@ static zval *to_zval_map(zval *ret, encodeTypePtr type, xmlNodePtr data) + } + + xmlValue = get_node(item->children, "value"); +- if (!xmlKey) { ++ if (!xmlValue) { + soap_error0(E_ERROR, "Encoding: Can't decode apache map, missing value"); + } + +@@ -3423,18 +3429,20 @@ void encode_reset_ns() + { + SOAP_GLOBAL(cur_uniq_ns) = 0; + SOAP_GLOBAL(cur_uniq_ref) = 0; ++ SOAP_GLOBAL(decode_depth) = 0; + if (SOAP_GLOBAL(ref_map)) { + zend_hash_destroy(SOAP_GLOBAL(ref_map)); + } else { + SOAP_GLOBAL(ref_map) = emalloc(sizeof(HashTable)); + } +- zend_hash_init(SOAP_GLOBAL(ref_map), 0, NULL, NULL, 0); ++ zend_hash_init(SOAP_GLOBAL(ref_map), 0, NULL, ZVAL_PTR_DTOR, 0); + } + + void encode_finish() + { + SOAP_GLOBAL(cur_uniq_ns) = 0; + SOAP_GLOBAL(cur_uniq_ref) = 0; ++ SOAP_GLOBAL(decode_depth) = 0; + if (SOAP_GLOBAL(ref_map)) { + zend_hash_destroy(SOAP_GLOBAL(ref_map)); + efree(SOAP_GLOBAL(ref_map)); +diff --git a/ext/soap/php_http.c b/ext/soap/php_http.c +index ee3dcbd..25d9972 100644 +--- a/ext/soap/php_http.c ++++ b/ext/soap/php_http.c +@@ -22,6 +22,7 @@ + #include "ext/standard/base64.h" + #include "ext/standard/md5.h" + #include "ext/standard/php_random.h" ++#include "ext/hash/php_hash.h" + + static char *get_http_header_value_nodup(char *headers, char *type, size_t *len); + static char *get_http_header_value(char *headers, char *type); +@@ -666,18 +667,23 @@ try_again: + if ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) != NULL) { + if (Z_TYPE_P(digest) == IS_ARRAY) { + char HA1[33], HA2[33], response[33], cnonce[33], nc[9]; +- zend_long nonce; ++ unsigned char nonce[16]; + PHP_MD5_CTX md5ctx; + unsigned char hash[16]; + +- php_random_bytes_throw(&nonce, sizeof(nonce)); +- nonce &= 0x7fffffff; ++ if (UNEXPECTED(php_random_bytes_throw(&nonce, sizeof(nonce)) != SUCCESS)) { ++ ZEND_ASSERT(EG(exception)); ++ php_stream_close(stream); ++ zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1); ++ zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1); ++ zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1); ++ smart_str_free(&soap_headers_z); ++ smart_str_free(&soap_headers); ++ return FALSE; ++ } + +- PHP_MD5Init(&md5ctx); +- snprintf(cnonce, sizeof(cnonce), ZEND_LONG_FMT, nonce); +- PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce)); +- PHP_MD5Final(hash, &md5ctx); +- make_digest(cnonce, hash); ++ php_hash_bin2hex(cnonce, nonce, sizeof(nonce)); ++ cnonce[32] = 0; + + if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nc", sizeof("nc")-1)) != NULL && + Z_TYPE_P(tmp) == IS_LONG) { +@@ -1130,7 +1136,7 @@ try_again: + char *t = ZSTR_VAL(phpurl->path); + char *p = strrchr(t, '/'); + if (p) { +- zend_string *s = zend_string_alloc((p - t) + ZSTR_LEN(new_url->path) + 2, 0); ++ zend_string *s = zend_string_safe_alloc(1, p - t, ZSTR_LEN(new_url->path) + 2, 0); + strncpy(ZSTR_VAL(s), t, (p - t) + 1); + ZSTR_VAL(s)[(p - t) + 1] = 0; + strcat(ZSTR_VAL(s), ZSTR_VAL(new_url->path)); +@@ -1423,7 +1429,8 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) + { + zend_string *http_buf = NULL; + char *header; +- int header_close = close, header_chunked = 0, header_length = 0, http_buf_size = 0; ++ int header_close = close, header_chunked = 0, header_length = 0; ++ size_t http_buf_size = 0; + + if (!close) { + header = get_http_header_value(headers, "Connection: "); +@@ -1453,14 +1460,14 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) + done = FALSE; + + while (!done) { +- int buf_size = 0; ++ unsigned int buf_size = 0; + + php_stream_gets(stream, headerbuf, sizeof(headerbuf)); + if (sscanf(headerbuf, "%x", &buf_size) > 0 ) { + if (buf_size > 0) { + size_t len_size = 0; + +- if (http_buf_size + buf_size + 1 < 0) { ++ if (buf_size >= ZSTR_MAX_LEN - http_buf_size) { + if (http_buf) { + zend_string_release_ex(http_buf, 0); + } +@@ -1468,7 +1475,7 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) + } + + if (http_buf) { +- http_buf = zend_string_realloc(http_buf, http_buf_size + buf_size, 0); ++ http_buf = zend_string_safe_realloc(http_buf, 1, http_buf_size, buf_size, 0); + } else { + http_buf = zend_string_alloc(buf_size, 0); + } +@@ -1527,7 +1534,7 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) + } + + } else if (header_length) { +- if (header_length < 0 || header_length >= INT_MAX) { ++ if (header_length < 0 || header_length >= ZSTR_MAX_LEN) { + return NULL; + } + http_buf = zend_string_alloc(header_length, 0); +@@ -1542,6 +1549,10 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) + do { + ssize_t len_read; + if (http_buf) { ++ if (UNEXPECTED(http_buf_size >= ZSTR_MAX_LEN - 4096)) { ++ zend_string_efree(http_buf); ++ return NULL; ++ } + http_buf = zend_string_realloc(http_buf, http_buf_size + 4096, 0); + } else { + http_buf = zend_string_alloc(4096, 0); +diff --git a/ext/soap/php_soap.h b/ext/soap/php_soap.h +index 8e8adb8..052c94b 100644 +--- a/ext/soap/php_soap.h ++++ b/ext/soap/php_soap.h +@@ -152,6 +152,8 @@ struct _soapService { + #define SOAP_SSL_METHOD_SSLv3 2 + #define SOAP_SSL_METHOD_SSLv23 3 + ++#define SOAP_MAX_XML_DEPTH 2048 ++#define SOAP_MAX_DECODE_DEPTH (SOAP_MAX_XML_DEPTH * 2) + + ZEND_BEGIN_MODULE_GLOBALS(soap) + HashTable defEncNs; /* mapping of default namespaces to prefixes */ +@@ -177,6 +179,7 @@ ZEND_BEGIN_MODULE_GLOBALS(soap) + HashTable wsdl_cache; + int cur_uniq_ref; + HashTable *ref_map; ++ unsigned int decode_depth; + ZEND_END_MODULE_GLOBALS(soap) + + #ifdef ZTS +diff --git a/ext/soap/php_xml.c b/ext/soap/php_xml.c +index 18a2661..8542bd0 100644 +--- a/ext/soap/php_xml.c ++++ b/ext/soap/php_xml.c +@@ -37,36 +37,72 @@ static int is_blank(const xmlChar* str) + return 1; + } + +-/* removes all empty text, comments and other insignoficant nodes */ ++/* removes all empty text, comments and other insignoficant nodes. ++ * Iterative because recursion overflows the stack on a deep document. */ + static void cleanup_xml_node(xmlNodePtr node) + { +- xmlNodePtr trav; +- xmlNodePtr del = NULL; ++ xmlNodePtr parent = node; ++ xmlNodePtr trav = node->children; + +- trav = node->children; + while (trav != NULL) { +- if (del != NULL) { +- xmlUnlinkNode(del); +- xmlFreeNode(del); +- del = NULL; +- } ++ xmlNodePtr next = trav->next; ++ + if (trav->type == XML_TEXT_NODE) { + if (is_blank(trav->content)) { +- del = trav; ++ xmlUnlinkNode(trav); ++ xmlFreeNode(trav); + } + } else if ((trav->type != XML_ELEMENT_NODE) && + (trav->type != XML_CDATA_SECTION_NODE)) { +- del = trav; ++ xmlUnlinkNode(trav); ++ xmlFreeNode(trav); + } else if (trav->children != NULL) { +- cleanup_xml_node(trav); ++ parent = trav; ++ trav = trav->children; ++ continue; + } +- trav = trav->next; ++ ++ while (next == NULL) { ++ if (parent == node) { ++ return; ++ } ++ next = parent->next; ++ parent = parent->parent; ++ } ++ trav = next; + } +- if (del != NULL) { +- xmlUnlinkNode(del); +- xmlFreeNode(del); ++} ++ ++#if LIBXML_VERSION < 21300 ++static int is_nesting_too_deep(xmlNodePtr node) ++{ ++ xmlNodePtr trav = node->children; ++ unsigned int depth = 0; ++ ++ while (trav != NULL) { ++ /* An entity reference borrows its declaration as child list, and that ++ * declaration hangs off the DTD, so descending leaves the document. */ ++ if (trav->children != NULL && ++ trav->type != XML_ENTITY_REF_NODE && ++ trav->type != XML_DTD_NODE) { ++ if (++depth > SOAP_MAX_XML_DEPTH) { ++ return TRUE; ++ } ++ trav = trav->children; ++ continue; ++ } ++ while (trav->next == NULL) { ++ trav = trav->parent; ++ if (trav == node) { ++ return FALSE; ++ } ++ depth--; ++ } ++ trav = trav->next; + } ++ return FALSE; + } ++#endif + + static void soap_ignorableWhitespace(void *ctx, const xmlChar *ch, int len) + { +@@ -93,6 +129,7 @@ xmlDocPtr soap_xmlParseFile(const char *filename) + if (ctxt) { + zend_bool old; + ++ php_libxml_sanitize_parse_ctxt_options(ctxt); + ctxt->keepBlanks = 0; + ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; + ctxt->sax->comment = soap_Comment; +@@ -123,6 +160,15 @@ xmlDocPtr soap_xmlParseFile(const char *filename) + */ + + if (ret) { ++#if LIBXML_VERSION < 21300 ++ if (is_nesting_too_deep((xmlNodePtr)ret)) { ++ /* php_sdl.c reports xmlGetLastError() as the reason, and libxml2 did ++ * not fail here, so drop the error an earlier parse left behind. */ ++ xmlResetLastError(); ++ xmlFreeDoc(ret); ++ return NULL; ++ } ++#endif + cleanup_xml_node((xmlNodePtr)ret); + } + return ret; +@@ -141,6 +187,7 @@ xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) + if (ctxt) { + zend_bool old; + ++ php_libxml_sanitize_parse_ctxt_options(ctxt); + ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; + ctxt->sax->comment = soap_Comment; + ctxt->sax->warning = NULL; +@@ -169,6 +216,13 @@ xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) + xmlCleanupParser(); + */ + ++#if LIBXML_VERSION < 21300 ++ if (ret && is_nesting_too_deep((xmlNodePtr)ret)) { ++ xmlFreeDoc(ret); ++ ret = NULL; ++ } ++#endif ++ + /* + if (ret) { + cleanup_xml_node((xmlNodePtr)ret); +@@ -291,6 +345,8 @@ xmlNodePtr get_node_with_attribute_ex(xmlNodePtr node, char *name, char *name_ns + + xmlNodePtr get_node_with_attribute_recursive_ex(xmlNodePtr node, char *name, char *name_ns, char *attribute, char *value, char *attr_ns) + { ++ unsigned int depth = 0; ++ + while (node != NULL) { + if (node_is_equal_ex(node, name, name_ns)) { + xmlAttrPtr attr = get_attribute_ex(node->properties, attribute, attr_ns); +@@ -298,11 +354,19 @@ xmlNodePtr get_node_with_attribute_recursive_ex(xmlNodePtr node, char *name, cha + return node; + } + } +- if (node->children != NULL) { +- xmlNodePtr tmp = get_node_with_attribute_recursive_ex(node->children, name, name_ns, attribute, value, attr_ns); +- if (tmp) { +- return tmp; ++ if (node->children != NULL && ++ node->type != XML_ENTITY_REF_NODE && ++ node->type != XML_DTD_NODE) { ++ node = node->children; ++ depth++; ++ continue; ++ } ++ while (node->next == NULL) { ++ if (depth == 0) { ++ return NULL; + } ++ node = node->parent; ++ depth--; + } + node = node->next; + } +diff --git a/ext/soap/soap.c b/ext/soap/soap.c +index 7429aeb..ec75d74 100644 +--- a/ext/soap/soap.c ++++ b/ext/soap/soap.c +@@ -579,6 +579,7 @@ static void php_soap_init_globals(zend_soap_globals *soap_globals) + soap_globals->soap_version = SOAP_1_1; + soap_globals->mem_cache = NULL; + soap_globals->ref_map = NULL; ++ soap_globals->decode_depth = 0; + } + + PHP_MSHUTDOWN_FUNCTION(soap) +@@ -1807,13 +1808,21 @@ PHP_METHOD(SoapServer, handle) + php_output_discard(); + soap_server_fault_ex(function, &h->retval, h); + efree(fn_name); +- if (service->type == SOAP_CLASS && soap_obj) {zval_ptr_dtor(soap_obj);} ++ if (service->type == SOAP_CLASS && soap_obj) { ++ if (service->soap_class.persistence != SOAP_PERSISTENCE_SESSION) { ++ zval_ptr_dtor(soap_obj); ++ } ++ } + goto fail; + } else if (EG(exception)) { + php_output_discard(); + _soap_server_exception(service, function, ZEND_THIS); + efree(fn_name); +- if (service->type == SOAP_CLASS && soap_obj) {zval_ptr_dtor(soap_obj);} ++ if (service->type == SOAP_CLASS && soap_obj) { ++ if (service->soap_class.persistence != SOAP_PERSISTENCE_SESSION) { ++ zval_ptr_dtor(soap_obj); ++ } ++ } + goto fail; + } + } else if (h->mustUnderstand) { +@@ -4457,8 +4466,10 @@ static xmlNodePtr serialize_zval(zval *val, sdlParamPtr param, char *paramName, + } + xmlParam = master_to_xml(enc, val, style, parent); + zval_ptr_dtor(&defval); +- if (!strcmp((char*)xmlParam->name, "BOGUS")) { +- xmlNodeSetName(xmlParam, BAD_CAST(paramName)); ++ if (xmlParam != NULL) { ++ if (xmlParam->name == NULL || strcmp((char*)xmlParam->name, "BOGUS") == 0) { ++ xmlNodeSetName(xmlParam, BAD_CAST(paramName)); ++ } + } + return xmlParam; + } +diff --git a/ext/soap/tests/GHSA-85c2-q967-79q5.phpt b/ext/soap/tests/GHSA-85c2-q967-79q5.phpt +new file mode 100644 +index 0000000..8bcac26 +--- /dev/null ++++ b/ext/soap/tests/GHSA-85c2-q967-79q5.phpt +@@ -0,0 +1,61 @@ ++--TEST-- ++GHSA-85c2-q967-79q5: Stale SOAP_GLOBAL(ref_map) pointer with Apache Map ++--CREDITS-- ++brettgervasoni ++--EXTENSIONS-- ++soap ++--FILE-- ++ ++ ++ ++ ++ ++ ++ ++ foo ++ bar ++ ++ ++ foo ++ baz ++ ++ ++ ++ ++ ++ ++XML; ++ ++$s = new SoapServer(null, ['uri' => 'urn:a']); ++$s->setClass(Handler::class); ++$s->handle($envelope); ++var_dump($result); ++ ++?> ++--EXPECTF-- ++ ++ ++array(2) { ++ [0]=> ++ array(1) { ++ ["foo"]=> ++ string(3) "baz" ++ } ++ [1]=> ++ object(stdClass)#%d (1) { ++ ["object"]=> ++ string(3) "bar" ++ } ++} +diff --git a/ext/soap/tests/GHSA-hmxp-6pc4-f3vv.phpt b/ext/soap/tests/GHSA-hmxp-6pc4-f3vv.phpt +new file mode 100644 +index 0000000..e46ab2e +--- /dev/null ++++ b/ext/soap/tests/GHSA-hmxp-6pc4-f3vv.phpt +@@ -0,0 +1,39 @@ ++--TEST-- ++GHSA-hmxp-6pc4-f3vv: Null pointer dereference on missing Apache map value ++--CREDITS-- ++Ilia Alshanetsky (iliaal) ++--EXTENSIONS-- ++soap ++--FILE-- ++ ++ ++ ++ ++ ++ ++ hello ++ ++ ++ ++ ++XML; ++ ++$server = new SoapServer(null, [ ++ 'uri' => 'urn:test', ++ 'typemap' => [['type_name' => 'anything']], ++]); ++$server->addFunction('test'); ++function test($m) { return null; } ++$server->handle($request); ++ ++?> ++--EXPECT-- ++ ++SOAP-ENV:ServerSOAP-ERROR: Encoding: Can't decode apache map, missing value +diff --git a/ext/soap/tests/GHSA-m33r-qmcv-p97q.phpt b/ext/soap/tests/GHSA-m33r-qmcv-p97q.phpt +new file mode 100644 +index 0000000..bcf441c +--- /dev/null ++++ b/ext/soap/tests/GHSA-m33r-qmcv-p97q.phpt +@@ -0,0 +1,58 @@ ++--TEST-- ++GHSA-m33r-qmcv-p97q: Use-after-free after header parsing failure with SOAP_PERSISTENCE_SESSION ++--CREDITS-- ++Ilia Alshanetsky (iliaal) ++--EXTENSIONS-- ++soap ++session ++--FILE-- ++ 'urn:a']); ++$srv->setClass(Handler::class); ++$srv->setPersistence(SOAP_PERSISTENCE_SESSION); ++ ++$srv->handle(<< ++ ++ ++ ++ ++ ++ ++ ++ ++XML); ++ ++$srv->handle(<< ++ ++ ++ ++ ++ ++ ++ ++ ++XML); ++ ++?> ++--EXPECT-- ++ ++SOAP-ENV:Serverdenied ++ ++SOAP-ENV:Serverdenied +diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt +new file mode 100644 +index 0000000..e07f78d +--- /dev/null ++++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt +@@ -0,0 +1,47 @@ ++--TEST-- ++GHSA-rgrp-mwpx-f6rm: Stack overflow on a chain of href references ++--EXTENSIONS-- ++soap ++--FILE-- ++' . ($i < $n ? '' : 'leaf') . ''; ++ } ++ ++ return '

' ++ . $links . ''; ++} ++ ++function test($arg) ++{ ++ $GLOBALS['decoded'] = $arg; ++ ++ return 'ok'; ++} ++ ++$server = new SoapServer(null, ['uri' => 'urn:test']); ++$server->addFunction('test'); ++ ++$server->handle(chain(3)); ++var_dump($GLOBALS['decoded']); ++ ++$server->handle(chain(12000)); ++ ++?> ++--EXPECTF-- ++ ++ok ++object(stdClass)#%d (1) { ++ ["q"]=> ++ object(stdClass)#%d (1) { ++ ["q"]=> ++ string(4) "leaf" ++ } ++} ++ ++SOAP-ENV:ServerSOAP-ERROR: Encoding: Nesting level too deep +diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt +new file mode 100644 +index 0000000..5058ba1 +--- /dev/null ++++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt +@@ -0,0 +1,43 @@ ++--TEST-- ++GHSA-rgrp-mwpx-f6rm: Stack overflow on an array element referencing its own array ++--EXTENSIONS-- ++soap ++--FILE-- ++' ++ . '' . $param . ''; ++} ++ ++function test($arg) ++{ ++ $GLOBALS['decoded'] = $arg; ++ ++ return 'ok'; ++} ++ ++$server = new SoapServer(null, ['uri' => 'urn:test']); ++$server->addFunction('test'); ++ ++$server->handle(envelope('ab')); ++var_dump($GLOBALS['decoded']); ++ ++$server->handle(envelope('')); ++ ++?> ++--EXPECTF-- ++ ++ok ++array(2) { ++ [0]=> ++ string(1) "a" ++ [1]=> ++ string(1) "b" ++} ++ ++SOAP-ENV:ServerSOAP-ERROR: Encoding: Nesting level too deep +diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt +new file mode 100644 +index 0000000..f321396 +--- /dev/null ++++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt +@@ -0,0 +1,89 @@ ++--TEST-- ++GHSA-rgrp-mwpx-f6rm: Stack overflow on deeply nested XML ++--EXTENSIONS-- ++soap ++--INI-- ++soap.wsdl_cache_enabled=0 ++--FILE-- ++' ++ . str_repeat('', $depth) . 'leaf' . str_repeat('', $depth) ++ . ''; ++} ++ ++function test($arg) ++{ ++ $depth = 0; ++ while (is_object($arg)) { ++ $depth++; ++ $arg = $arg->a; ++ } ++ $GLOBALS['decoded'] = [$depth, $arg]; ++ ++ return 'ok'; ++} ++ ++$server = new SoapServer(null, ['uri' => 'urn:test']); ++$server->addFunction('test'); ++ ++$server->handle(envelope(200)); ++var_dump($GLOBALS['decoded']); ++ ++/* libxml2 2.13 rejects past 2048 despite XML_PARSE_HUGE, older ones do not. */ ++$wsdl = __DIR__ . '/GHSA-rgrp-mwpx-f6rm.wsdl'; ++foreach ([1000, 2100] as $depth) { ++ file_put_contents($wsdl, '' . str_repeat('', $depth) . 'leaf' . str_repeat('', $depth) . ''); ++ try { ++ new SoapClient($wsdl); ++ } catch (SoapFault $e) { ++ echo rtrim($e->getMessage()), "\n"; ++ } ++} ++ ++/* A WSDL reached through an entity reference still loads. Its replacement tree cannot ++ be built deeper than the 2048 libxml2 2.13 enforces, so this pins the entity skip ++ rather than the limit. */ ++$entity = __DIR__ . '/GHSA-rgrp-mwpx-f6rm-entity.wsdl'; ++$desc = str_repeat('<p>', 300) . 'A test service.' . str_repeat('</p>', 300); ++file_put_contents($entity, ' ++]> ++ ++ &desc; ++ ++ ++ ++ ++ ++ ++ ++'); ++var_dump((new SoapClient($entity))->__getFunctions()); ++ ++$server->handle(envelope(3000)); ++ ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++ ++ok ++array(2) { ++ [0]=> ++ int(199) ++ [1]=> ++ string(4) "leaf" ++} ++SOAP-ERROR: Parsing WSDL: Couldn't find in '%sGHSA-rgrp-mwpx-f6rm.wsdl' ++SOAP-ERROR: Parsing WSDL: Couldn't load from '%sGHSA-rgrp-mwpx-f6rm.wsdl'%S ++array(1) { ++ [0]=> ++ string(9) "void op()" ++} ++ ++SOAP-ENV:ClientBad Request +diff --git a/ext/soap/tests/bugs/GHSA-cj93-vc83-wgqv.phpt b/ext/soap/tests/bugs/GHSA-cj93-vc83-wgqv.phpt +new file mode 100644 +index 0000000..d97ec66 +--- /dev/null ++++ b/ext/soap/tests/bugs/GHSA-cj93-vc83-wgqv.phpt +@@ -0,0 +1,156 @@ ++--TEST-- ++GHSA-cj93-vc83-wgqv ++--INI-- ++soap.wsdl_cache_enabled=0 ++memory_limit=-1 ++--EXTENSIONS-- ++soap ++--CONFLICTS-- ++all ++--SKIPIF-- ++ 6) { ++ $enough_free_ram = true; ++ } ++ } ++ } ++} ++ ++if (empty($enough_free_ram)) { ++ die(sprintf("skip need +6G free RAM, but only %01.2f available", $free_ram)); ++} ++--FILE-- ++ $v) { ++ $chunks[$k] = sprintf("%08x\r\n%s\r\n", strlen($v), $v); ++ } ++ ++ return join('', $chunks); ++} ++ ++$wsdl = file_get_contents(__DIR__.'/../server030.wsdl'); ++ ++$headers = ++ "HTTP/1.1 200 OK\r\n". ++ "Content-Type: text/xml;charset=utf-8\r\n". ++ "Transfer-Encoding: \t chunked\t \r\n". ++ "Connection: close\r\n". ++ "\r\n"; ++ ++/* Custom minimal server. Unlike the generic http_server() helper it streams the ++ * 2 GiB filler in bounded blocks instead of materialising it (and a data:// ++ * copy of it) in memory. That keeps the sender's footprint tiny: only the ++ * client needs to hold the large buffers, so total memory and run time stay far ++ * lower and the test no longer thrashes on slower machines. */ ++function heavy_soap_server($wsdl, $headers) ++{ ++ $server = stream_socket_server('tcp://localhost:0', $errno, $errstr); ++ if (!$server) { ++ return false; ++ } ++ $uri = 'http://' . stream_socket_get_name($server, false); ++ ++ $pid = pcntl_fork(); ++ if ($pid == -1) { ++ die('could not fork'); ++ } else if ($pid) { ++ return ['pid' => $pid, 'uri' => $uri]; ++ } ++ ++ /* Child: streaming 2 GiB can exceed the 60s alarm the helper would use, so ++ * match the run-tests per-test timeout instead. */ ++ pcntl_alarm(120); ++ ++ $drain = static function ($sock) { ++ stream_set_blocking($sock, false); ++ while (!feof($sock)) { ++ $r = [$sock]; $w = $e = null; ++ if (!stream_select($r, $w, $e, 1)) continue; ++ $line = stream_get_line($sock, 8192, "\r\n"); ++ if ($line === '') break; ++ } ++ stream_set_blocking($sock, true); ++ }; ++ ++ /* Response 1: the WSDL, chunked. */ ++ $sock = stream_socket_accept($server, 60); ++ if ($sock) { ++ $drain($sock); ++ fwrite($sock, $headers . chunk_body($wsdl, 64)); ++ fclose($sock); ++ } ++ ++ /* Response 2: an oversized chunk. Only the size header of the second chunk ++ * is needed: the reallocation for it happens before its body is read, so on ++ * the unfixed code the overflow triggers on the first read into the ++ * undersized buffer. The 2 GiB first-chunk body is streamed in 8 MiB blocks ++ * rather than built as one string. */ ++ $sock = stream_socket_accept($server, 60); ++ if ($sock) { ++ $drain($sock); ++ fwrite($sock, $headers); ++ fwrite($sock, sprintf("%08x\r\n", 0x7fffffff)); ++ ++ $remaining = 0x7fffffff; ++ $block = str_repeat('x', 1 << 23); // 8 MiB ++ $block_len = strlen($block); ++ while ($remaining > 0) { ++ $n = $remaining < $block_len ? $remaining : $block_len; ++ fwrite($sock, $n === $block_len ? $block : substr($block, 0, $n)); ++ $remaining -= $n; ++ } ++ ++ fwrite($sock, "\r\n"); ++ fwrite($sock, sprintf("%08x\r\n", 0x7fffffff)); ++ fwrite($sock, "xxxx"); ++ fclose($sock); ++ } ++ ++ exit(0); ++} ++ ++['pid' => $pid, 'uri' => $uri] = heavy_soap_server($wsdl, $headers); ++ ++$options = [ ++ 'trace' => false, ++ 'location' => $uri, ++]; ++ ++$client = new SoapClient($uri, $options); ++ ++$client->getItems(); ++ ++http_server_kill($pid); ++ ++--EXPECTF-- ++Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http body, No Content-Length, connection closed or chunked data in %s:%d ++Stack trace: ++#0 [internal function]: SoapClient->__doRequest('__call('getItems', Array) ++#2 {main} ++ thrown in %s on line %d +diff --git a/ext/soap/tests/soap_qname_crash.phpt b/ext/soap/tests/soap_qname_crash.phpt +new file mode 100644 +index 0000000..7a1bf02 +--- /dev/null ++++ b/ext/soap/tests/soap_qname_crash.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++Test SoapClient with excessively large QName prefix in SoapVar ++--EXTENSIONS-- ++soap ++--SKIPIF-- ++ ++--INI-- ++memory_limit=8G ++--FILE-- ++ 'http://127.0.0.1/', ++ 'uri' => 'urn:dummy', ++ 'trace' => 1, ++ 'exceptions' => true, ++]; ++$client = new TestSoapClient(null, $options); ++$client->__soapCall("DummyFunction", [$var]); ++?> ++--EXPECT-- ++Attempting to create SoapVar with very large QName ++Attempting encoding ++ ++value +diff --git a/ext/standard/array.c b/ext/standard/array.c +index cd2e528..153a4d3 100644 +--- a/ext/standard/array.c ++++ b/ext/standard/array.c +@@ -3813,7 +3813,7 @@ static zend_always_inline void php_array_merge_wrapper(INTERNAL_FUNCTION_PARAMET + int argc, i; + zval *src_entry; + HashTable *src, *dest; +- uint32_t count = 0; ++ uint64_t count = 0; + + ZEND_PARSE_PARAMETERS_START(0, -1) + Z_PARAM_VARIADIC('+', args, argc) +@@ -3833,6 +3833,11 @@ static zend_always_inline void php_array_merge_wrapper(INTERNAL_FUNCTION_PARAMET + count += zend_hash_num_elements(Z_ARRVAL_P(arg)); + } + ++ if (UNEXPECTED(count >= HT_MAX_SIZE)) { ++ zend_throw_error(NULL, "The total number of elements must be lower than %u", HT_MAX_SIZE); ++ return; ++ } ++ + if (argc == 2) { + zval *ret = NULL; + +diff --git a/ext/standard/basic_functions.c b/ext/standard/basic_functions.c +index 64f27ef..4574633 100644 +--- a/ext/standard/basic_functions.c ++++ b/ext/standard/basic_functions.c +@@ -3960,7 +3960,7 @@ PHP_NAMED_FUNCTION(php_inet_pton) + char buffer[17]; + + ZEND_PARSE_PARAMETERS_START(1, 1) +- Z_PARAM_STRING(address, address_len) ++ Z_PARAM_PATH(address, address_len) + ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); + + memset(buffer, 0, sizeof(buffer)); +@@ -3998,7 +3998,7 @@ PHP_FUNCTION(ip2long) + #endif + + ZEND_PARSE_PARAMETERS_START(1, 1) +- Z_PARAM_STRING(addr, addr_len) ++ Z_PARAM_PATH(addr, addr_len) + ZEND_PARSE_PARAMETERS_END(); + + #ifdef HAVE_INET_PTON +@@ -5714,8 +5714,8 @@ PHP_FUNCTION(getservbyname) + struct servent *serv; + + ZEND_PARSE_PARAMETERS_START(2, 2) +- Z_PARAM_STRING(name, name_len) +- Z_PARAM_STRING(proto, proto_len) ++ Z_PARAM_PATH(name, name_len) ++ Z_PARAM_PATH(proto, proto_len) + ZEND_PARSE_PARAMETERS_END(); + + +@@ -5759,7 +5759,7 @@ PHP_FUNCTION(getservbyport) + + ZEND_PARSE_PARAMETERS_START(2, 2) + Z_PARAM_LONG(port) +- Z_PARAM_STRING(proto, proto_len) ++ Z_PARAM_PATH(proto, proto_len) + ZEND_PARSE_PARAMETERS_END(); + + serv = getservbyport(htons((unsigned short) port), proto); +@@ -5783,7 +5783,7 @@ PHP_FUNCTION(getprotobyname) + struct protoent *ent; + + ZEND_PARSE_PARAMETERS_START(1, 1) +- Z_PARAM_STRING(name, name_len) ++ Z_PARAM_PATH(name, name_len) + ZEND_PARSE_PARAMETERS_END(); + + ent = getprotobyname(name); +diff --git a/ext/standard/crypt.c b/ext/standard/crypt.c +index 92430b6..04487f3 100644 +--- a/ext/standard/crypt.c ++++ b/ext/standard/crypt.c +@@ -151,6 +151,7 @@ PHPAPI zend_string *php_crypt(const char *password, const int pass_len, const ch + } else if ( + salt[0] == '$' && + salt[1] == '2' && ++ salt[2] != 0 && + salt[3] == '$') { + char output[PHP_MAX_SALT_LEN + 1]; + +diff --git a/ext/standard/crypt_blowfish.c b/ext/standard/crypt_blowfish.c +index c1f945f..aa7e1bc 100644 +--- a/ext/standard/crypt_blowfish.c ++++ b/ext/standard/crypt_blowfish.c +@@ -376,7 +376,6 @@ static unsigned char BF_atoi64[0x60] = { + #define BF_safe_atoi64(dst, src) \ + { \ + tmp = (unsigned char)(src); \ +- if (tmp == '$') break; /* PHP hack */ \ + if ((unsigned int)(tmp -= 0x20) >= 0x60) return -1; \ + tmp = BF_atoi64[tmp]; \ + if (tmp > 63) return -1; \ +@@ -404,13 +403,6 @@ static int BF_decode(BF_word *dst, const char *src, int size) + *dptr++ = ((c3 & 0x03) << 6) | c4; + } while (dptr < end); + +- if (end - dptr == size) { +- return -1; +- } +- +- while (dptr < end) /* PHP hack */ +- *dptr++ = 0; +- + return 0; + } + +diff --git a/ext/standard/dl.c b/ext/standard/dl.c +index bef2e51..6e0aae7 100644 +--- a/ext/standard/dl.c ++++ b/ext/standard/dl.c +@@ -85,7 +85,7 @@ PHPAPI void *php_load_shlib(char *path, char **errp) + size_t i = strlen(err); + (*errp)=estrdup(err); + php_win32_error_msg_free(err); +- while (i > 0 && isspace((*errp)[i-1])) { (*errp)[i-1] = '\0'; i--; } ++ while (i > 0 && isspace((unsigned char)(*errp)[i-1])) { (*errp)[i-1] = '\0'; i--; } + } else { + (*errp) = estrdup(""); + } +diff --git a/ext/standard/dns.c b/ext/standard/dns.c +index dc85c45..698ad4f 100644 +--- a/ext/standard/dns.c ++++ b/ext/standard/dns.c +@@ -377,7 +377,7 @@ PHP_FUNCTION(dns_check_record) + #endif + + ZEND_PARSE_PARAMETERS_START(1, 2) +- Z_PARAM_STRING(hostname, hostname_len) ++ Z_PARAM_PATH(hostname, hostname_len) + Z_PARAM_OPTIONAL + Z_PARAM_STRING(rectype, rectype_len) + ZEND_PARSE_PARAMETERS_END(); +@@ -825,7 +825,7 @@ PHP_FUNCTION(dns_get_record) + zend_bool raw = 0; + + ZEND_PARSE_PARAMETERS_START(1, 5) +- Z_PARAM_STRING(hostname, hostname_len) ++ Z_PARAM_PATH(hostname, hostname_len) + Z_PARAM_OPTIONAL + Z_PARAM_LONG(type_param) + Z_PARAM_ZVAL(authns) +@@ -1065,7 +1065,7 @@ PHP_FUNCTION(dns_get_mx) + #endif + + ZEND_PARSE_PARAMETERS_START(2, 3) +- Z_PARAM_STRING(hostname, hostname_len) ++ Z_PARAM_PATH(hostname, hostname_len) + Z_PARAM_ZVAL(mx_list) + Z_PARAM_OPTIONAL + Z_PARAM_ZVAL(weight_list) +diff --git a/ext/standard/dns_win32.c b/ext/standard/dns_win32.c +index 466d927..f5b6e03 100644 +--- a/ext/standard/dns_win32.c ++++ b/ext/standard/dns_win32.c +@@ -50,7 +50,7 @@ PHP_FUNCTION(dns_get_mx) /* {{{ */ + DNS_STATUS status; /* Return value of DnsQuery_A() function */ + PDNS_RECORD pResult, pRec; /* Pointer to DNS_RECORD structure */ + +- if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) { ++ if (zend_parse_parameters(ZEND_NUM_ARGS(), "pz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) { + return; + } + +@@ -104,7 +104,7 @@ PHP_FUNCTION(dns_check_record) + DNS_STATUS status; /* Return value of DnsQuery_A() function */ + PDNS_RECORD pResult; /* Pointer to DNS_RECORD structure */ + +- if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) { ++ if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) { + return; + } + +@@ -357,7 +357,7 @@ PHP_FUNCTION(dns_get_record) + int type, type_to_fetch, first_query = 1, store_results = 1; + zend_bool raw = 0; + +- if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|lz!z!b", ++ if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|lz!z!b", + &hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) { + return; + } +diff --git a/ext/standard/file.c b/ext/standard/file.c +index 3bd3421..bf9d45d 100644 +--- a/ext/standard/file.c ++++ b/ext/standard/file.c +@@ -2118,7 +2118,7 @@ PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, int + inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0); + if (inc_len == 1) { + char *tmp = bptr; +- while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) { ++ while ((*tmp != delimiter) && isspace((unsigned char)*tmp)) { + tmp++; + } + if (*tmp == enclosure) { +diff --git a/ext/standard/filters.c b/ext/standard/filters.c +index 018270c..168e00d 100644 +--- a/ext/standard/filters.c ++++ b/ext/standard/filters.c +@@ -367,7 +367,7 @@ static php_conv_err_t php_conv_base64_encode_ctor(php_conv_base64_encode *inst, + inst->line_ccnt = line_len; + inst->line_len = line_len; + if (lbchars != NULL) { +- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars); ++ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars); + inst->lbchars_len = lbchars_len; + } else { + inst->lbchars = NULL; +@@ -976,7 +976,7 @@ static php_conv_err_t php_conv_qprint_encode_ctor(php_conv_qprint_encode *inst, + inst->line_ccnt = line_len; + inst->line_len = line_len; + if (lbchars != NULL) { +- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars); ++ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars); + inst->lbchars_len = lbchars_len; + } else { + inst->lbchars = NULL; +@@ -1090,7 +1090,7 @@ static php_conv_err_t php_conv_qprint_decode_convert(php_conv_qprint_decode *ins + goto out; + } + +- if (!isxdigit((int) *ps)) { ++ if (!isxdigit(*ps)) { + err = PHP_CONV_ERR_INVALID_SEQ; + goto out; + } +@@ -1128,6 +1128,9 @@ static php_conv_err_t php_conv_qprint_decode_convert(php_conv_qprint_decode *ins + } break; + + case 5: { ++ if (icnt == 0) { ++ goto out; ++ } + if (!inst->lbchars && lb_cnt == 1 && *ps == '\n') { + /* auto-detect soft line breaks, found network line break */ + lb_cnt = lb_ptr = 0; +@@ -1141,15 +1144,13 @@ static php_conv_err_t php_conv_qprint_decode_convert(php_conv_qprint_decode *ins + /* soft line break */ + lb_cnt = lb_ptr = 0; + scan_stat = 0; +- } else if (icnt > 0) { ++ } else { + if (*ps == (unsigned char)inst->lbchars[lb_cnt]) { + lb_cnt++; + ps++, icnt--; + } else { + scan_stat = 6; /* no break for short-cut */ + } +- } else { +- goto out; + } + } break; + +@@ -1188,7 +1189,7 @@ static php_conv_err_t php_conv_qprint_decode_ctor(php_conv_qprint_decode *inst, + inst->next_char = 0; + inst->lb_ptr = inst->lb_cnt = 0; + if (lbchars != NULL) { +- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars); ++ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars); + inst->lbchars_len = lbchars_len; + } else { + inst->lbchars = NULL; +diff --git a/ext/standard/formatted_print.c b/ext/standard/formatted_print.c +index 4ee68ad..5060627 100644 +--- a/ext/standard/formatted_print.c ++++ b/ext/standard/formatted_print.c +@@ -440,13 +440,13 @@ php_formatted_print(zval *z_format, zval *args, int argc) + + PRINTF_DEBUG(("sprintf: first looking at '%c', inpos=%d\n", + *format, format - Z_STRVAL_P(z_format))); +- if (isalpha((int)*format)) { ++ if (isalpha((unsigned char)*format)) { + width = precision = 0; + argnum = currarg++; + } else { + /* first look for argnum */ + temppos = format; +- while (isdigit((int)*temppos)) temppos++; ++ while (isdigit((unsigned char)*temppos)) temppos++; + if (*temppos == '$') { + argnum = php_sprintf_getnumber(&format, &format_len); + +@@ -489,7 +489,7 @@ php_formatted_print(zval *z_format, zval *args, int argc) + + + /* after modifiers comes width */ +- if (isdigit((int)*format)) { ++ if (isdigit((unsigned char)*format)) { + PRINTF_DEBUG(("sprintf: getting width\n")); + if ((width = php_sprintf_getnumber(&format, &format_len)) < 0) { + efree(result); +@@ -507,7 +507,7 @@ php_formatted_print(zval *z_format, zval *args, int argc) + format++; + format_len--; + PRINTF_DEBUG(("sprintf: getting precision\n")); +- if (isdigit((int)*format)) { ++ if (isdigit((unsigned char)*format)) { + if ((precision = php_sprintf_getnumber(&format, &format_len)) < 0) { + efree(result); + php_error_docref(NULL, E_WARNING, "Precision must be greater than zero and less than %d", INT_MAX); +diff --git a/ext/standard/fsock.c b/ext/standard/fsock.c +index fe8fbea..df6a74b 100644 +--- a/ext/standard/fsock.c ++++ b/ext/standard/fsock.c +@@ -25,6 +25,28 @@ + #include "php_network.h" + #include "file.h" + ++static size_t php_fsockopen_format_host_port(char **message, const char *prefix, size_t prefix_len, ++ const char *host, size_t host_len, zend_long port) ++{ ++ char portbuf[32]; ++ int portlen = snprintf(portbuf, sizeof(portbuf), ":" ZEND_LONG_FMT, port); ++ size_t total_len = prefix_len + host_len + portlen; ++ ++ char *result = emalloc(total_len + 1); ++ ++ if (prefix_len > 0) { ++ memcpy(result, prefix, prefix_len); ++ } ++ memcpy(result + prefix_len, host, host_len); ++ memcpy(result + prefix_len + host_len, portbuf, portlen); ++ ++ result[total_len] = '\0'; ++ ++ *message = result; ++ ++ return total_len; ++} ++ + /* {{{ php_fsockopen() */ + + static void php_fsockopen_stream(INTERNAL_FUNCTION_PARAMETERS, int persistent) +@@ -59,11 +81,12 @@ static void php_fsockopen_stream(INTERNAL_FUNCTION_PARAMETERS, int persistent) + ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); + + if (persistent) { +- spprintf(&hashkey, 0, "pfsockopen__%s:" ZEND_LONG_FMT, host, port); ++ php_fsockopen_format_host_port(&hashkey, "pfsockopen__", strlen("pfsockopen__"), host, ++ host_len, port); + } + + if (port > 0) { +- hostname_len = spprintf(&hostname, 0, "%s:" ZEND_LONG_FMT, host, port); ++ hostname_len = php_fsockopen_format_host_port(&hostname, "", 0, host, host_len, port); + } else { + hostname_len = host_len; + hostname = host; +diff --git a/ext/standard/ftp_fopen_wrapper.c b/ext/standard/ftp_fopen_wrapper.c +index 3a7dec4..f046772 100644 +--- a/ext/standard/ftp_fopen_wrapper.c ++++ b/ext/standard/ftp_fopen_wrapper.c +@@ -81,8 +81,8 @@ static inline int get_ftp_result(php_stream *stream, char *buffer, size_t buffer + { + buffer[0] = '\0'; /* in case read fails to read anything */ + while (php_stream_gets(stream, buffer, buffer_size-1) && +- !(isdigit((int) buffer[0]) && isdigit((int) buffer[1]) && +- isdigit((int) buffer[2]) && buffer[3] == ' ')); ++ !(isdigit((unsigned char)buffer[0]) && isdigit((unsigned char)buffer[1]) && ++ isdigit((unsigned char)buffer[2]) && buffer[3] == ' ')); + return strtol(buffer, NULL, 10); + } + /* }}} */ +@@ -234,7 +234,7 @@ static php_stream *php_ftp_fopen_connect(php_stream_wrapper *wrapper, const char + #define PHP_FTP_CNTRL_CHK(val, val_len, err_msg) { \ + unsigned char *s = (unsigned char *) val, *e = (unsigned char *) s + val_len; \ + while (s < e) { \ +- if (iscntrl(*s)) { \ ++ if (iscntrl((unsigned char)*s)) { \ + php_stream_wrapper_log_error(wrapper, options, err_msg, val); \ + goto connect_errexit; \ + } \ +@@ -346,14 +346,14 @@ static unsigned short php_fopen_do_pasv(php_stream *stream, char *ip, size_t ip_ + /* parse pasv command (129, 80, 95, 25, 13, 221) */ + tpath = tmp_line; + /* skip over the "227 Some message " part */ +- for (tpath += 4; *tpath && !isdigit((int) *tpath); tpath++); ++ for (tpath += 4; *tpath && !isdigit((unsigned char)*tpath); tpath++); + if (!*tpath) { + return 0; + } + /* skip over the host ip, to get the port */ + hoststart = tpath; + for (i = 0; i < 4; i++) { +- for (; isdigit((int) *tpath); tpath++); ++ for (; isdigit((unsigned char)*tpath); tpath++); + if (*tpath != ',') { + return 0; + } +@@ -838,7 +838,7 @@ static int php_stream_ftp_url_stat(php_stream_wrapper *wrapper, const char *url, + struct tm tm, tmbuf, *gmt; + time_t stamp; + +- while ((size_t)(p - tmp_line) < sizeof(tmp_line) && !isdigit(*p)) { ++ while ((size_t)(p - tmp_line) < sizeof(tmp_line) && !isdigit((unsigned char)*p)) { + p++; + } + +diff --git a/ext/standard/html.c b/ext/standard/html.c +index e9c46ba..a2e39f7 100644 +--- a/ext/standard/html.c ++++ b/ext/standard/html.c +@@ -753,8 +753,8 @@ static inline int process_numeric_entity(const char **buf, unsigned *code_point) + + /* strtol allows whitespace and other stuff in the beginning + * we're not interested */ +- if ((hexadecimal && !isxdigit(**buf)) || +- (!hexadecimal && !isdigit(**buf))) { ++ if ((hexadecimal && !isxdigit((unsigned char)**buf)) || ++ (!hexadecimal && !isdigit((unsigned char)**buf))) { + return FAILURE; + } + +diff --git a/ext/standard/http_fopen_wrapper.c b/ext/standard/http_fopen_wrapper.c +index 4d918b2..4a36874 100644 +--- a/ext/standard/http_fopen_wrapper.c ++++ b/ext/standard/http_fopen_wrapper.c +@@ -69,46 +69,91 @@ + + #include "php_fopen_wrappers.h" + +-#define HTTP_HEADER_BLOCK_SIZE 1024 +-#define PHP_URL_REDIRECT_MAX 20 +-#define HTTP_HEADER_USER_AGENT 1 +-#define HTTP_HEADER_HOST 2 +-#define HTTP_HEADER_AUTH 4 +-#define HTTP_HEADER_FROM 8 +-#define HTTP_HEADER_CONTENT_LENGTH 16 +-#define HTTP_HEADER_TYPE 32 +-#define HTTP_HEADER_CONNECTION 64 ++#define HTTP_HEADER_BLOCK_SIZE 1024 ++#define HTTP_HEADER_MAX_LOCATION_SIZE 8182 /* 8192 - 10 (size of "Location: ") */ ++#define PHP_URL_REDIRECT_MAX 20 ++#define HTTP_HEADER_USER_AGENT 1 ++#define HTTP_HEADER_HOST 2 ++#define HTTP_HEADER_AUTH 4 ++#define HTTP_HEADER_FROM 8 ++#define HTTP_HEADER_CONTENT_LENGTH 16 ++#define HTTP_HEADER_TYPE 32 ++#define HTTP_HEADER_CONNECTION 64 + + #define HTTP_WRAPPER_HEADER_INIT 1 + #define HTTP_WRAPPER_REDIRECTED 2 ++#define HTTP_WRAPPER_KEEP_METHOD 4 ++#define HTTP_WRAPPER_STRIP_AUTH 8 + ++static char *next_header_line(char *line) ++{ ++ while (*line != '\0' && *line != '\r' && *line != '\n') { ++ line++; ++ } ++ if (*line == '\r') { ++ line++; ++ } ++ if (*line == '\n') { ++ line++; ++ } ++ ++ return line; ++} ++ ++/* Removes every line whose header name matches, along with the folded ++ * continuation lines carrying the rest of its value. Neither a repeated header ++ * nor an occurrence of the name inside another header's value may leave the real ++ * header behind, as that would defeat HTTP_WRAPPER_STRIP_AUTH. */ + static inline void strip_header(char *header_bag, char *lc_header_bag, + const char *lc_header_name) + { +- char *lc_header_start = strstr(lc_header_bag, lc_header_name); +- if (lc_header_start +- && (lc_header_start == lc_header_bag || *(lc_header_start-1) == '\n') +- ) { +- char *header_start = header_bag + (lc_header_start - lc_header_bag); +- char *lc_eol = strchr(lc_header_start, '\n'); ++ size_t name_len = strlen(lc_header_name); ++ char *lc_line = lc_header_bag; + +- if (lc_eol) { +- char *eol = header_start + (lc_eol - lc_header_start); +- size_t eollen = strlen(lc_eol); ++ while (*lc_line != '\0') { ++ if (strncmp(lc_line, lc_header_name, name_len) != 0) { ++ lc_line = next_header_line(lc_line); ++ continue; ++ } + +- memmove(lc_header_start, lc_eol+1, eollen); +- memmove(header_start, eol+1, eollen); +- } else { +- *lc_header_start = '\0'; +- *header_start = '\0'; ++ /* the whitespace RFC 7230 forbids before the colon is tolerated by some ++ * servers, so it must not hide the header from us either */ ++ const char *lc_colon = lc_line + name_len; ++ while (*lc_colon == ' ' || *lc_colon == '\t') { ++ lc_colon++; ++ } ++ ++ if (*lc_colon != ':') { ++ lc_line = next_header_line(lc_line); ++ continue; ++ } ++ ++ char *lc_next = next_header_line(lc_line); ++ while (*lc_next == ' ' || *lc_next == '\t') { ++ lc_next = next_header_line(lc_next); + } ++ ++ if (*lc_next == '\0') { ++ /* drop the preceding line break too, or the one appended after the bag ++ * would close the header block early */ ++ while (lc_line > lc_header_bag ++ && (*(lc_line - 1) == '\r' || *(lc_line - 1) == '\n')) { ++ --lc_line; ++ } ++ } ++ ++ size_t tail_len = strlen(lc_next) + 1; ++ char *line = header_bag + (lc_line - lc_header_bag); ++ ++ memmove(line, header_bag + (lc_next - lc_header_bag), tail_len); ++ memmove(lc_line, lc_next, tail_len); + } + } + + static zend_bool check_has_header(const char *headers, const char *header) { + const char *s = headers; + while ((s = strstr(s, header))) { +- if (s == headers || *(s-1) == '\n') { ++ if (s == headers || (*(s-1) == '\n' && *(s-2) == '\r')) { + return 1; + } + s++; +@@ -116,6 +161,204 @@ static zend_bool check_has_header(const char *headers, const char *header) { + return 0; + } + ++typedef struct _php_stream_http_response_header_info { ++ php_stream_filter *transfer_encoding; ++ size_t file_size; ++ zend_bool error; ++ zend_bool follow_location; ++ char *location; ++ size_t location_len; ++} php_stream_http_response_header_info; ++ ++static void php_stream_http_response_header_info_init( ++ php_stream_http_response_header_info *header_info) ++{ ++ memset(header_info, 0, sizeof(php_stream_http_response_header_info)); ++ header_info->follow_location = 1; ++} ++ ++/* Trim white spaces from response header line and update its length */ ++static zend_bool php_stream_http_response_header_trim(char *http_header_line, ++ size_t *http_header_line_length) ++{ ++ char *http_header_line_end = http_header_line + *http_header_line_length - 1; ++ while (http_header_line_end >= http_header_line && ++ (*http_header_line_end == '\n' || *http_header_line_end == '\r')) { ++ http_header_line_end--; ++ } ++ ++ /* The primary definition of an HTTP header in RFC 7230 states: ++ * > Each header field consists of a case-insensitive field name followed ++ * > by a colon (":"), optional leading whitespace, the field value, and ++ * > optional trailing whitespace. */ ++ ++ /* Strip trailing whitespace */ ++ zend_bool space_trim = (*http_header_line_end == ' ' || *http_header_line_end == '\t'); ++ if (space_trim) { ++ do { ++ http_header_line_end--; ++ } while (http_header_line_end >= http_header_line && ++ (*http_header_line_end == ' ' || *http_header_line_end == '\t')); ++ } ++ http_header_line_end++; ++ *http_header_line_end = '\0'; ++ *http_header_line_length = http_header_line_end - http_header_line; ++ ++ return space_trim; ++} ++ ++/* Process folding headers of the current line and if there are none, parse last full response ++ * header line. It returns NULL if the last header is finished, otherwise it returns updated ++ * last header line. */ ++static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *wrapper, ++ php_stream *stream, php_stream_context *context, int options, ++ zend_string *last_header_line_str, char *header_line, size_t *header_line_length, ++ int response_code, zval *response_header, ++ php_stream_http_response_header_info *header_info) ++{ ++ char *last_header_line = ZSTR_VAL(last_header_line_str); ++ size_t last_header_line_length = ZSTR_LEN(last_header_line_str); ++ char *last_header_line_end = ZSTR_VAL(last_header_line_str) + ZSTR_LEN(last_header_line_str) - 1; ++ ++ /* Process non empty header line. */ ++ if (header_line && (*header_line != '\n' && *header_line != '\r')) { ++ /* Removing trailing white spaces. */ ++ if (php_stream_http_response_header_trim(header_line, header_line_length) && ++ *header_line_length == 0) { ++ /* Only spaces so treat as an empty folding header. */ ++ return last_header_line_str; ++ } ++ ++ /* Process folding headers if starting with a space or a tab. */ ++ if (header_line && (*header_line == ' ' || *header_line == '\t')) { ++ char *http_folded_header_line = header_line; ++ size_t http_folded_header_line_length = *header_line_length; ++ /* Remove the leading white spaces. */ ++ while (*http_folded_header_line == ' ' || *http_folded_header_line == '\t') { ++ http_folded_header_line++; ++ http_folded_header_line_length--; ++ } ++ /* It has to have some characters because it would get returned after the call ++ * php_stream_http_response_header_trim above. */ ++ ZEND_ASSERT(http_folded_header_line_length > 0); ++ /* Concatenate last header line, space and current header line. */ ++ zend_string *extended_header_str = zend_string_alloc(last_header_line_length + 1 + http_folded_header_line_length, 0); ++ memcpy(ZSTR_VAL(extended_header_str), last_header_line, last_header_line_length); ++ ZSTR_VAL(extended_header_str)[last_header_line_length] = ' '; ++ memcpy(ZSTR_VAL(extended_header_str) + last_header_line_length + 1, http_folded_header_line, http_folded_header_line_length); ++ ZSTR_VAL(extended_header_str)[ZSTR_LEN(extended_header_str)] = 0; ++ zend_string_efree(last_header_line_str); ++ last_header_line_str = extended_header_str; ++ /* Return new header line. */ ++ return last_header_line_str; ++ } ++ } ++ ++ /* Find header separator position. */ ++ char *last_header_value = memchr(last_header_line, ':', last_header_line_length); ++ if (last_header_value) { ++ /* Verify there is no space in header name */ ++ char *last_header_name = last_header_line + 1; ++ while (last_header_name < last_header_value) { ++ if (*last_header_name == ' ' || *last_header_name == '\t') { ++ header_info->error = 1; ++ php_stream_wrapper_log_error(wrapper, options, ++ "HTTP invalid response format (space in header name)!"); ++ zend_string_efree(last_header_line_str); ++ return NULL; ++ } ++ ++last_header_name; ++ } ++ ++ last_header_value++; /* Skip ':'. */ ++ ++ /* Strip leading whitespace. */ ++ while (last_header_value < last_header_line_end ++ && (*last_header_value == ' ' || *last_header_value == '\t')) { ++ last_header_value++; ++ } ++ } else { ++ /* There is no colon which means invalid response so error. */ ++ header_info->error = 1; ++ php_stream_wrapper_log_error(wrapper, options, ++ "HTTP invalid response format (no colon in header line)!"); ++ zend_string_efree(last_header_line_str); ++ return NULL; ++ } ++ ++ zend_bool store_header = 1; ++ zval *tmpzval = NULL; ++ ++ if (!strncasecmp(last_header_line, "Location:", sizeof("Location:")-1)) { ++ /* Check if the location should be followed. */ ++ if (context && (tmpzval = php_stream_context_get_option(context, "http", "follow_location")) != NULL) { ++ header_info->follow_location = zval_is_true(tmpzval); ++ } else if (!((response_code >= 300 && response_code < 304) ++ || 307 == response_code || 308 == response_code)) { ++ /* The redirection should not be automatic if follow_location is not set and ++ * response_code not in (300, 301, 302, 303 and 307) ++ * see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 ++ * RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ ++ header_info->follow_location = 0; ++ } ++ size_t last_header_value_len = strlen(last_header_value); ++ if (last_header_value_len > HTTP_HEADER_MAX_LOCATION_SIZE) { ++ header_info->error = 1; ++ php_stream_wrapper_log_error(wrapper, options, ++ "HTTP Location header size is over the limit of %d bytes", ++ HTTP_HEADER_MAX_LOCATION_SIZE); ++ zend_string_efree(last_header_line_str); ++ return NULL; ++ } ++ if (header_info->location_len == 0) { ++ header_info->location = emalloc(last_header_value_len + 1); ++ } else if (header_info->location_len <= last_header_value_len) { ++ header_info->location = erealloc(header_info->location, last_header_value_len + 1); ++ } ++ header_info->location_len = last_header_value_len; ++ memcpy(header_info->location, last_header_value, last_header_value_len + 1); ++ } else if (!strncasecmp(last_header_line, "Content-Type:", sizeof("Content-Type:")-1)) { ++ php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, last_header_value, 0); ++ } else if (!strncasecmp(last_header_line, "Content-Length:", sizeof("Content-Length:")-1)) { ++ header_info->file_size = atoi(last_header_value); ++ php_stream_notify_file_size(context, header_info->file_size, last_header_line, 0); ++ } else if ( ++ !strncasecmp(last_header_line, "Transfer-Encoding:", sizeof("Transfer-Encoding:")-1) ++ && !strncasecmp(last_header_value, "Chunked", sizeof("Chunked")-1) ++ ) { ++ /* Create filter to decode response body. */ ++ if (!(options & STREAM_ONLY_GET_HEADERS)) { ++ zend_long decode = 1; ++ ++ if (context && (tmpzval = php_stream_context_get_option(context, "http", "auto_decode")) != NULL) { ++ decode = zend_is_true(tmpzval); ++ } ++ if (decode) { ++ if (header_info->transfer_encoding != NULL) { ++ /* Prevent a memory leak in case there are more transfer-encoding headers. */ ++ php_stream_filter_free(header_info->transfer_encoding); ++ } ++ header_info->transfer_encoding = php_stream_filter_create( ++ "dechunk", NULL, php_stream_is_persistent(stream)); ++ if (header_info->transfer_encoding != NULL) { ++ /* Do not store transfer-encoding header. */ ++ store_header = 0; ++ } ++ } ++ } ++ } ++ ++ if (store_header) { ++ zval http_header; ++ ZVAL_NEW_STR(&http_header, last_header_line_str); ++ zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header); ++ } else { ++ zend_string_efree(last_header_line_str); ++ } ++ ++ return NULL; ++} ++ + static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, + const char *path, const char *mode, int options, zend_string **opened_path, + php_stream_context *context, int redirect_max, int flags, +@@ -128,11 +371,12 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, + zend_string *tmp = NULL; + char *ua_str = NULL; + zval *ua_zval = NULL, *tmpzval = NULL, ssl_proxy_peer_name; +- char location[HTTP_HEADER_BLOCK_SIZE]; + int reqok = 0; + char *http_header_line = NULL; ++ zend_string *last_header_line_str = NULL; ++ php_stream_http_response_header_info header_info; + char tmp_line[128]; +- size_t chunk_size = 0, file_size = 0; ++ size_t chunk_size = 0; + int eol_detect = 0; + char *transport_string; + zend_string *errstr = NULL; +@@ -143,8 +387,7 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, + char *user_headers = NULL; + int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); + int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); +- zend_bool follow_location = 1; +- php_stream_filter *transfer_encoding = NULL; ++ int redirect_keep_method = ((flags & HTTP_WRAPPER_KEEP_METHOD) != 0); + int response_code; + smart_str req_buf = {0}; + zend_bool custom_request_method; +@@ -186,6 +429,11 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, + return NULL; + } + ++ /* Should we send the entire path in the request line, default to no. */ ++ if (context && (tmpzval = php_stream_context_get_option(context, "http", "request_fulluri")) != NULL) { ++ request_fulluri = zend_is_true(tmpzval); ++ } ++ + use_ssl = resource->scheme && (ZSTR_LEN(resource->scheme) > 4) && ZSTR_VAL(resource->scheme)[4] == 's'; + /* choose default ports */ + if (use_ssl && resource->port == 0) +@@ -205,6 +453,13 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, + } + } + ++ if (request_fulluri && (strchr(path, '\n') != NULL || strchr(path, '\r') != NULL)) { ++ php_stream_wrapper_log_error(wrapper, options, "HTTP wrapper full URI path does not allow CR or LF characters"); ++ php_url_free(resource); ++ efree(transport_string); ++ return NULL; ++ } ++ + if (context && (tmpzval = php_stream_context_get_option(context, wrapper->wops->label, "timeout")) != NULL) { + double d = zval_get_double(tmpzval); + #ifndef PHP_WIN32 +@@ -345,6 +600,8 @@ finish: + } + } + ++ php_stream_http_response_header_info_init(&header_info); ++ + if (stream == NULL) + goto out; + +@@ -370,7 +627,7 @@ finish: + if (Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval) > 0) { + /* As per the RFC, automatically redirected requests MUST NOT use other methods than + * GET and HEAD unless it can be confirmed by the user */ +- if (!redirected ++ if (!redirected || redirect_keep_method + || (Z_STRLEN_P(tmpzval) == 3 && memcmp("GET", Z_STRVAL_P(tmpzval), 3) == 0) + || (Z_STRLEN_P(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_P(tmpzval), 4) == 0) + ) { +@@ -385,12 +642,6 @@ finish: + smart_str_appends(&req_buf, "GET "); + } + +- /* Should we send the entire path in the request line, default to no. */ +- if (!request_fulluri && context && +- (tmpzval = php_stream_context_get_option(context, "http", "request_fulluri")) != NULL) { +- request_fulluri = zend_is_true(tmpzval); +- } +- + if (request_fulluri) { + /* Ask for everything */ + smart_str_appends(&req_buf, path); +@@ -464,10 +715,25 @@ finish: + php_strtolower(ZSTR_VAL(tmp), ZSTR_LEN(tmp)); + t = ZSTR_VAL(tmp); + +- if (!header_init) { ++ if (!header_init && !redirect_keep_method) { + /* strip POST headers on redirect */ +- strip_header(user_headers, t, "content-length:"); +- strip_header(user_headers, t, "content-type:"); ++ strip_header(user_headers, t, "content-length"); ++ strip_header(user_headers, t, "content-type"); ++ } ++ ++ if (flags & HTTP_WRAPPER_STRIP_AUTH) { ++ strip_header(user_headers, t, "authorization"); ++ strip_header(user_headers, t, "cookie"); ++ if (!use_proxy) { ++ strip_header(user_headers, t, "proxy-authorization"); ++ } ++ } ++ ++ if (*user_headers == '\0') { ++ /* everything got stripped, keeping the empty bag would append a ++ * stray CRLF and end the header block early */ ++ efree(user_headers); ++ user_headers = NULL; + } + + if (check_has_header(t, "user-agent:")) { +@@ -612,7 +878,7 @@ finish: + * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. + */ + if ( +- header_init && ++ (header_init || redirect_keep_method) && + context && + !(have_header & HTTP_HEADER_CONTENT_LENGTH) && + (tmpzval = php_stream_context_get_option(context, "http", "content")) != NULL && +@@ -630,7 +896,7 @@ finish: + } + + /* Request content, such as for POST requests */ +- if (header_init && context && ++ if ((header_init || redirect_keep_method) && context && + (tmpzval = php_stream_context_get_option(context, "http", "content")) != NULL && + Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval) > 0) { + if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { +@@ -651,8 +917,6 @@ finish: + /* send it */ + php_stream_write(stream, ZSTR_VAL(req_buf.s), ZSTR_LEN(req_buf.s)); + +- location[0] = '\0'; +- + if (Z_ISUNDEF_P(response_header)) { + array_init(response_header); + } +@@ -731,124 +995,103 @@ finish: + } + + /* read past HTTP headers */ +- + while (!php_stream_eof(stream)) { + size_t http_header_line_length; + + if (http_header_line != NULL) { + efree(http_header_line); + } +- if ((http_header_line = php_stream_get_line(stream, NULL, 0, &http_header_line_length)) && *http_header_line != '\n' && *http_header_line != '\r') { +- char *e = http_header_line + http_header_line_length - 1; +- char *http_header_value; +- +- while (e >= http_header_line && (*e == '\n' || *e == '\r')) { +- e--; +- } +- +- /* The primary definition of an HTTP header in RFC 7230 states: +- * > Each header field consists of a case-insensitive field name followed +- * > by a colon (":"), optional leading whitespace, the field value, and +- * > optional trailing whitespace. */ +- +- /* Strip trailing whitespace */ +- while (e >= http_header_line && (*e == ' ' || *e == '\t')) { +- e--; +- } +- +- /* Terminate header line */ +- e++; +- *e = '\0'; +- http_header_line_length = e - http_header_line; +- +- http_header_value = memchr(http_header_line, ':', http_header_line_length); +- if (http_header_value) { +- http_header_value++; /* Skip ':' */ +- +- /* Strip leading whitespace */ +- while (http_header_value < e +- && (*http_header_value == ' ' || *http_header_value == '\t')) { +- http_header_value++; ++ if ((http_header_line = php_stream_get_line(stream, NULL, 0, &http_header_line_length))) { ++ zend_bool last_line; ++ if (*http_header_line == '\r') { ++ if (http_header_line[1] != '\n') { ++ php_stream_close(stream); ++ stream = NULL; ++ php_stream_wrapper_log_error(wrapper, options, ++ "HTTP invalid header name (cannot start with CR character)!"); ++ goto out; + } ++ last_line = 1; ++ } else if (*http_header_line == '\n') { ++ last_line = 1; + } else { +- /* There is no colon. Set the value to the end of the header line, which is +- * effectively an empty string. */ +- http_header_value = e; +- } +- +- if (!strncasecmp(http_header_line, "Location:", sizeof("Location:")-1)) { +- if (context && (tmpzval = php_stream_context_get_option(context, "http", "follow_location")) != NULL) { +- follow_location = zval_is_true(tmpzval); +- } else if (!((response_code >= 300 && response_code < 304) +- || 307 == response_code || 308 == response_code)) { +- /* we shouldn't redirect automatically +- if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) +- see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 +- RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ +- follow_location = 0; +- } +- strlcpy(location, http_header_value, sizeof(location)); +- } else if (!strncasecmp(http_header_line, "Content-Type:", sizeof("Content-Type:")-1)) { +- php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_value, 0); +- } else if (!strncasecmp(http_header_line, "Content-Length:", sizeof("Content-Length:")-1)) { +- file_size = atoi(http_header_value); +- php_stream_notify_file_size(context, file_size, http_header_line, 0); +- } else if ( +- !strncasecmp(http_header_line, "Transfer-Encoding:", sizeof("Transfer-Encoding:")-1) +- && !strncasecmp(http_header_value, "Chunked", sizeof("Chunked")-1) +- ) { +- +- /* create filter to decode response body */ +- if (!(options & STREAM_ONLY_GET_HEADERS)) { +- zend_long decode = 1; +- +- if (context && (tmpzval = php_stream_context_get_option(context, "http", "auto_decode")) != NULL) { +- decode = zend_is_true(tmpzval); +- } +- if (decode) { +- transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream)); +- if (transfer_encoding) { +- /* don't store transfer-encodeing header */ +- continue; +- } ++ last_line = 0; ++ } ++ ++ if (last_header_line_str != NULL) { ++ /* Parse last header line. */ ++ last_header_line_str = php_stream_http_response_headers_parse(wrapper, stream, ++ context, options, last_header_line_str, http_header_line, ++ &http_header_line_length, response_code, response_header, &header_info); ++ if (EXPECTED(last_header_line_str == NULL)) { ++ if (UNEXPECTED(header_info.error)) { ++ php_stream_close(stream); ++ stream = NULL; ++ goto out; + } ++ } else { ++ /* Folding header present so continue. */ ++ continue; + } ++ } else if (!last_line) { ++ /* The first line cannot start with spaces. */ ++ if (*http_header_line == ' ' || *http_header_line == '\t') { ++ php_stream_close(stream); ++ stream = NULL; ++ php_stream_wrapper_log_error(wrapper, options, ++ "HTTP invalid response format (folding header at the start)!"); ++ goto out; ++ } ++ /* Trim the first line if it is not the last line. */ ++ php_stream_http_response_header_trim(http_header_line, &http_header_line_length); + } +- +- { +- zval http_header; +- ZVAL_STRINGL(&http_header, http_header_line, http_header_line_length); +- zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header); ++ if (last_line) { ++ /* For the last line the last header line must be NULL. */ ++ ZEND_ASSERT(last_header_line_str == NULL); ++ break; + } ++ /* Save current line as the last line so it gets parsed in the next round. */ ++ last_header_line_str = zend_string_init(http_header_line, http_header_line_length, 0); + } else { + break; + } + } + +- if (!reqok || (location[0] != '\0' && follow_location)) { +- if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { ++ /* If the stream was closed early, we still want to process the last line to keep BC. */ ++ if (last_header_line_str != NULL) { ++ php_stream_http_response_headers_parse(wrapper, stream, context, options, ++ last_header_line_str, NULL, NULL, response_code, response_header, &header_info); ++ } ++ ++ if (!reqok || (header_info.location != NULL && header_info.follow_location)) { ++ if (!header_info.follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { + goto out; + } + +- if (location[0] != '\0') +- php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); ++ if (header_info.location != NULL) ++ php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, header_info.location, 0); + + php_stream_close(stream); + stream = NULL; + +- if (location[0] != '\0') { ++ if (header_info.transfer_encoding) { ++ php_stream_filter_free(header_info.transfer_encoding); ++ header_info.transfer_encoding = NULL; ++ } ++ ++ if (header_info.location != NULL) { + +- char new_path[HTTP_HEADER_BLOCK_SIZE]; +- char loc_path[HTTP_HEADER_BLOCK_SIZE]; ++ char *new_path = NULL; + +- *new_path='\0'; +- if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && +- strncasecmp(location, "https://", sizeof("https://")-1) && +- strncasecmp(location, "ftp://", sizeof("ftp://")-1) && +- strncasecmp(location, "ftps://", sizeof("ftps://")-1))) ++ if (header_info.location_len < 8 || ++ (strncasecmp(header_info.location, "http://", sizeof("http://")-1) && ++ strncasecmp(header_info.location, "https://", sizeof("https://")-1) && ++ strncasecmp(header_info.location, "ftp://", sizeof("ftp://")-1) && ++ strncasecmp(header_info.location, "ftps://", sizeof("ftps://")-1))) + { +- if (*location != '/') { +- if (*(location+1) != '\0' && resource->path) { ++ char *loc_path = NULL; ++ if (*header_info.location != '/') { ++ if (header_info.location_len > 1 && resource->path) { + char *s = strrchr(ZSTR_VAL(resource->path), '/'); + if (!s) { + s = ZSTR_VAL(resource->path); +@@ -864,32 +1107,46 @@ finish: + if (resource->path && + ZSTR_VAL(resource->path)[0] == '/' && + ZSTR_VAL(resource->path)[1] == '\0') { +- snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", ZSTR_VAL(resource->path), location); ++ spprintf(&loc_path, 0, "%s%s", ZSTR_VAL(resource->path), header_info.location); + } else { +- snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", ZSTR_VAL(resource->path), location); ++ spprintf(&loc_path, 0, "%s/%s", ZSTR_VAL(resource->path), header_info.location); + } + } else { +- snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); ++ spprintf(&loc_path, 0, "/%s", header_info.location); + } + } else { +- strlcpy(loc_path, location, sizeof(loc_path)); ++ loc_path = header_info.location; ++ header_info.location = NULL; + } + if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { +- snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), resource->port, loc_path); ++ spprintf(&new_path, 0, "%s://%s:%d%s", ZSTR_VAL(resource->scheme), ++ ZSTR_VAL(resource->host), resource->port, loc_path); + } else { +- snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), loc_path); ++ spprintf(&new_path, 0, "%s://%s%s", ZSTR_VAL(resource->scheme), ++ ZSTR_VAL(resource->host), loc_path); + } ++ efree(loc_path); + } else { +- strlcpy(new_path, location, sizeof(new_path)); ++ new_path = header_info.location; ++ header_info.location = NULL; + } + +- php_url_free(resource); +- /* check for invalid redirection URLs */ +- if ((resource = php_url_parse(new_path)) == NULL) { ++ php_url *new_resource = php_url_parse(new_path); ++ if (new_resource == NULL) { + php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path); ++ efree(new_path); + goto out; + } + ++ int default_port = use_ssl ? 443 : 80; ++ zend_bool same_origin = zend_string_equals_ci(resource->scheme, new_resource->scheme) ++ && zend_string_equals_ci(resource->host, new_resource->host) ++ && (resource->port ? resource->port : default_port) ++ == (new_resource->port ? new_resource->port : default_port); ++ ++ php_url_free(resource); ++ resource = new_resource; ++ + #define CHECK_FOR_CNTRL_CHARS(val) { \ + if (val) { \ + unsigned char *s, *e; \ +@@ -898,6 +1155,7 @@ finish: + while (s < e) { \ + if (iscntrl(*s)) { \ + php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path); \ ++ efree(new_path); \ + goto out; \ + } \ + s++; \ +@@ -910,9 +1168,20 @@ finish: + CHECK_FOR_CNTRL_CHARS(resource->pass); + CHECK_FOR_CNTRL_CHARS(resource->path); + } ++ int new_flags = HTTP_WRAPPER_REDIRECTED | (flags & HTTP_WRAPPER_STRIP_AUTH); ++ if (!same_origin) { ++ new_flags |= HTTP_WRAPPER_STRIP_AUTH; ++ } ++ if (response_code == 307 || response_code == 308) { ++ /* RFC 7538 specifies that status code 308 does not allow changing the request method from POST to GET. ++ * RFC 7231 does the same for status code 307. ++ * To keep consistency between POST and PATCH requests, we'll also not change the request method from PATCH to GET, even though it's allowed it's not mandated by the RFC. */ ++ new_flags |= HTTP_WRAPPER_KEEP_METHOD; ++ } + stream = php_stream_url_wrap_http_ex( + wrapper, new_path, mode, options, opened_path, context, +- --redirect_max, HTTP_WRAPPER_REDIRECTED, response_header STREAMS_CC); ++ --redirect_max, new_flags, response_header STREAMS_CC); ++ efree(new_path); + } else { + php_stream_wrapper_log_error(wrapper, options, "HTTP request failed! %s", tmp_line); + } +@@ -925,6 +1194,10 @@ out: + efree(http_header_line); + } + ++ if (header_info.location != NULL) { ++ efree(header_info.location); ++ } ++ + if (resource) { + php_url_free(resource); + } +@@ -933,7 +1206,7 @@ out: + if (header_init) { + ZVAL_COPY(&stream->wrapperdata, response_header); + } +- php_stream_notify_progress_init(context, 0, file_size); ++ php_stream_notify_progress_init(context, 0, header_info.file_size); + + /* Restore original chunk size now that we're done with headers */ + if (options & STREAM_WILL_CAST) +@@ -949,12 +1222,8 @@ out: + /* restore mode */ + strlcpy(stream->mode, mode, sizeof(stream->mode)); + +- if (transfer_encoding) { +- php_stream_filter_append(&stream->readfilters, transfer_encoding); +- } +- } else { +- if (transfer_encoding) { +- php_stream_filter_free(transfer_encoding); ++ if (header_info.transfer_encoding) { ++ php_stream_filter_append(&stream->readfilters, header_info.transfer_encoding); + } + } + +diff --git a/ext/standard/image.c b/ext/standard/image.c +index 4f2c5a5..800c5de 100644 +--- a/ext/standard/image.c ++++ b/ext/standard/image.c +@@ -434,8 +434,22 @@ static int php_skip_variable(php_stream * stream) + } + /* }}} */ + +-/* {{{ php_read_APP +- */ ++static size_t php_read_stream_all_chunks(php_stream *stream, char *buffer, size_t length) ++{ ++ size_t read_total = 0; ++ do { ++ ssize_t read_now = php_stream_read(stream, buffer, length - read_total); ++ read_total += read_now; ++ if (read_now < stream->chunk_size && read_total != length) { ++ return 0; ++ } ++ buffer += read_now; ++ } while (read_total < length); ++ ++ return read_total; ++} ++ ++/* {{{ php_read_APP */ + static int php_read_APP(php_stream * stream, unsigned int marker, zval *info) + { + unsigned short length; +@@ -451,7 +465,7 @@ static int php_read_APP(php_stream * stream, unsigned int marker, zval *info) + + buffer = emalloc((size_t)length); + +- if (php_stream_read(stream, buffer, (size_t) length) != length) { ++ if (php_read_stream_all_chunks(stream, buffer, length) != length) { + efree(buffer); + return 0; + } +diff --git a/ext/standard/math.c b/ext/standard/math.c +index ba7e394..d8675be 100644 +--- a/ext/standard/math.c ++++ b/ext/standard/math.c +@@ -863,9 +863,9 @@ PHPAPI int _php_math_basetozval(zval *arg, int base, zval *ret) + e = s + Z_STRLEN_P(arg); + + /* Skip leading whitespace */ +- while (s < e && isspace(*s)) s++; ++ while (s < e && isspace((unsigned char)*s)) s++; + /* Skip trailing whitespace */ +- while (s < e && isspace(*(e-1))) e--; ++ while (s < e && isspace((unsigned char)e[-1])) e--; + + if (e - s >= 2) { + if (base == 16 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) s += 2; +@@ -1160,7 +1160,7 @@ PHPAPI zend_string *_php_math_number_format_ex(double d, int dec, char *dec_poin + tmpbuf = strpprintf(0, "%.*F", dec, d); + if (tmpbuf == NULL) { + return NULL; +- } else if (!isdigit((int)ZSTR_VAL(tmpbuf)[0])) { ++ } else if (!isdigit((unsigned char)ZSTR_VAL(tmpbuf)[0])) { + return tmpbuf; + } + +diff --git a/ext/standard/metaphone.c b/ext/standard/metaphone.c +index 16fd149..5a967fe 100644 +--- a/ext/standard/metaphone.c ++++ b/ext/standard/metaphone.c +@@ -83,7 +83,7 @@ static const char _codes[26] = + }; + + +-#define ENCODE(c) (isalpha(c) ? _codes[((toupper(c)) - 'A')] : 0) ++#define ENCODE(c) (isalpha((unsigned char)(c)) ? _codes[((toupper((unsigned char)(c))) - 'A')] : 0) + + #define isvowel(c) (ENCODE(c) & 1) /* AEIOU */ + +@@ -107,25 +107,25 @@ static const char _codes[26] = + * accesssing the array directly... */ + + /* Look at the next letter in the word */ +-#define Next_Letter (toupper(word[w_idx+1])) ++#define Next_Letter (toupper((unsigned char)word[w_idx+1])) + /* Look at the current letter in the word */ +-#define Curr_Letter (toupper(word[w_idx])) ++#define Curr_Letter (toupper((unsigned char)word[w_idx])) + /* Go N letters back. */ +-#define Look_Back_Letter(n) (w_idx >= n ? toupper(word[w_idx-n]) : '\0') ++#define Look_Back_Letter(n) (w_idx >= n ? toupper((unsigned char)word[w_idx-n]) : '\0') + /* Previous letter. I dunno, should this return null on failure? */ + #define Prev_Letter (Look_Back_Letter(1)) + /* Look two letters down. It makes sure you don't walk off the string. */ +-#define After_Next_Letter (Next_Letter != '\0' ? toupper(word[w_idx+2]) \ ++#define After_Next_Letter (Next_Letter != '\0' ? toupper((unsigned char)word[w_idx+2]) \ + : '\0') +-#define Look_Ahead_Letter(n) (toupper(Lookahead((char *) word+w_idx, n))) ++#define Look_Ahead_Letter(n) (toupper((unsigned char)Lookahead((char *) word+w_idx, n))) + + + /* Allows us to safely look ahead an arbitrary # of letters */ + /* I probably could have just used strlen... */ +-static char Lookahead(char *word, int how_far) ++static char Lookahead(char *word, size_t how_far) + { + char letter_ahead = '\0'; /* null by default */ +- int idx; ++ size_t idx; + for (idx = 0; word[idx] != '\0' && idx < how_far; idx++); + /* Edge forward in the string... */ + +@@ -161,13 +161,13 @@ static char Lookahead(char *word, int how_far) + #define Phone_Len (p_idx) + + /* Note is a letter is a 'break' in the word */ +-#define Isbreak(c) (!isalpha(c)) ++#define Isbreak(c) (!isalpha((unsigned char)(c))) + + /* {{{ metaphone + */ + static int metaphone(unsigned char *word, size_t word_len, zend_long max_phonemes, zend_string **phoned_word, int traditional) + { +- int w_idx = 0; /* point in the phonization we're at. */ ++ size_t w_idx = 0; /* point in the phonization we're at. */ + size_t p_idx = 0; /* end of the phoned phrase */ + size_t max_buffer_len = 0; /* maximum length of the destination buffer */ + +@@ -196,7 +196,7 @@ static int metaphone(unsigned char *word, size_t word_len, zend_long max_phoneme + + /*-- The first phoneme has to be processed specially. --*/ + /* Find our first letter */ +- for (; !isalpha(Curr_Letter); w_idx++) { ++ for (; !isalpha((unsigned char)Curr_Letter); w_idx++) { + /* On the off chance we were given nothing but crap... */ + if (Curr_Letter == '\0') { + End_Phoned_Word +@@ -280,7 +280,7 @@ static int metaphone(unsigned char *word, size_t word_len, zend_long max_phoneme + */ + + /* Ignore non-alphas */ +- if (!isalpha(Curr_Letter)) ++ if (!isalpha((unsigned char)Curr_Letter)) + continue; + + /* Drop duplicates, except CC */ +diff --git a/ext/standard/password.c b/ext/standard/password.c +index 9fe7fb1..af80670 100644 +--- a/ext/standard/password.c ++++ b/ext/standard/password.c +@@ -260,6 +260,11 @@ static zend_string* php_password_bcrypt_hash(const zend_string *password, zend_a + zval *zcost; + zend_long cost = PHP_PASSWORD_BCRYPT_COST; + ++ if (memchr(ZSTR_VAL(password), '\0', ZSTR_LEN(password))) { ++ php_error_docref(NULL, E_WARNING, "Bcrypt password must not contain null character"); ++ return NULL; ++ } ++ + if (options && (zcost = zend_hash_str_find(options, "cost", sizeof("cost")-1)) != NULL) { + cost = zval_get_long(zcost); + } +diff --git a/ext/standard/proc_open.c b/ext/standard/proc_open.c +index 25a5f7f..fd3bf21 100644 +--- a/ext/standard/proc_open.c ++++ b/ext/standard/proc_open.c +@@ -420,10 +420,33 @@ static void append_backslashes(smart_string *str, size_t num_bs) { + } + } + +-/* See https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments */ +-static void append_win_escaped_arg(smart_string *str, char *arg) { ++/* See https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments and ++ * https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way */ ++const char *special_chars = "()!^\"<>&|%"; ++ ++static BOOL is_special_character_present(const char *arg) ++{ ++ for (size_t i = 0; i < strlen(arg); ++i) { ++ if (strchr(special_chars, arg[i]) != NULL) { ++ return 1; ++ } ++ } ++ return 0; ++} ++ ++static void append_win_escaped_arg(smart_string *str, char *arg, BOOL is_cmd_argument) ++{ + char c; + size_t num_bs = 0; ++ BOOL has_special_character = 0; ++ ++ if (is_cmd_argument) { ++ has_special_character = is_special_character_present(arg); ++ if (has_special_character) { ++ /* Escape double quote with ^ if executed by cmd.exe. */ ++ smart_string_appendc(str, '^'); ++ } ++ } + smart_string_appendc(str, '"'); + while ((c = *arg)) { + if (c == '\\') { +@@ -434,19 +457,63 @@ static void append_win_escaped_arg(smart_string *str, char *arg) { + num_bs = num_bs * 2 + 1; + } + append_backslashes(str, num_bs); ++ if (has_special_character && strchr(special_chars, c) != NULL) { ++ /* Escape special chars with ^ if executed by cmd.exe. */ ++ smart_string_appendc(str, '^'); ++ } + smart_string_appendc(str, c); + num_bs = 0; + } + arg++; + } + append_backslashes(str, num_bs * 2); ++ if (has_special_character) { ++ /* Escape double quote with ^ if executed by cmd.exe. */ ++ smart_string_appendc(str, '^'); ++ } + smart_string_appendc(str, '"'); + } + ++static BOOL is_executed_by_cmd(const char *prog_name, size_t prog_name_length) ++{ ++ size_t out_len; ++ WCHAR long_name[MAX_PATH]; ++ WCHAR full_name[MAX_PATH]; ++ LPWSTR file_part = NULL; ++ ++ wchar_t *prog_name_wide = php_win32_cp_conv_any_to_w(prog_name, prog_name_length, &out_len); ++ ++ if (GetLongPathNameW(prog_name_wide, long_name, MAX_PATH) == 0) { ++ /* This can fail for example with ERROR_FILE_NOT_FOUND (short path resolution only works for existing files) ++ * in which case we'll pass the path verbatim to the FullPath transformation. */ ++ lstrcpynW(long_name, prog_name_wide, MAX_PATH); ++ } ++ ++ free(prog_name_wide); ++ prog_name_wide = NULL; ++ ++ if (GetFullPathNameW(long_name, MAX_PATH, full_name, &file_part) == 0 || file_part == NULL) { ++ return 0; ++ } ++ ++ BOOL uses_cmd = 0; ++ if (_wcsicmp(file_part, L"cmd.exe") == 0 || _wcsicmp(file_part, L"cmd") == 0) { ++ uses_cmd = 1; ++ } else { ++ const WCHAR *extension_dot = wcsrchr(file_part, L'.'); ++ if (extension_dot && (_wcsicmp(extension_dot, L".bat") == 0 || _wcsicmp(extension_dot, L".cmd") == 0)) { ++ uses_cmd = 1; ++ } ++ } ++ ++ return uses_cmd; ++} ++ + static char *create_win_command_from_args(HashTable *args) { + smart_string str = {0}; + zval *arg_zv; +- zend_bool is_prog_name = 1; ++ BOOL is_prog_name = 1; ++ BOOL is_cmd_execution = 0; + int elem_num = 0; + + ZEND_HASH_FOREACH_VAL(args, arg_zv) { +@@ -456,11 +523,13 @@ static char *create_win_command_from_args(HashTable *args) { + return NULL; + } + +- if (!is_prog_name) { ++ if (is_prog_name) { ++ is_cmd_execution = is_executed_by_cmd(ZSTR_VAL(arg_str), ZSTR_LEN(arg_str)); ++ } else { + smart_string_appendc(&str, ' '); + } + +- append_win_escaped_arg(&str, ZSTR_VAL(arg_str)); ++ append_win_escaped_arg(&str, ZSTR_VAL(arg_str), !is_prog_name && is_cmd_execution); + + is_prog_name = 0; + zend_string_release(arg_str); +diff --git a/ext/standard/quot_print.c b/ext/standard/quot_print.c +index 336a4cc..22e48fd 100644 +--- a/ext/standard/quot_print.c ++++ b/ext/standard/quot_print.c +@@ -219,11 +219,11 @@ PHP_FUNCTION(quoted_printable_decode) + switch (str_in[i]) { + case '=': + if (str_in[i + 1] && str_in[i + 2] && +- isxdigit((int) str_in[i + 1]) && +- isxdigit((int) str_in[i + 2])) ++ isxdigit((unsigned char)str_in[i + 1]) && ++ isxdigit((unsigned char)str_in[i + 2])) + { +- ZSTR_VAL(str_out)[j++] = (php_hex2int((int) str_in[i + 1]) << 4) +- + php_hex2int((int) str_in[i + 2]); ++ ZSTR_VAL(str_out)[j++] = (php_hex2int((unsigned char)str_in[i + 1]) << 4) ++ + php_hex2int((unsigned char)str_in[i + 2]); + i += 3; + } else /* check for soft line break according to RFC 2045*/ { + k = 1; +diff --git a/ext/standard/scanf.c b/ext/standard/scanf.c +index fc48315..d62b910 100644 +--- a/ext/standard/scanf.c ++++ b/ext/standard/scanf.c +@@ -345,7 +345,7 @@ PHPAPI int ValidateFormat(char *format, int numVars, int *totalSubs) + goto xpgCheckDone; + } + +- if ( isdigit( (int)*ch ) ) { ++ if ( isdigit( (unsigned char)*ch ) ) { + /* + * Check for an XPG3-style %n$ specification. Note: there + * must not be a mixture of XPG3 specs and non-XPG3 specs +@@ -664,9 +664,9 @@ PHPAPI int php_sscanf_internal( char *string, char *format, + /* + * If we see whitespace in the format, skip whitespace in the string. + */ +- if ( isspace( (int)*ch ) ) { ++ if ( isspace( (unsigned char)*ch ) ) { + sch = *string; +- while ( isspace( (int)sch ) ) { ++ while ( isspace( (unsigned char)sch ) ) { + if (*string == '\0') { + goto done; + } +@@ -817,7 +817,7 @@ literal: + if (!(flags & SCAN_NOSKIP)) { + while (*string != '\0') { + sch = *string; +- if (! isspace((int)sch) ) { ++ if (! isspace((unsigned char)sch) ) { + break; + } + string++; +@@ -843,7 +843,7 @@ literal: + end = string; + while (*end != '\0') { + sch = *end; +- if ( isspace( (int)sch ) ) { ++ if ( isspace( (unsigned char)sch ) ) { + break; + } + end++; +diff --git a/ext/standard/soundex.c b/ext/standard/soundex.c +index 0f46fbf..7530e24 100644 +--- a/ext/standard/soundex.c ++++ b/ext/standard/soundex.c +@@ -74,7 +74,7 @@ PHP_FUNCTION(soundex) + /* BUG: should also map here accented letters used in non */ + /* English words or names (also found in English text!): */ + /* esstsett, thorn, n-tilde, c-cedilla, s-caron, ... */ +- code = toupper((int)(unsigned char)str[i]); ++ code = toupper((unsigned char)str[i]); + if (code >= 'A' && code <= 'Z') { + if (_small == 0) { + /* remember first valid char */ +diff --git a/ext/standard/string.c b/ext/standard/string.c +index 825d1b7..0c95361 100644 +--- a/ext/standard/string.c ++++ b/ext/standard/string.c +@@ -3773,9 +3773,9 @@ PHPAPI void php_stripcslashes(zend_string *str) + case 'f': *target++='\f'; nlen--; break; + case '\\': *target++='\\'; nlen--; break; + case 'x': +- if (source+1 < end && isxdigit((int)(*(source+1)))) { ++ if (source+1 < end && isxdigit((unsigned char)source[1])) { + numtmp[0] = *++source; +- if (source+1 < end && isxdigit((int)(*(source+1)))) { ++ if (source+1 < end && isxdigit((unsigned char)source[1])) { + numtmp[1] = *++source; + numtmp[2] = '\0'; + nlen-=3; +@@ -4227,19 +4227,23 @@ static zend_always_inline char *php_stripslashes_impl(const char *str, char *out + quad_word q; + vst1q_u8(q.mem, vceqq_u8(x, vdupq_n_u8('\\'))); + if (q.dw[0] | q.dw[1]) { +- int i = 0; +- for (; i < 16; i++) { ++ unsigned int i = 0; ++ while (i < 16) { + if (q.mem[i] == 0) { + *out++ = str[i]; ++ i++; + continue; + } + + i++; /* skip the slash */ +- char s = str[i]; +- if (s == '0') +- *out++ = '\0'; +- else +- *out++ = s; /* preserve the next character */ ++ if (i < len) { ++ char s = str[i]; ++ if (s == '0') ++ *out++ = '\0'; ++ else ++ *out++ = s; /* preserve the next character */ ++ i++; ++ } + } + str += i; + len -= i; +@@ -4636,7 +4640,7 @@ static void php_hebrev(INTERNAL_FUNCTION_PARAMETERS, int convert_newlines) + + do { + if (block_type == _HEB_BLOCK_TYPE_HEB) { +- while ((isheb((int)*(tmp+1)) || _isblank((int)*(tmp+1)) || ispunct((int)*(tmp+1)) || (int)*(tmp+1)=='\n' ) && block_end block_start) { ++ while ((_isblank((int)*tmp) || ispunct((unsigned char)*tmp)) && *tmp!='/' && *tmp!='-' && block_end > block_start) { + tmp--; + block_end--; + } +@@ -5113,7 +5117,7 @@ int php_tag_find(char *tag, size_t len, const char *set) { + done =1; + break; + default: +- if (!isspace((int)c)) { ++ if (!isspace((unsigned char)c)) { + if (state == 0) { + state=1; + } +@@ -5215,7 +5219,7 @@ state_0: + if (in_q) { + break; + } +- if (isspace(*(p + 1)) && !allow_tag_spaces) { ++ if (isspace((unsigned char)p[1]) && !allow_tag_spaces) { + *(rp++) = c; + break; + } +@@ -5262,7 +5266,7 @@ state_1: + if (in_q) { + break; + } +- if (isspace(*(p + 1)) && !allow_tag_spaces) { ++ if (isspace((unsigned char)p[1]) && !allow_tag_spaces) { + goto reg_char_1; + } + depth++; +diff --git a/ext/standard/strnatcmp.c b/ext/standard/strnatcmp.c +index 72ed5e1..dc091b4 100644 +--- a/ext/standard/strnatcmp.c ++++ b/ext/standard/strnatcmp.c +@@ -41,12 +41,12 @@ compare_right(char const **a, char const *aend, char const **b, char const *bend + both numbers to know that they have the same magnitude, so we + remember it in BIAS. */ + for(;; (*a)++, (*b)++) { +- if ((*a == aend || !isdigit((int)(unsigned char)**a)) && +- (*b == bend || !isdigit((int)(unsigned char)**b))) ++ if ((*a == aend || !isdigit((unsigned char)**a)) && ++ (*b == bend || !isdigit((unsigned char)**b))) + return bias; +- else if (*a == aend || !isdigit((int)(unsigned char)**a)) ++ else if (*a == aend || !isdigit((unsigned char)**a)) + return -1; +- else if (*b == bend || !isdigit((int)(unsigned char)**b)) ++ else if (*b == bend || !isdigit((unsigned char)**b)) + return +1; + else if (**a < **b) { + if (!bias) +@@ -69,12 +69,12 @@ compare_left(char const **a, char const *aend, char const **b, char const *bend) + /* Compare two left-aligned numbers: the first to have a + different value wins. */ + for(;; (*a)++, (*b)++) { +- if ((*a == aend || !isdigit((int)(unsigned char)**a)) && +- (*b == bend || !isdigit((int)(unsigned char)**b))) ++ if ((*a == aend || !isdigit((unsigned char)**a)) && ++ (*b == bend || !isdigit((unsigned char)**b))) + return 0; +- else if (*a == aend || !isdigit((int)(unsigned char)**a)) ++ else if (*a == aend || !isdigit((unsigned char)**a)) + return -1; +- else if (*b == bend || !isdigit((int)(unsigned char)**b)) ++ else if (*b == bend || !isdigit((unsigned char)**b)) + return +1; + else if (**a < **b) + return -1; +@@ -107,27 +107,27 @@ PHPAPI int strnatcmp_ex(char const *a, size_t a_len, char const *b, size_t b_len + ca = *ap; cb = *bp; + + /* skip over leading zeros */ +- while (leading && ca == '0' && (ap+1 < aend) && isdigit((int)(unsigned char)*(ap+1))) { ++ while (leading && ca == '0' && (ap+1 < aend) && isdigit((unsigned char)ap[1])) { + ca = *++ap; + } + +- while (leading && cb == '0' && (bp+1 < bend) && isdigit((int)(unsigned char)*(bp+1))) { ++ while (leading && cb == '0' && (bp+1 < bend) && isdigit((unsigned char)bp[1])) { + cb = *++bp; + } + + leading = 0; + + /* Skip consecutive whitespace */ +- while (isspace((int)(unsigned char)ca)) { ++ while (isspace(ca)) { + ca = *++ap; + } + +- while (isspace((int)(unsigned char)cb)) { ++ while (isspace(cb)) { + cb = *++bp; + } + + /* process run of digits */ +- if (isdigit((int)(unsigned char)ca) && isdigit((int)(unsigned char)cb)) { ++ if (isdigit(ca) && isdigit(cb)) { + fractional = (ca == '0' || cb == '0'); + + if (fractional) +@@ -151,8 +151,8 @@ PHPAPI int strnatcmp_ex(char const *a, size_t a_len, char const *b, size_t b_len + } + + if (fold_case) { +- ca = toupper((int)(unsigned char)ca); +- cb = toupper((int)(unsigned char)cb); ++ ca = toupper(ca); ++ cb = toupper(cb); + } + + if (ca < cb) +diff --git a/ext/standard/tests/GHSA-96wq-48vp-hh57.phpt b/ext/standard/tests/GHSA-96wq-48vp-hh57.phpt +new file mode 100644 +index 0000000..cf9a400 +--- /dev/null ++++ b/ext/standard/tests/GHSA-96wq-48vp-hh57.phpt +@@ -0,0 +1,22 @@ ++--TEST-- ++GHSA-96wq-48vp-hh57: signed integer overflow of char array offset ++--CREDITS-- ++Aleksey Solovev (Positive Technologies) ++--INI-- ++memory_limit=3G ++--SKIPIF-- ++ ++--FILE-- ++ ++===DONE=== ++--EXPECT-- ++===DONE=== +diff --git a/ext/standard/tests/array/GHSA-h96m-rvf9-jgm2.phpt b/ext/standard/tests/array/GHSA-h96m-rvf9-jgm2.phpt +new file mode 100644 +index 0000000..2e3e853 +--- /dev/null ++++ b/ext/standard/tests/array/GHSA-h96m-rvf9-jgm2.phpt +@@ -0,0 +1,16 @@ ++--TEST-- ++GHSA-h96m-rvf9-jgm2 ++--FILE-- ++getMessage(), "\n"; ++} ++ ++?> ++--EXPECTF-- ++The total number of elements must be lower than %d +diff --git a/ext/standard/tests/crypt/bcrypt_salt_dollar.phpt b/ext/standard/tests/crypt/bcrypt_salt_dollar.phpt +new file mode 100644 +index 0000000..32e335f +--- /dev/null ++++ b/ext/standard/tests/crypt/bcrypt_salt_dollar.phpt +@@ -0,0 +1,82 @@ ++--TEST-- ++bcrypt correctly rejects salts containing $ ++--FILE-- ++ ++--EXPECT-- ++string(8) "$2y$04$$" ++string(2) "*0" ++bool(false) ++string(9) "$2y$04$0$" ++string(2) "*0" ++bool(false) ++string(10) "$2y$04$00$" ++string(2) "*0" ++bool(false) ++string(11) "$2y$04$000$" ++string(2) "*0" ++bool(false) ++string(12) "$2y$04$0000$" ++string(2) "*0" ++bool(false) ++string(13) "$2y$04$00000$" ++string(2) "*0" ++bool(false) ++string(14) "$2y$04$000000$" ++string(2) "*0" ++bool(false) ++string(15) "$2y$04$0000000$" ++string(2) "*0" ++bool(false) ++string(16) "$2y$04$00000000$" ++string(2) "*0" ++bool(false) ++string(17) "$2y$04$000000000$" ++string(2) "*0" ++bool(false) ++string(18) "$2y$04$0000000000$" ++string(2) "*0" ++bool(false) ++string(19) "$2y$04$00000000000$" ++string(2) "*0" ++bool(false) ++string(20) "$2y$04$000000000000$" ++string(2) "*0" ++bool(false) ++string(21) "$2y$04$0000000000000$" ++string(2) "*0" ++bool(false) ++string(22) "$2y$04$00000000000000$" ++string(2) "*0" ++bool(false) ++string(23) "$2y$04$000000000000000$" ++string(2) "*0" ++bool(false) ++string(24) "$2y$04$0000000000000000$" ++string(2) "*0" ++bool(false) ++string(25) "$2y$04$00000000000000000$" ++string(2) "*0" ++bool(false) ++string(26) "$2y$04$000000000000000000$" ++string(2) "*0" ++bool(false) ++string(27) "$2y$04$0000000000000000000$" ++string(2) "*0" ++bool(false) ++string(28) "$2y$04$00000000000000000000$" ++string(2) "*0" ++bool(false) ++string(29) "$2y$04$000000000000000000000$" ++string(2) "*0" ++bool(false) ++string(30) "$2y$04$0000000000000000000000$" ++string(60) "$2y$04$000000000000000000000u2a2UpVexIt9k3FMJeAVr3c04F5tcI8K" ++bool(false) +diff --git a/ext/standard/tests/file/ghsa-9f67-6fw4-hpfp-win32.phpt b/ext/standard/tests/file/ghsa-9f67-6fw4-hpfp-win32.phpt +new file mode 100644 +index 0000000..d83260e +--- /dev/null ++++ b/ext/standard/tests/file/ghsa-9f67-6fw4-hpfp-win32.phpt +@@ -0,0 +1,86 @@ ++--TEST-- ++GHSA-9f67-6fw4-hpfp: Windows reserved device names are rejected in filesystem paths ++--SKIPIF-- ++ ++--FILE-- ++ ++--EXPECT-- ++Bare device names keep working: ++bool(true) ++bool(true) ++bool(true) ++Reserved names in paths are rejected: ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(false) ++bool(true) ++bool(true) ++bool(true) ++bool(true) ++bool(true) ++Similar names are fine: ++bool(true) ++bool(true) ++bool(true) ++bool(true) ++bool(true) ++bool(true) ++bool(true) +diff --git a/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt b/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt +new file mode 100644 +index 0000000..84a85da +--- /dev/null ++++ b/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt +@@ -0,0 +1,27 @@ ++--TEST-- ++GHSA-88hq-2827-7pg6: OOB read in convert stream filters when line-break-chars contains NUL ++--FILE-- ++ 4, "line-break-chars" => "\0X"]; ++$fp = fopen("php://temp", "r+"); ++fwrite($fp, str_repeat("A", 6)); ++rewind($fp); ++stream_filter_append($fp, "convert.base64-encode", STREAM_FILTER_READ, $opts); ++$out = stream_get_contents($fp); ++fclose($fp); ++ ++// base64("AAAAAA") = "QUFBQUFB" (8 chars) ++// With line-length=4: "QUFB" + "\0X" + "QUFB" ++// Hex: 5155464200585155 4642 ++echo bin2hex($out), "\n"; ++ ++echo "Done\n"; ++ ++?> ++--EXPECT-- ++51554642005851554642 ++Done +diff --git a/ext/standard/tests/filters/ghsa-r977-prxv-hc43.phpt b/ext/standard/tests/filters/ghsa-r977-prxv-hc43.phpt +new file mode 100644 +index 0000000..8fdcce8 +--- /dev/null ++++ b/ext/standard/tests/filters/ghsa-r977-prxv-hc43.phpt +@@ -0,0 +1,12 @@ ++--TEST-- ++GHSA-r977-prxv-hc43: Single byte overread with convert.quoted-printable-decode filter ++--FILE-- ++ ++--EXPECT-- ++string(8190) "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAX" +diff --git a/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_001.phpt b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_001.phpt +new file mode 100644 +index 0000000..0a88d6b +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_001.phpt +@@ -0,0 +1,58 @@ ++--TEST-- ++GHSA-9fcc-425m-g385 - bypass CVE-2024-1874 - batch file variation ++--SKIPIF-- ++ ++--XFAIL-- ++Before PHP 8.0.0 we would need to add extra quotes. ++--FILE-- ++ ++--EXPECTF-- ++'"%sghsa-9fcc-425m-g385_001.bat."' is not recognized as an internal or external command, ++operable program or batch file. ++%sghsa-9fcc-425m-g385_001.bat ++"¬epad.exe ++%sghsa-9fcc-425m-g385_001.bat. ++"¬epad.exe ++%sghsa-9fcc-425m-g385_001.bat. ... ++"¬epad.exe ++%sghsa-9fcc-425m-g385_001.bat. ... . ++"¬epad.exe ++'"%sghsa-9fcc-425m-g385_001.bat. ... . ."' is not recognized as an internal or external command, ++operable program or batch file. ++ ++Warning: proc_open(): CreateProcess failed, error code: 2 in %s on line %d ++--CLEAN-- ++ +diff --git a/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_002.phpt b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_002.phpt +new file mode 100644 +index 0000000..6fbb420 +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_002.phpt +@@ -0,0 +1,68 @@ ++--TEST-- ++GHSA-9fcc-425m-g385 - bypass CVE-2024-1874 - cmd.exe variation ++--SKIPIF-- ++ ++--XFAIL-- ++Before PHP 8.0.0 we would need to add extra quotes. ++--FILE-- ++ ++--EXPECTF-- ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++ ++Warning: proc_open(): CreateProcess failed, error code: 2 in %s on line %d ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++%sghsa-9fcc-425m-g385_002.bat ++"¬epad.exe ++ ++Warning: proc_open(): CreateProcess failed, error code: 2 in %s on line %d ++ ++Warning: proc_open(): CreateProcess failed, error code: 2 in %s on line %d ++ ++Warning: proc_open(): CreateProcess failed, error code: 2 in %s on line %d ++--CLEAN-- ++ +diff --git a/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_003.phpt b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_003.phpt +new file mode 100644 +index 0000000..038db4f +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-9fcc-425m-g385_003.phpt +@@ -0,0 +1,552 @@ ++--TEST-- ++GHSA-9fcc-425m-g385 - bypass CVE-2024-1874 - exhaustive suffix test ++--SKIPIF-- ++ ++--XFAIL-- ++Before PHP 8.0.0 we would need to add extra quotes. ++--FILE-- ++ true)); ++ var_dump($proc); ++ proc_close($proc); ++ } catch (Error) {} ++} ++ ++?> ++--EXPECTF-- ++Testing 1 ++bool(false) ++Testing 2 ++bool(false) ++Testing 3 ++bool(false) ++Testing 4 ++bool(false) ++Testing 5 ++bool(false) ++Testing 6 ++bool(false) ++Testing 7 ++bool(false) ++Testing 8 ++bool(false) ++Testing 9 ++bool(false) ++Testing 10 ++bool(false) ++Testing 11 ++bool(false) ++Testing 12 ++bool(false) ++Testing 13 ++bool(false) ++Testing 14 ++bool(false) ++Testing 15 ++bool(false) ++Testing 16 ++bool(false) ++Testing 17 ++bool(false) ++Testing 18 ++bool(false) ++Testing 19 ++bool(false) ++Testing 20 ++bool(false) ++Testing 21 ++bool(false) ++Testing 22 ++bool(false) ++Testing 23 ++bool(false) ++Testing 24 ++bool(false) ++Testing 25 ++bool(false) ++Testing 26 ++bool(false) ++Testing 27 ++bool(false) ++Testing 28 ++bool(false) ++Testing 29 ++bool(false) ++Testing 30 ++bool(false) ++Testing 31 ++bool(false) ++Testing 32 ++resource(%d) of type (process) ++%s.bat ++"¬epad.exe ++Testing 33 ++bool(false) ++Testing 34 ++bool(false) ++Testing 35 ++bool(false) ++Testing 36 ++bool(false) ++Testing 37 ++bool(false) ++Testing 38 ++bool(false) ++Testing 39 ++bool(false) ++Testing 40 ++bool(false) ++Testing 41 ++bool(false) ++Testing 42 ++bool(false) ++Testing 43 ++bool(false) ++Testing 44 ++bool(false) ++Testing 45 ++bool(false) ++Testing 46 ++resource(%d) of type (process) ++'"%s.bat."' is not recognized as an internal or external command, ++operable program or batch file. ++Testing 47 ++bool(false) ++Testing 48 ++bool(false) ++Testing 49 ++bool(false) ++Testing 50 ++bool(false) ++Testing 51 ++bool(false) ++Testing 52 ++bool(false) ++Testing 53 ++bool(false) ++Testing 54 ++bool(false) ++Testing 55 ++bool(false) ++Testing 56 ++bool(false) ++Testing 57 ++bool(false) ++Testing 58 ++bool(false) ++Testing 59 ++bool(false) ++Testing 60 ++bool(false) ++Testing 61 ++bool(false) ++Testing 62 ++bool(false) ++Testing 63 ++bool(false) ++Testing 64 ++bool(false) ++Testing 65 ++bool(false) ++Testing 66 ++bool(false) ++Testing 67 ++bool(false) ++Testing 68 ++bool(false) ++Testing 69 ++bool(false) ++Testing 70 ++bool(false) ++Testing 71 ++bool(false) ++Testing 72 ++bool(false) ++Testing 73 ++bool(false) ++Testing 74 ++bool(false) ++Testing 75 ++bool(false) ++Testing 76 ++bool(false) ++Testing 77 ++bool(false) ++Testing 78 ++bool(false) ++Testing 79 ++bool(false) ++Testing 80 ++bool(false) ++Testing 81 ++bool(false) ++Testing 82 ++bool(false) ++Testing 83 ++bool(false) ++Testing 84 ++bool(false) ++Testing 85 ++bool(false) ++Testing 86 ++bool(false) ++Testing 87 ++bool(false) ++Testing 88 ++bool(false) ++Testing 89 ++bool(false) ++Testing 90 ++bool(false) ++Testing 91 ++bool(false) ++Testing 92 ++bool(false) ++Testing 93 ++bool(false) ++Testing 94 ++bool(false) ++Testing 95 ++bool(false) ++Testing 96 ++bool(false) ++Testing 97 ++bool(false) ++Testing 98 ++bool(false) ++Testing 99 ++bool(false) ++Testing 100 ++bool(false) ++Testing 101 ++bool(false) ++Testing 102 ++bool(false) ++Testing 103 ++bool(false) ++Testing 104 ++bool(false) ++Testing 105 ++bool(false) ++Testing 106 ++bool(false) ++Testing 107 ++bool(false) ++Testing 108 ++bool(false) ++Testing 109 ++bool(false) ++Testing 110 ++bool(false) ++Testing 111 ++bool(false) ++Testing 112 ++bool(false) ++Testing 113 ++bool(false) ++Testing 114 ++bool(false) ++Testing 115 ++bool(false) ++Testing 116 ++bool(false) ++Testing 117 ++bool(false) ++Testing 118 ++bool(false) ++Testing 119 ++bool(false) ++Testing 120 ++bool(false) ++Testing 121 ++bool(false) ++Testing 122 ++bool(false) ++Testing 123 ++bool(false) ++Testing 124 ++bool(false) ++Testing 125 ++bool(false) ++Testing 126 ++bool(false) ++Testing 127 ++bool(false) ++Testing 128 ++bool(false) ++Testing 129 ++bool(false) ++Testing 130 ++bool(false) ++Testing 131 ++bool(false) ++Testing 132 ++bool(false) ++Testing 133 ++bool(false) ++Testing 134 ++bool(false) ++Testing 135 ++bool(false) ++Testing 136 ++bool(false) ++Testing 137 ++bool(false) ++Testing 138 ++bool(false) ++Testing 139 ++bool(false) ++Testing 140 ++bool(false) ++Testing 141 ++bool(false) ++Testing 142 ++bool(false) ++Testing 143 ++bool(false) ++Testing 144 ++bool(false) ++Testing 145 ++bool(false) ++Testing 146 ++bool(false) ++Testing 147 ++bool(false) ++Testing 148 ++bool(false) ++Testing 149 ++bool(false) ++Testing 150 ++bool(false) ++Testing 151 ++bool(false) ++Testing 152 ++bool(false) ++Testing 153 ++bool(false) ++Testing 154 ++bool(false) ++Testing 155 ++bool(false) ++Testing 156 ++bool(false) ++Testing 157 ++bool(false) ++Testing 158 ++bool(false) ++Testing 159 ++bool(false) ++Testing 160 ++bool(false) ++Testing 161 ++bool(false) ++Testing 162 ++bool(false) ++Testing 163 ++bool(false) ++Testing 164 ++bool(false) ++Testing 165 ++bool(false) ++Testing 166 ++bool(false) ++Testing 167 ++bool(false) ++Testing 168 ++bool(false) ++Testing 169 ++bool(false) ++Testing 170 ++bool(false) ++Testing 171 ++bool(false) ++Testing 172 ++bool(false) ++Testing 173 ++bool(false) ++Testing 174 ++bool(false) ++Testing 175 ++bool(false) ++Testing 176 ++bool(false) ++Testing 177 ++bool(false) ++Testing 178 ++bool(false) ++Testing 179 ++bool(false) ++Testing 180 ++bool(false) ++Testing 181 ++bool(false) ++Testing 182 ++bool(false) ++Testing 183 ++bool(false) ++Testing 184 ++bool(false) ++Testing 185 ++bool(false) ++Testing 186 ++bool(false) ++Testing 187 ++bool(false) ++Testing 188 ++bool(false) ++Testing 189 ++bool(false) ++Testing 190 ++bool(false) ++Testing 191 ++bool(false) ++Testing 192 ++bool(false) ++Testing 193 ++bool(false) ++Testing 194 ++bool(false) ++Testing 195 ++bool(false) ++Testing 196 ++bool(false) ++Testing 197 ++bool(false) ++Testing 198 ++bool(false) ++Testing 199 ++bool(false) ++Testing 200 ++bool(false) ++Testing 201 ++bool(false) ++Testing 202 ++bool(false) ++Testing 203 ++bool(false) ++Testing 204 ++bool(false) ++Testing 205 ++bool(false) ++Testing 206 ++bool(false) ++Testing 207 ++bool(false) ++Testing 208 ++bool(false) ++Testing 209 ++bool(false) ++Testing 210 ++bool(false) ++Testing 211 ++bool(false) ++Testing 212 ++bool(false) ++Testing 213 ++bool(false) ++Testing 214 ++bool(false) ++Testing 215 ++bool(false) ++Testing 216 ++bool(false) ++Testing 217 ++bool(false) ++Testing 218 ++bool(false) ++Testing 219 ++bool(false) ++Testing 220 ++bool(false) ++Testing 221 ++bool(false) ++Testing 222 ++bool(false) ++Testing 223 ++bool(false) ++Testing 224 ++bool(false) ++Testing 225 ++bool(false) ++Testing 226 ++bool(false) ++Testing 227 ++bool(false) ++Testing 228 ++bool(false) ++Testing 229 ++bool(false) ++Testing 230 ++bool(false) ++Testing 231 ++bool(false) ++Testing 232 ++bool(false) ++Testing 233 ++bool(false) ++Testing 234 ++bool(false) ++Testing 235 ++bool(false) ++Testing 236 ++bool(false) ++Testing 237 ++bool(false) ++Testing 238 ++bool(false) ++Testing 239 ++bool(false) ++Testing 240 ++bool(false) ++Testing 241 ++bool(false) ++Testing 242 ++bool(false) ++Testing 243 ++bool(false) ++Testing 244 ++bool(false) ++Testing 245 ++bool(false) ++Testing 246 ++bool(false) ++Testing 247 ++bool(false) ++Testing 248 ++bool(false) ++Testing 249 ++bool(false) ++Testing 250 ++bool(false) ++Testing 251 ++bool(false) ++Testing 252 ++bool(false) ++Testing 253 ++bool(false) ++Testing 254 ++bool(false) ++Testing 255 ++bool(false) ++--CLEAN-- ++ +diff --git a/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_1.phpt b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_1.phpt +new file mode 100644 +index 0000000..8d0939c +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_1.phpt +@@ -0,0 +1,29 @@ ++--TEST-- ++GHSA-54hq-v5wp-fqgv - proc_open does not correctly escape args for bat files ++--SKIPIF-- ++ ++--FILE-- ++ ++--EXPECT-- ++"¬epad.exe ++--CLEAN-- ++ +diff --git a/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_2.phpt b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_2.phpt +new file mode 100644 +index 0000000..a1e39d7 +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_2.phpt +@@ -0,0 +1,29 @@ ++--TEST-- ++GHSA-54hq-v5wp-fqgv - proc_open does not correctly escape args for cmd files ++--SKIPIF-- ++ ++--FILE-- ++^()!.exe"], $descriptorspec, $pipes); ++proc_close($proc); ++ ++?> ++--EXPECT-- ++"¬epad<>^()!.exe ++--CLEAN-- ++ +diff --git a/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_3.phpt b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_3.phpt +new file mode 100644 +index 0000000..69f12d7 +--- /dev/null ++++ b/ext/standard/tests/general_functions/ghsa-pc52-254m-w9w7_3.phpt +@@ -0,0 +1,29 @@ ++--TEST-- ++GHSA-54hq-v5wp-fqgv - proc_open does not correctly escape args for cmd executing batch files ++--SKIPIF-- ++ ++--FILE-- ++ ++--EXPECT-- ++"¬epad.exe ++--CLEAN-- ++ +diff --git a/ext/standard/tests/ghsa-wpj3-hf5j-x4v4.phpt b/ext/standard/tests/ghsa-wpj3-hf5j-x4v4.phpt +new file mode 100644 +index 0000000..77fcb68 +--- /dev/null ++++ b/ext/standard/tests/ghsa-wpj3-hf5j-x4v4.phpt +@@ -0,0 +1,63 @@ ++--TEST-- ++ghsa-wpj3-hf5j-x4v4 (__Host-/__Secure- cookie bypass due to partial CVE-2022-31629 fix) ++--COOKIE-- ++..Host-test=ignore_1; ++._Host-test=ignore_2; ++.[Host-test=ignore_3; ++_.Host-test=ignore_4; ++__Host-test=ignore_5; ++_[Host-test=ignore_6; ++[.Host-test=ignore_7; ++[_Host-test=ignore_8; ++[[Host-test=ignore_9; ++..Host-test[]=ignore_10; ++._Host-test[]=ignore_11; ++.[Host-test[]=ignore_12; ++_.Host-test[]=ignore_13; ++__Host-test[]=legitimate_14; ++_[Host-test[]=legitimate_15; ++[.Host-test[]=ignore_16; ++[_Host-test[]=ignore_17; ++[[Host-test[]=ignore_18; ++..Secure-test=ignore_1; ++._Secure-test=ignore_2; ++.[Secure-test=ignore_3; ++_.Secure-test=ignore_4; ++__Secure-test=ignore_5; ++_[Secure-test=ignore_6; ++[.Secure-test=ignore_7; ++[_Secure-test=ignore_8; ++[[Secure-test=ignore_9; ++..Secure-test[]=ignore_10; ++._Secure-test[]=ignore_11; ++.[Secure-test[]=ignore_12; ++_.Secure-test[]=ignore_13; ++__Secure-test[]=legitimate_14; ++_[Secure-test[]=legitimate_15; ++[.Secure-test[]=ignore_16; ++[_Secure-test[]=ignore_17; ++[[Secure-test[]=ignore_18; ++--FILE-- ++ ++--EXPECT-- ++array(3) { ++ ["__Host-test"]=> ++ array(1) { ++ [0]=> ++ string(13) "legitimate_14" ++ } ++ ["_"]=> ++ array(2) { ++ ["Host-test["]=> ++ string(13) "legitimate_15" ++ ["Secure-test["]=> ++ string(13) "legitimate_15" ++ } ++ ["__Secure-test"]=> ++ array(1) { ++ [0]=> ++ string(13) "legitimate_14" ++ } ++} +diff --git a/ext/standard/tests/http/ServerClientTestCase.inc b/ext/standard/tests/http/ServerClientTestCase.inc +new file mode 100644 +index 0000000..c74da44 +--- /dev/null ++++ b/ext/standard/tests/http/ServerClientTestCase.inc +@@ -0,0 +1,199 @@ ++notify($worker, $message); ++} ++ ++function phpt_wait($worker = WORKER_DEFAULT_NAME, $timeout = null): ?string ++{ ++ return ServerClientTestCase::getInstance()->wait($worker, $timeout); ++} ++ ++function phpt_notify_server_start($server): void ++{ ++ ServerClientTestCase::getInstance()->notify_server_start($server); ++} ++ ++function phpt_has_sslv3() { ++ static $result = null; ++ if (!is_null($result)) { ++ return $result; ++ } ++ $server = @stream_socket_server('sslv3://127.0.0.1:10013'); ++ if ($result = !!$server) { ++ fclose($server); ++ } ++ return $result; ++} ++ ++/** ++ * This is a singleton to let the wait/notify functions work ++ * I know it's horrible, but it's a means to an end ++ */ ++class ServerClientTestCase ++{ ++ private $isWorker = false; ++ ++ private $workerHandle = []; ++ ++ private $workerStdIn = []; ++ ++ private $workerStdOut = []; ++ ++ private static $instance; ++ ++ public static function getInstance($isWorker = false) ++ { ++ if (!isset(self::$instance)) { ++ self::$instance = new self($isWorker); ++ } ++ ++ return self::$instance; ++ } ++ ++ public function __construct($isWorker = false) ++ { ++ if (!isset(self::$instance)) { ++ self::$instance = $this; ++ } ++ ++ $this->isWorker = $isWorker; ++ } ++ ++ private function spawnWorkerProcess($worker, $code) ++ { ++ if (defined("PHP_WINDOWS_VERSION_MAJOR")) { ++ $ini = php_ini_loaded_file(); ++ $cmd = sprintf( ++ '%s %s "%s" %s', ++ PHP_BINARY, $ini ? "-n -c $ini" : "", ++ __FILE__, ++ WORKER_ARGV_VALUE ++ ); ++ } else { ++ $cmd = sprintf( ++ '%s "%s" %s %s', ++ PHP_BINARY, ++ __FILE__, ++ WORKER_ARGV_VALUE, ++ $worker ++ ); ++ } ++ $this->workerHandle[$worker] = proc_open( ++ $cmd, ++ [['pipe', 'r'], ['pipe', 'w'], STDERR], ++ $pipes ++ ); ++ $this->workerStdIn[$worker] = $pipes[0]; ++ $this->workerStdOut[$worker] = $pipes[1]; ++ ++ fwrite($this->workerStdIn[$worker], $code . "\n---\n"); ++ } ++ ++ private function cleanupWorkerProcess($worker) ++ { ++ fclose($this->workerStdIn[$worker]); ++ fclose($this->workerStdOut[$worker]); ++ proc_close($this->workerHandle[$worker]); ++ } ++ ++ private function stripPhpTagsFromCode($code) ++ { ++ return preg_replace('/^\s*<\?(?:php)?|\?>\s*$/i', '', $code); ++ } ++ ++ public function runWorker() ++ { ++ $code = ''; ++ ++ while (1) { ++ $line = fgets(STDIN); ++ ++ if (trim($line) === "---") { ++ break; ++ } ++ ++ $code .= $line; ++ } ++ ++ eval($code); ++ } ++ ++ /** ++ * Run client and all workers ++ * ++ * @param string $clientCode The client PHP code ++ * @param string|array $workerCode ++ * @param bool $ephemeral Select whether automatic port selection and automatic awaiting is used ++ * @return void ++ * @throws Exception ++ */ ++ public function run(string $clientCode, $workerCode, bool $ephemeral = true): void ++ { ++ if (!is_array($workerCode)) { ++ $workerCode = [WORKER_DEFAULT_NAME => $workerCode]; ++ } ++ reset($workerCode); ++ $code = current($workerCode); ++ $worker = key($workerCode); ++ while ($worker != null) { ++ $this->spawnWorkerProcess($worker, $this->stripPhpTagsFromCode($code)); ++ $code = next($workerCode); ++ if ($ephemeral) { ++ $addr = trim($this->wait($worker)); ++ if (empty($addr)) { ++ throw new \Exception("Failed server start"); ++ } ++ if ($code === false) { ++ $clientCode = preg_replace('/{{\s*ADDR\s*}}/', $addr, $clientCode); ++ } else { ++ $code = preg_replace('/{{\s*ADDR\s*}}/', $addr, $code); ++ } ++ } ++ $worker = key($workerCode); ++ } ++ ++ eval($this->stripPhpTagsFromCode($clientCode)); ++ foreach ($workerCode as $worker => $code) { ++ $this->cleanupWorkerProcess($worker); ++ } ++ } ++ ++ public function wait($worker, $timeout = null): ?string ++ { ++ $handle = $this->isWorker ? STDIN : $this->workerStdOut[$worker]; ++ if ($timeout === null) { ++ return fgets($handle); ++ } ++ ++ stream_set_blocking($handle, false); ++ $read = [$handle]; ++ $result = stream_select($read, $write, $except, $timeout); ++ if (!$result) { ++ return null; ++ } ++ ++ $result = fgets($handle); ++ stream_set_blocking($handle, true); ++ return $result; ++ } ++ ++ public function notify(string $worker, string $message = ""): void ++ { ++ fwrite($this->isWorker ? STDOUT : $this->workerStdIn[$worker], "$message\n"); ++ } ++ ++ public function notify_server_start($server): void ++ { ++ echo stream_socket_get_name($server, false) . "\n"; ++ } ++} ++ ++if (isset($argv[1]) && $argv[1] === WORKER_ARGV_VALUE) { ++ ServerClientTestCase::getInstance(true)->runWorker(); ++} +diff --git a/ext/standard/tests/http/bug47021.phpt b/ext/standard/tests/http/bug47021.phpt +index f3db3e1..a287b71 100644 +--- a/ext/standard/tests/http/bug47021.phpt ++++ b/ext/standard/tests/http/bug47021.phpt +@@ -47,9 +47,9 @@ function do_test($num_spaces, $leave_trailing_space=false) { + ]; + $pid = http_server('tcp://127.0.0.1:12342', $responses); + +- echo file_get_contents('http://127.0.0.1:12342/', false, $ctx); ++ echo file_get_contents('http://127.0.0.1:12342', false, $ctx); + echo "\n"; +- echo file_get_contents('http://127.0.0.1:12342/', false, $ctx); ++ echo file_get_contents('http://127.0.0.1:12342', false, $ctx); + echo "\n"; + + http_server_kill($pid); +@@ -70,23 +70,27 @@ do_test(1, true); + echo "\n"; + + ?> +---EXPECT-- ++--EXPECTF-- ++ + Type='text/plain' + Hello +-Size=5 +-World ++ ++Warning: file_get_contents(http://%s:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s ++ + + Type='text/plain' + Hello +-Size=5 +-World ++ ++Warning: file_get_contents(http://%s:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s ++ + + Type='text/plain' + Hello +-Size=5 +-World ++ ++Warning: file_get_contents(http://%s:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s ++ + + Type='text/plain' + Hello +-Size=5 +-World ++ ++Warning: file_get_contents(http://%s:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s +diff --git a/ext/standard/tests/http/bug61548.phpt b/ext/standard/tests/http/bug61548.phpt +index 38b2bbf..b4b7079 100644 +--- a/ext/standard/tests/http/bug61548.phpt ++++ b/ext/standard/tests/http/bug61548.phpt +@@ -55,7 +55,6 @@ Connection: close + First:1 + Second:2 + +- + POST / HTTP/1.0 + Host: 127.0.0.1:12342 + Connection: close +@@ -69,7 +68,6 @@ Connection: close + First:1 + Second:2 + +- + POST / HTTP/1.0 + Host: 127.0.0.1:12342 + Connection: close +diff --git a/ext/standard/tests/http/bug67430.phpt b/ext/standard/tests/http/bug67430.phpt +index a563951..61c7080 100644 +--- a/ext/standard/tests/http/bug67430.phpt ++++ b/ext/standard/tests/http/bug67430.phpt +@@ -41,7 +41,7 @@ POST / HTTP/1.0 + Host: 127.0.0.1:12342 + Connection: close + +-GET /foo HTTP/1.0 ++POST /foo HTTP/1.0 + Host: 127.0.0.1:12342 + Connection: close + +diff --git a/ext/standard/tests/http/bug75535.phpt b/ext/standard/tests/http/bug75535.phpt +index 9bf298c..e3757ba 100644 +--- a/ext/standard/tests/http/bug75535.phpt ++++ b/ext/standard/tests/http/bug75535.phpt +@@ -22,10 +22,8 @@ http_server_kill($pid); + ==DONE== + --EXPECT-- + string(0) "" +-array(2) { ++array(1) { + [0]=> + string(15) "HTTP/1.0 200 Ok" +- [1]=> +- string(14) "Content-Length" + } + ==DONE== +diff --git a/ext/standard/tests/http/gh11274.phpt b/ext/standard/tests/http/gh11274.phpt +new file mode 100644 +index 0000000..fc125bf +--- /dev/null ++++ b/ext/standard/tests/http/gh11274.phpt +@@ -0,0 +1,62 @@ ++--TEST-- ++GH-11274 (POST/PATCH request via file_get_contents + stream_context_create switches to GET after a HTTP 308 redirect) ++--INI-- ++allow_url_fopen=1 ++--CONFLICTS-- ++server ++--FILE-- ++ ['method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]])); ++ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test$suffix", false, stream_context_create(['http' => ['method' => 'PATCH', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]])); ++ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test/$suffix", false, stream_context_create(['http' => ['method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]])); ++ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test/$suffix", false, stream_context_create(['http' => ['method' => 'PATCH', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]])); ++} ++?> ++--EXPECT-- ++-- Testing unredirected request -- ++method: POST; body: hello=world ++method: PATCH; body: hello=world ++method: POST; body: hello=world ++method: PATCH; body: hello=world ++-- Testing redirect status code 301 -- ++method: GET; body: ++method: GET; body: ++method: GET; body: ++method: GET; body: ++-- Testing redirect status code 302 -- ++method: GET; body: ++method: GET; body: ++method: GET; body: ++method: GET; body: ++-- Testing redirect status code 307 -- ++method: POST; body: hello=world ++method: PATCH; body: hello=world ++method: POST; body: hello=world ++method: PATCH; body: hello=world ++-- Testing redirect status code 308 -- ++method: POST; body: hello=world ++method: PATCH; body: hello=world ++method: POST; body: hello=world ++method: PATCH; body: hello=world +diff --git a/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt +new file mode 100644 +index 0000000..3475a03 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt +@@ -0,0 +1,58 @@ ++--TEST-- ++GHSA-52jp-hrpf-2jff: HTTP stream wrapper truncate redirect location to 1024 bytes (success) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ $loc = str_repeat("y", 8000); ++ fwrite($conn, "HTTP/1.0 301 Ok\r\nContent-Type: text/html;\r\nLocation: $loc\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ case STREAM_NOTIFY_REDIRECTED: ++ echo "Redirected: "; ++ var_dump($message); ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html; ++Redirected: string(8000) "%s" ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: %s ++string(0) "" ++array(3) { ++ [0]=> ++ string(15) "HTTP/1.0 301 Ok" ++ [1]=> ++ string(24) "Content-Type: text/html;" ++ [2]=> ++ string(8010) "Location: %s" ++} +diff --git a/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt +new file mode 100644 +index 0000000..706a85f +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt +@@ -0,0 +1,55 @@ ++--TEST-- ++GHSA-52jp-hrpf-2jff: HTTP stream wrapper truncate redirect location to 1024 bytes (over limit) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ $loc = str_repeat("y", 9000); ++ fwrite($conn, "HTTP/1.0 301 Ok\r\nContent-Type: text/html;\r\nLocation: $loc\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ case STREAM_NOTIFY_REDIRECTED: ++ echo "Redirected: "; ++ var_dump($message); ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html; ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP Location header size is over the limit of 8182 bytes in %s ++string(0) "" ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 301 Ok" ++ [1]=> ++ string(24) "Content-Type: text/html;" ++} +diff --git a/ext/standard/tests/http/ghsa-c5f2-jwm7-mmq2.phpt b/ext/standard/tests/http/ghsa-c5f2-jwm7-mmq2.phpt +new file mode 100644 +index 0000000..5b2e04f +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-c5f2-jwm7-mmq2.phpt +@@ -0,0 +1,28 @@ ++--TEST-- ++GHSA-c5f2-jwm7-mmq2 (Configuring a proxy in a stream context might allow for CRLF injection in URIs) ++--INI-- ++allow_url_fopen=1 ++--CONFLICTS-- ++server ++--FILE-- ++ ['proxy' => 'tcp://' . $host, 'request_fulluri' => true]]); ++echo file_get_contents("http://$host/$userinput", false, $context); ++?> ++--EXPECTF-- ++Warning: file_get_contents(http://localhost:%d/index.php HTTP/1.1 ++Host: localhost:%d ++ ++GET /index2.php HTTP/1.1 ++Host: localhost:%d ++ ++GET /index.php): failed to open stream: HTTP wrapper full URI path does not allow CR or LF characters in %s on line %d +diff --git a/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt b/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt +new file mode 100644 +index 0000000..69b8936 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt +@@ -0,0 +1,159 @@ ++--TEST-- ++GHSA-fpwc-w8rq-cr92: strip credentials from user headers on cross-origin redirect ++--INI-- ++allow_url_fopen=1 ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ 'header' => "Authorization: Bearer SECRET\r\n" ++ . "Cookie: sid=abc\r\n" ++ . "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n" ++ . "X-Custom: keep-me", ++ 'follow_location' => 1, ++]]); ++ ++/* server B listens on a different port than server A, so the hop from A to B is ++ * cross-origin; B then redirects to itself: credentials must stay withheld for ++ * that same-origin hop too */ ++$captureB = null; ++$pidB = http_server("tcp://127.0.0.1:12342", [ ++ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: /second\r\nContent-Length: 0\r\n\r\n", ++ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", ++], $captureB); ++ ++$captureA = null; ++$pidA = http_server("tcp://127.0.0.1:12343", [ ++ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:12342/first\r\nContent-Length: 0\r\n\r\n", ++], $captureA); ++ ++var_dump(file_get_contents("http://127.0.0.1:12343" . '/src', false, $ctx)); ++ ++http_server_kill($pidA); ++http_server_kill($pidB); ++ ++rewind($captureA); ++rewind($captureB); ++report('--- origin A (1 request) ---', stream_get_contents($captureA)); ++report('--- origin B (2 requests) ---', stream_get_contents($captureB)); ++ ++/* same origin throughout: credentials must be sent on both hops */ ++$captureC = null; ++$pidC = http_server("tcp://127.0.0.1:12344", [ ++ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: /next\r\nContent-Length: 0\r\n\r\n", ++ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", ++], $captureC); ++ ++var_dump(file_get_contents( "http://127.0.0.1:12344" . '/first', false, $ctx)); ++ ++http_server_kill($pidC); ++ ++rewind($captureC); ++report('--- origin C (2 requests) ---', stream_get_contents($captureC)); ++ ++/* a stripped header that was last in the bag must not leave a trailing line break ++ * behind, or the request body would be pushed out of the request */ ++$ctx = stream_context_create(['http' => [ ++ 'method' => 'POST', ++ 'content' => 'hello=world', ++ 'header' => "X-Custom: keep-me\r\nAuthorization: Bearer SECRET", ++ 'follow_location' => 1, ++]]); ++ ++$captureH = null; ++$pidH = http_server("tcp://127.0.0.1:12345", [ ++ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", ++], $captureH); ++ ++$captureG = null; ++$pidG = http_server("tcp://127.0.0.1:12346", [ ++ "data://text/plain,HTTP/1.1 307 Temporary Redirect\r\nLocation: http://127.0.0.1:12345/second\r\nContent-Length: 0\r\n\r\n", ++], $captureG); ++ ++var_dump(@file_get_contents("http://127.0.0.1:12346" . '/first', false, $ctx)); ++ ++http_server_kill($pidG); ++http_server_kill($pidH); ++ ++rewind($captureH); ++echo "--- credential header last in the bag (307) ---\n"; ++echo preg_replace('/^Host:.*$/m', 'Host: ...', stream_get_contents($captureH)); ++ ++echo "--- malformed header bags ---\n"; ++foreach ([ ++ 'folded value ' => "Authorization:\r\n Bearer SECRET\r\nX-Custom: keep-me", ++ 'folded value (tab)' => "Authorization:\r\n\tBearer SECRET\r\nX-Custom: keep-me", ++ 'lone CR ' => "X-Custom: keep-me\rAuthorization: Bearer SECRET", ++ 'space before colon' => "Authorization : Bearer SECRET\r\nX-Custom: keep-me", ++ 'tab before colon ' => "Authorization\t: Bearer SECRET\r\nX-Custom: keep-me", ++] as $label => $header) { ++ $ctx = stream_context_create(['http' => ['header' => $header, 'follow_location' => 1]]); ++ ++ $captureF = null; ++ $pidF = http_server("tcp://127.0.0.1:12347", [ ++ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", ++ ], $captureF); ++ ++ $captureE = null; ++ $pidE = http_server("tcp://127.0.0.1:12348", [ ++ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:12347/second\r\nContent-Length: 0\r\n\r\n", ++ ], $captureE); ++ ++ file_get_contents("http://127.0.0.1:12348" . '/first', false, $ctx); ++ ++ http_server_kill($pidE); ++ http_server_kill($pidF); ++ ++ rewind($captureF); ++ $request = stream_get_contents($captureF); ++ printf(" %s SECRET leaked: %d, X-Custom kept: %d\n", $label, ++ strpos($request, 'SECRET')!==false, strpos($request, 'X-Custom')!==false); ++} ++?> ++--EXPECT-- ++string(2) "OK" ++--- origin A (1 request) --- ++ Authorization: 1 ++ Cookie: 1 ++ Proxy-Authorization: 1 ++ X-Custom: 1 ++--- origin B (2 requests) --- ++ Authorization: 0 ++ Cookie: 0 ++ Proxy-Authorization: 0 ++ X-Custom: 2 ++string(2) "OK" ++--- origin C (2 requests) --- ++ Authorization: 2 ++ Cookie: 2 ++ Proxy-Authorization: 2 ++ X-Custom: 2 ++string(2) "OK" ++--- credential header last in the bag (307) --- ++POST /second HTTP/1.0 ++Host: ... ++Connection: close ++Content-Length: 11 ++X-Custom: keep-me ++Content-Type: application/x-www-form-urlencoded ++ ++hello=world--- malformed header bags --- ++ folded value SECRET leaked: 0, X-Custom kept: 1 ++ folded value (tab) SECRET leaked: 0, X-Custom kept: 1 ++ lone CR SECRET leaked: 0, X-Custom kept: 1 ++ space before colon SECRET leaked: 0, X-Custom kept: 1 ++ tab before colon SECRET leaked: 0, X-Custom kept: 1 +diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt +new file mode 100644 +index 0000000..121f077 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt +@@ -0,0 +1,65 @@ ++--TEST-- ++GHSA-hgf5-96fm-v528: Stream HTTP wrapper header check might omit basic auth header (incorrect inside pos) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ $result = fread($conn, 1024); ++ $encoded_result = base64_encode($result); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n"); ++ ++CODE; ++ ++$clientCode = <<<'CODE' ++ $opts = [ ++ "http" => [ ++ "method" => "GET", ++ "header" => "Cookie: foo=bar\nauthorization:x\r\n" ++ ] ++ ]; ++ $ctx = stream_context_create($opts); ++ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx)))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++array(7) { ++ [0]=> ++ string(14) "GET / HTTP/1.%d" ++ [1]=> ++ string(33) "Authorization: Basic dXNlcjpwd2Q=" ++ [2]=> ++ string(21) "Host: 127.0.0.1:%d" ++ [3]=> ++ string(17) "Connection: close" ++ [4]=> ++ string(31) "Cookie: foo=bar ++authorization:x" ++ [5]=> ++ string(0) "" ++ [6]=> ++ string(0) "" ++} ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(38) "Content-Type: text/html; charset=utf-8" ++} +diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt +new file mode 100644 +index 0000000..0d141f9 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt +@@ -0,0 +1,62 @@ ++--TEST-- ++GHSA-hgf5-96fm-v528: Header parser of http stream wrapper does not handle folded headers (correct start pos) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ $result = fread($conn, 1024); ++ $encoded_result = base64_encode($result); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n"); ++ ++CODE; ++ ++$clientCode = <<<'CODE' ++ $opts = [ ++ "http" => [ ++ "method" => "GET", ++ "header" => "Authorization: Bearer x\r\n" ++ ] ++ ]; ++ $ctx = stream_context_create($opts); ++ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx)))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++array(6) { ++ [0]=> ++ string(14) "GET / HTTP/1.%d" ++ [1]=> ++ string(21) "Host: 127.0.0.1:%d" ++ [2]=> ++ string(17) "Connection: close" ++ [3]=> ++ string(23) "Authorization: Bearer x" ++ [4]=> ++ string(0) "" ++ [5]=> ++ string(0) "" ++} ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(38) "Content-Type: text/html; charset=utf-8" ++} +diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt +new file mode 100644 +index 0000000..8041487 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt +@@ -0,0 +1,64 @@ ++--TEST-- ++GHSA-hgf5-96fm-v528: Header parser of http stream wrapper does not handle folded headers (correct middle pos) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ $result = fread($conn, 1024); ++ $encoded_result = base64_encode($result); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n"); ++ ++CODE; ++ ++$clientCode = <<<'CODE' ++ $opts = [ ++ "http" => [ ++ "method" => "GET", ++ "header" => "Cookie: x=y\r\nAuthorization: Bearer x\r\n" ++ ] ++ ]; ++ $ctx = stream_context_create($opts); ++ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx)))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++array(7) { ++ [0]=> ++ string(14) "GET / HTTP/1.%d" ++ [1]=> ++ string(21) "Host: 127.0.0.1:%d" ++ [2]=> ++ string(17) "Connection: close" ++ [3]=> ++ string(11) "Cookie: x=y" ++ [4]=> ++ string(23) "Authorization: Bearer x" ++ [5]=> ++ string(0) "" ++ [6]=> ++ string(0) "" ++} ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(38) "Content-Type: text/html; charset=utf-8" ++} +diff --git a/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt +new file mode 100644 +index 0000000..f491acf +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt +@@ -0,0 +1,51 @@ ++--TEST-- ++GHSA-pcmh-g36c-qc44: Header parser of http stream wrapper does not verify header name and colon (colon) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html\r\nWrong-Header\r\nGood-Header: test\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx)); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s ++bool(false) ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(23) "Content-Type: text/html" ++} +diff --git a/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt +new file mode 100644 +index 0000000..4320b17 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt +@@ -0,0 +1,51 @@ ++--TEST-- ++GHSA-pcmh-g36c-qc44: Header parser of http stream wrapper does not verify header name and colon (name) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html\r\nWrong-Header : test\r\nGood-Header: test\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx)); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (space in header name)! in %s ++bool(false) ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(23) "Content-Type: text/html" ++} +diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt +new file mode 100644 +index 0000000..3f1cc79 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt +@@ -0,0 +1,49 @@ ++--TEST-- ++GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (single) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\n charset=utf-8\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html; charset=utf-8 ++string(4) "body" ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(38) "Content-Type: text/html; charset=utf-8" ++} +diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt +new file mode 100644 +index 0000000..c7c1387 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt +@@ -0,0 +1,51 @@ ++--TEST-- ++GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (multiple) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\nCustom-Header: somevalue;\r\n param1=value1; \r\n param2=value2\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html; ++string(4) "body" ++array(3) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(24) "Content-Type: text/html;" ++ [2]=> ++ string(54) "Custom-Header: somevalue; param1=value1; param2=value2" ++} +diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt +new file mode 100644 +index 0000000..c67663b +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt +@@ -0,0 +1,49 @@ ++--TEST-- ++GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (empty) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\n \r\n charset=utf-8\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx))); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++Found the mime-type: text/html; charset=utf-8 ++string(4) "body" ++array(2) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++ [1]=> ++ string(38) "Content-Type: text/html; charset=utf-8" ++} +diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt +new file mode 100644 +index 0000000..7a59e26 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (first line) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\n Content-Type: text/html;\r\n \r\n charset=utf-8\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx)); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (folding header at the start)! in %s ++bool(false) ++array(1) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++} +diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt +new file mode 100644 +index 0000000..f097762 +--- /dev/null ++++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (CR before header name) ++--FILE-- ++ [ ++ "tcp_nodelay" => true ++ ] ++ ]); ++ ++ $server = stream_socket_server( ++ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt); ++ phpt_notify_server_start($server); ++ ++ $conn = stream_socket_accept($server); ++ ++ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted"); ++ ++ fwrite($conn, "HTTP/1.0 200 Ok\r\n\rIgnored: ignored\r\n\r\nbody\r\n"); ++CODE; ++ ++$clientCode = <<<'CODE' ++ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) { ++ switch($notification_code) { ++ case STREAM_NOTIFY_MIME_TYPE_IS: ++ echo "Found the mime-type: ", $message, PHP_EOL; ++ break; ++ } ++ } ++ ++ $ctx = stream_context_create(); ++ stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); ++ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx)); ++ var_dump($http_response_header); ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECTF-- ++ ++Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid header name (cannot start with CR character)! in %s ++bool(false) ++array(1) { ++ [0]=> ++ string(15) "HTTP/1.0 200 Ok" ++} +diff --git a/ext/standard/tests/http/http_empty_location_redirect.phpt b/ext/standard/tests/http/http_empty_location_redirect.phpt +new file mode 100644 +index 0000000..399c8c6 +--- /dev/null ++++ b/ext/standard/tests/http/http_empty_location_redirect.phpt +@@ -0,0 +1,36 @@ ++--TEST-- ++Empty Location header must not over-read when building the redirect target ++--FILE-- ++ ['follow_location' => 1]]); ++echo @file_get_contents("http://{{ ADDR }}/a/b", false, $ctx), "\n"; ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECT-- ++uri=/ +diff --git a/ext/standard/tests/http/http_response_header_05.phpt b/ext/standard/tests/http/http_response_header_05.phpt +deleted file mode 100644 +index dbdd7b8..0000000 +--- a/ext/standard/tests/http/http_response_header_05.phpt ++++ /dev/null +@@ -1,35 +0,0 @@ +---TEST-- +-$http_reponse_header (whitespace-only "header") +---SKIPIF-- +- +---INI-- +-allow_url_fopen=1 +---FILE-- +- +-==DONE== +---EXPECT-- +-string(4) "Body" +-array(2) { +- [0]=> +- string(15) "HTTP/1.0 200 Ok" +- [1]=> +- string(0) "" +-} +-==DONE== +diff --git a/ext/standard/tests/http/http_single_char_location_redirect.phpt b/ext/standard/tests/http/http_single_char_location_redirect.phpt +new file mode 100644 +index 0000000..7888bae +--- /dev/null ++++ b/ext/standard/tests/http/http_single_char_location_redirect.phpt +@@ -0,0 +1,39 @@ ++--TEST-- ++Single-char relative Location header keeps resolving against the host root (pre-GH-23467 behavior) ++--DESCRIPTION-- ++Not RFC 3986 compliant ("x" against "/a/b" gives "/a/x"), but matches ++PHP's long-standing behavior of resolving against the host root. See GH-23521. ++--FILE-- ++ ['follow_location' => 1]]); ++echo @file_get_contents("http://{{ ADDR }}/a/b", false, $ctx), "\n"; ++CODE; ++ ++include sprintf("%s/ServerClientTestCase.inc", __DIR__); ++ServerClientTestCase::getInstance()->run($clientCode, $serverCode); ++?> ++--EXPECT-- ++uri=/x +diff --git a/ext/standard/tests/http/newserver.inc b/ext/standard/tests/http/newserver.inc +new file mode 100644 +index 0000000..5c63670 +--- /dev/null ++++ b/ext/standard/tests/http/newserver.inc +@@ -0,0 +1,124 @@ ++ $pid, ++ 'uri' => 'http://' . stream_socket_get_name($server, false), ++ ]; ++ } ++ ++ return $server; ++} ++ ++/* Minimal HTTP server with predefined responses. ++ * ++ * $socket_string is the socket to create and listen on (e.g. tcp://127.0.0.1:1234) ++ * $files is an iterable of files or callable generator yielding files. ++ * containing N responses for N expected requests. Server dies after N requests. ++ * $output is a stream on which everything sent by clients is written to ++ */ ++function http_server($files, &$output = null) { ++ ++ if (!is_resource($server = http_server_init($output))) { ++ return $server; ++ } ++ ++ if (is_callable($files)) { ++ $files = $files($server); ++ } ++ ++ foreach($files as $file) { ++ ++ $sock = stream_socket_accept($server); ++ if (!$sock) { ++ exit(1); ++ } ++ ++ // read headers ++ ++ $content_length = 0; ++ ++ stream_set_blocking($sock, false); ++ while (!feof($sock)) { ++ ++ list($r, $w, $e) = array(array($sock), null, null); ++ if (!stream_select($r, $w, $e, 1)) continue; ++ ++ $line = stream_get_line($sock, 8192, "\r\n"); ++ if ($line === '') { ++ fwrite($output, "\r\n"); ++ break; ++ } else if ($line !== false) { ++ fwrite($output, "$line\r\n"); ++ ++ if (preg_match('#^Content-Length\s*:\s*([[:digit:]]+)\s*$#i', $line, $matches)) { ++ $content_length = (int) $matches[1]; ++ } ++ } ++ } ++ stream_set_blocking($sock, true); ++ ++ // read content ++ ++ if ($content_length > 0) { ++ stream_copy_to_stream($sock, $output, $content_length); ++ } ++ ++ // send response ++ ++ $fd = fopen($file, 'rb'); ++ stream_copy_to_stream($fd, $sock); ++ ++ fclose($sock); ++ } ++ ++ exit(0); ++} ++ ++function http_server_sleep($micro_seconds = 500000) ++{ ++ if (!is_resource($server = http_server_init($output))) { ++ return $server; ++ } ++ ++ $sock = stream_socket_accept($server); ++ if (!$sock) { ++ exit(1); ++ } ++ ++ usleep($micro_seconds); ++ ++ fclose($sock); ++ ++ exit(0); ++} ++ ++function http_server_kill(int $pid) { ++ posix_kill($pid, SIGTERM); ++ pcntl_waitpid($pid, $status); ++} +diff --git a/ext/standard/tests/image/gh20584.phpt b/ext/standard/tests/image/gh20584.phpt +new file mode 100644 +index 0000000..d117f21 +--- /dev/null ++++ b/ext/standard/tests/image/gh20584.phpt +@@ -0,0 +1,39 @@ ++--TEST-- ++GH-20584 (Information Leak of Memory) ++--CREDITS-- ++Nikita Sveshnikov (Positive Technologies) ++--FILE-- ++ ++--CLEAN-- ++ ++--EXPECT-- ++bool(true) +diff --git a/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt b/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt +new file mode 100644 +index 0000000..e16d3fa +--- /dev/null ++++ b/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt +@@ -0,0 +1,21 @@ ++--TEST-- ++GHSA-3cr5-j632-f35r: Null byte termination in fsockopen() ++--FILE-- ++ ++--EXPECTF-- ++ ++Warning: fsockopen(): unable to connect to localhost:%d (The hostname must not contain null bytes) in %s ++bool(false) +diff --git a/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt b/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt +new file mode 100644 +index 0000000..b14c8ca +--- /dev/null ++++ b/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt +@@ -0,0 +1,71 @@ ++--TEST-- ++GHSA-www2-q4fc-65wf ++--DESCRIPTION-- ++This is a ZPP test but *keep* this as it is security-sensitive! ++--FILE-- ++getMessage(), "\n"; ++} ++try { ++ dns_get_mx("\0", $out); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ dns_get_record("\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ getprotobyname("\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ getservbyname("\0", "tcp"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ getservbyname("x", "tcp\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ getservbyport(0, "tcp\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ inet_pton("\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++try { ++ ip2long("\0"); ++} catch (ValueError $e) { ++ echo $e->getMessage(), "\n"; ++} ++?> ++--EXPECTF-- ++Warning: dns_check_record() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: dns_get_mx() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: dns_get_record() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: getprotobyname() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: getservbyname() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: getservbyname() expects parameter 2 to be a valid path, string given in %s ++ ++Warning: getservbyport() expects parameter 2 to be a valid path, string given in %s ++ ++Warning: inet_pton() expects parameter 1 to be a valid path, string given in %s ++ ++Warning: ip2long() expects parameter 1 to be a valid path, string given in %s ++ +diff --git a/ext/standard/tests/network/ip_x86_64.phpt b/ext/standard/tests/network/ip_x86_64.phpt +index 3c530b8..2158e28 100644 +--- a/ext/standard/tests/network/ip_x86_64.phpt ++++ b/ext/standard/tests/network/ip_x86_64.phpt +@@ -54,7 +54,7 @@ bool(false) + bool(false) + int(1869573999) + +-Warning: ip2long() expects parameter 1 to be string, array given in %sip_x86_64.php on line %d ++Warning: ip2long() expects parameter 1 to be a valid path, array given in %sip_x86_64.php on line %d + NULL + + Warning: long2ip() expects exactly 1 parameter, 0 given in %sip_x86_64.php on line %d +diff --git a/ext/standard/tests/password/password_bcrypt_errors.phpt b/ext/standard/tests/password/password_bcrypt_errors.phpt +index a082608..f95b726 100644 +--- a/ext/standard/tests/password/password_bcrypt_errors.phpt ++++ b/ext/standard/tests/password/password_bcrypt_errors.phpt +@@ -16,6 +16,8 @@ var_dump(password_hash("foo", PASSWORD_BCRYPT, array("salt" => 123))); + + var_dump(password_hash("foo", PASSWORD_BCRYPT, array("cost" => "foo"))); + ++var_dump(password_hash("null\0password", PASSWORD_BCRYPT)); ++ + ?> + --EXPECTF-- + Warning: password_hash(): Invalid bcrypt cost parameter specified: 3 in %s on line %d +@@ -41,3 +43,7 @@ NULL + + Warning: password_hash(): Invalid bcrypt cost parameter specified: 0 in %s on line %d + NULL ++ ++Warning: password_hash(): Bcrypt password must not contain null character in %s on line %d ++NULL ++ +diff --git a/ext/standard/tests/password/password_bcrypt_short.phpt b/ext/standard/tests/password/password_bcrypt_short.phpt +new file mode 100644 +index 0000000..085bc8a +--- /dev/null ++++ b/ext/standard/tests/password/password_bcrypt_short.phpt +@@ -0,0 +1,8 @@ ++--TEST-- ++Test that password_hash() does not overread buffers when a short hash is passed ++--FILE-- ++ ++--EXPECT-- ++bool(false) +diff --git a/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt b/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt +new file mode 100644 +index 0000000..bc1f34e +--- /dev/null ++++ b/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt +@@ -0,0 +1,26 @@ ++--TEST-- ++GHSA-3cr5-j632-f35r: Null byte termination in stream_socket_client() ++--FILE-- ++ ++--EXPECTF-- ++ ++Warning: stream_socket_client(): unable to connect to tcp://localhost\0.example.com:%d (The hostname must not contain null bytes) in %s ++bool(false) +diff --git a/ext/standard/tests/strings/gh10187.phpt b/ext/standard/tests/strings/gh10187.phpt +new file mode 100644 +index 0000000..b42c95e +--- /dev/null ++++ b/ext/standard/tests/strings/gh10187.phpt +@@ -0,0 +1,8 @@ ++--TEST-- ++GH-10187 (Segfault in stripslashes() with arm64) ++--FILE-- ++ ++--EXPECT-- ++string(15) "1234567890abcde" +diff --git a/ext/standard/type.c b/ext/standard/type.c +index d2e267b..82d7a1b 100644 +--- a/ext/standard/type.c ++++ b/ext/standard/type.c +@@ -121,7 +121,7 @@ PHP_FUNCTION(intval) + char *strval = Z_STRVAL_P(num); + size_t strlen = Z_STRLEN_P(num); + +- while (isspace(*strval) && strlen) { ++ while (isspace((unsigned char)*strval) && strlen) { + strval++; + strlen--; + } +diff --git a/ext/standard/url.c b/ext/standard/url.c +index eaad48a..900523e 100644 +--- a/ext/standard/url.c ++++ b/ext/standard/url.c +@@ -124,7 +124,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, zend_bool *has + p = s; + while (p < e) { + /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */ +- if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') { ++ if (!isalpha((unsigned char)*p) && !isdigit((unsigned char)*p) && *p != '+' && *p != '.' && *p != '-') { + if (e + 1 < ue && e < binary_strcspn(s, ue, "?#")) { + goto parse_port; + } else if (s + 1 < ue && *s == '/' && *(s + 1) == '/') { /* relative-scheme URL */ +@@ -153,7 +153,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, zend_bool *has + * correctly parse things like a.com:80 + */ + p = e + 1; +- while (p < ue && isdigit(*p)) { ++ while (p < ue && isdigit((unsigned char)*p)) { + p++; + } + +@@ -193,7 +193,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, zend_bool *has + p = e + 1; + pp = p; + +- while (pp < ue && pp - p < 6 && isdigit(*pp)) { ++ while (pp < ue && pp - p < 6 && isdigit((unsigned char)*pp)) { + pp++; + } + +@@ -434,12 +434,12 @@ static int php_htoi(char *s) + int value; + int c; + +- c = ((unsigned char *)s)[0]; ++ c = (unsigned char)s[0]; + if (isupper(c)) + c = tolower(c); + value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; + +- c = ((unsigned char *)s)[1]; ++ c = (unsigned char)s[1]; + if (isupper(c)) + c = tolower(c); + value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; +@@ -553,8 +553,8 @@ PHPAPI size_t php_url_decode(char *str, size_t len) + if (*data == '+') { + *dest = ' '; + } +- else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) +- && isxdigit((int) *(data + 2))) { ++ else if (*data == '%' && len >= 2 && isxdigit((unsigned char)data[1]) ++ && isxdigit((unsigned char)data[2])) { + #ifndef CHARSET_EBCDIC + *dest = (char) php_htoi(data + 1); + #else +@@ -649,8 +649,8 @@ PHPAPI size_t php_raw_url_decode(char *str, size_t len) + char *data = str; + + while (len--) { +- if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) +- && isxdigit((int) *(data + 2))) { ++ if (*data == '%' && len >= 2 && isxdigit((unsigned char)data[1]) ++ && isxdigit((unsigned char)data[2])) { + #ifndef CHARSET_EBCDIC + *dest = (char) php_htoi(data + 1); + #else +@@ -716,7 +716,7 @@ no_name_header: + c = *p; + *p = '\0'; + s = p + 1; +- while (isspace((int)*(unsigned char *)s)) { ++ while (isspace((unsigned char)*s)) { + s++; + } + +diff --git a/ext/standard/url_scanner_ex.re b/ext/standard/url_scanner_ex.re +index 1877e68..ec3caa6 100644 +--- a/ext/standard/url_scanner_ex.re ++++ b/ext/standard/url_scanner_ex.re +@@ -87,7 +87,7 @@ static int php_ini_on_update_tags(zend_ini_entry *entry, zend_string *new_value, + + *val++ = '\0'; + for (q = key; *q; q++) { +- *q = tolower(*q); ++ *q = tolower((unsigned char)*q); + } + keylen = q - key; + str = zend_string_init(key, keylen, 1); +@@ -136,7 +136,7 @@ static int php_ini_on_update_hosts(zend_ini_entry *entry, zend_string *new_value + char *q; + + for (q = key; *q; q++) { +- *q = tolower(*q); ++ *q = tolower((unsigned char)*q); + } + keylen = q - key; + if (keylen > 0) { +@@ -456,7 +456,7 @@ static inline void handle_tag(STD_PARA) + } + smart_str_appendl(&ctx->tag, start, YYCURSOR - start); + for (i = 0; i < ZSTR_LEN(ctx->tag.s); i++) +- ZSTR_VAL(ctx->tag.s)[i] = tolower((int)(unsigned char)ZSTR_VAL(ctx->tag.s)[i]); ++ ZSTR_VAL(ctx->tag.s)[i] = tolower((unsigned char)ZSTR_VAL(ctx->tag.s)[i]); + /* intentionally using str_find here, in case the hash value is set, but the string val is changed later */ + if ((ctx->lookup_data = zend_hash_str_find_ptr(ctx->tags, ZSTR_VAL(ctx->tag.s), ZSTR_LEN(ctx->tag.s))) != NULL) { + ok = 1; +diff --git a/ext/standard/versioning.c b/ext/standard/versioning.c +index e435313..fa361bb 100644 +--- a/ext/standard/versioning.c ++++ b/ext/standard/versioning.c +@@ -47,8 +47,8 @@ php_canonicalize_version(const char *version) + * s/([^\d\.])([^\D\.])/$1.$2/g; + * s/([^\D\.])([^\d\.])/$1.$2/g; + */ +-#define isdig(x) (isdigit(x)&&(x)!='.') +-#define isndig(x) (!isdigit(x)&&(x)!='.') ++#define isdig(x) (isdigit((unsigned char)(x))&&(x)!='.') ++#define isndig(x) (!isdigit((unsigned char)(x))&&(x)!='.') + #define isspecialver(x) ((x)=='-'||(x)=='_'||(x)=='+') + + lq = *(q - 1); +@@ -61,7 +61,7 @@ php_canonicalize_version(const char *version) + *q++ = '.'; + } + *q++ = *p; +- } else if (!isalnum(*p)) { ++ } else if (!isalnum((unsigned char)*p)) { + if (lq != '.') { + *q++ = '.'; + } +@@ -154,17 +154,17 @@ php_version_compare(const char *orig_ver1, const char *orig_ver2) + if ((n2 = strchr(p2, '.')) != NULL) { + *n2 = '\0'; + } +- if (isdigit(*p1) && isdigit(*p2)) { ++ if (isdigit((unsigned char)*p1) && isdigit((unsigned char)*p2)) { + /* compare element numerically */ + l1 = strtol(p1, NULL, 10); + l2 = strtol(p2, NULL, 10); + compare = ZEND_NORMALIZE_BOOL(l1 - l2); +- } else if (!isdigit(*p1) && !isdigit(*p2)) { ++ } else if (!isdigit((unsigned char)*p1) && !isdigit((unsigned char)*p2)) { + /* compare element names */ + compare = compare_special_version_forms(p1, p2); + } else { + /* mix of names and numbers */ +- if (isdigit(*p1)) { ++ if (isdigit((unsigned char)*p1)) { + compare = compare_special_version_forms("#N#", p2); + } else { + compare = compare_special_version_forms(p1, "#N#"); +@@ -182,13 +182,13 @@ php_version_compare(const char *orig_ver1, const char *orig_ver2) + } + if (compare == 0) { + if (n1 != NULL) { +- if (isdigit(*p1)) { ++ if (isdigit((unsigned char)*p1)) { + compare = 1; + } else { + compare = php_version_compare(p1, "#N#"); + } + } else if (n2 != NULL) { +- if (isdigit(*p2)) { ++ if (isdigit((unsigned char)*p2)) { + compare = -1; + } else { + compare = php_version_compare("#N#", p2); +diff --git a/ext/xml/compat.c b/ext/xml/compat.c +index fc45256..57eb00d 100644 +--- a/ext/xml/compat.c ++++ b/ext/xml/compat.c +@@ -19,6 +19,7 @@ + #include "php.h" + #if defined(HAVE_LIBXML) && (defined(HAVE_XML) || defined(HAVE_XMLRPC)) && !defined(HAVE_LIBEXPAT) + #include "expat_compat.h" ++#include "ext/libxml/php_libxml.h" + + typedef struct _php_xml_ns { + xmlNsPtr nsptr; +@@ -471,6 +472,7 @@ XML_ParserCreate_MM(const XML_Char *encoding, const XML_Memory_Handling_Suite *m + return NULL; + } + ++ php_libxml_sanitize_parse_ctxt_options(parser->parser); + xmlCtxtUseOptions(parser->parser, XML_PARSE_OLDSAX); + + parser->parser->replaceEntities = 1; +diff --git a/ext/xml/tests/bug26614_libxml_gte2_11.phpt b/ext/xml/tests/bug26614_libxml_gte2_11.phpt +new file mode 100644 +index 0000000..9a81b67 +--- /dev/null ++++ b/ext/xml/tests/bug26614_libxml_gte2_11.phpt +@@ -0,0 +1,95 @@ ++--TEST-- ++Bug #26614 (CDATA sections skipped on line count) ++--EXTENSIONS-- ++xml ++--SKIPIF-- ++= 2.11'); ++?> ++--FILE-- ++ ++ ++ ++'; ++ ++// Case 2: replace some characters so that we get comments instead ++$xmls["Comment"] =' ++ ++ ++'; ++ ++// Case 3: replace even more characters so that only textual data is left ++$xmls["Text"] =' ++ ++-!-- ATA[ ++multi ++line ++CDATA ++block ++--- ++'; ++ ++function startElement($parser, $name, $attrs) { ++ printf("<$name> at line %d, col %d (byte %d)\n", ++ xml_get_current_line_number($parser), ++ xml_get_current_column_number($parser), ++ xml_get_current_byte_index($parser)); ++} ++ ++function endElement($parser, $name) { ++ printf(" at line %d, col %d (byte %d)\n", ++ xml_get_current_line_number($parser), ++ xml_get_current_column_number($parser), ++ xml_get_current_byte_index($parser)); ++} ++ ++function characterData($parser, $data) { ++ // dummy ++} ++ ++foreach ($xmls as $desc => $xml) { ++ echo "$desc\n"; ++ $xml_parser = xml_parser_create(); ++ xml_set_element_handler($xml_parser, "startElement", "endElement"); ++ xml_set_character_data_handler($xml_parser, "characterData"); ++ if (!xml_parse($xml_parser, $xml, true)) ++ echo "Error: ".xml_error_string(xml_get_error_code($xml_parser))."\n"; ++ xml_parser_free($xml_parser); ++} ++?> ++--EXPECTF-- ++CDATA ++ at line 2, col %d (byte 50) ++ at line 9, col %d (byte 96) ++Comment ++ at line 2, col %d (byte 50) ++ at line 9, col %d (byte 96) ++Text ++ at line 2, col %d (byte 50) ++ at line 9, col %d (byte 96) +diff --git a/ext/xml/tests/bug26614_libxml.phpt b/ext/xml/tests/bug26614_libxml_pre2_11.phpt +similarity index 96% +rename from ext/xml/tests/bug26614_libxml.phpt +rename to ext/xml/tests/bug26614_libxml_pre2_11.phpt +index 3ddd35e..afacaa1 100644 +--- a/ext/xml/tests/bug26614_libxml.phpt ++++ b/ext/xml/tests/bug26614_libxml_pre2_11.phpt +@@ -4,6 +4,7 @@ Bug #26614 (CDATA sections skipped on line count) + = 21100) die('skip libxml2 test variant for version < 2.11'); + ?> + --FILE-- + "; ++$parser = xml_parser_create(); ++xml_parser_set_option($parser, XML_OPTION_SKIP_TAGSTART, 100); ++$res = xml_parse_into_struct($parser,$sample,$vals,$index); ++var_dump($vals); ++?> ++--EXPECT-- ++array(3) { ++ [0]=> ++ array(3) { ++ ["tag"]=> ++ string(0) "" ++ ["type"]=> ++ string(4) "open" ++ ["level"]=> ++ int(1) ++ } ++ [1]=> ++ array(3) { ++ ["tag"]=> ++ string(0) "" ++ ["type"]=> ++ string(8) "complete" ++ ["level"]=> ++ int(2) ++ } ++ [2]=> ++ array(3) { ++ ["tag"]=> ++ string(0) "" ++ ["type"]=> ++ string(5) "close" ++ ["level"]=> ++ int(1) ++ } ++} +diff --git a/ext/xml/xml.c b/ext/xml/xml.c +index 6fe6151..b56bf79 100644 +--- a/ext/xml/xml.c ++++ b/ext/xml/xml.c +@@ -773,9 +773,11 @@ void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Ch + array_init(&tag); + array_init(&atr); + +- _xml_add_to_info(parser, ZSTR_VAL(tag_name) + parser->toffset); ++ char *skipped_tag_name = SKIP_TAGSTART(ZSTR_VAL(tag_name)); + +- add_assoc_string(&tag, "tag", SKIP_TAGSTART(ZSTR_VAL(tag_name))); /* cast to avoid gcc-warning */ ++ _xml_add_to_info(parser, skipped_tag_name); ++ ++ add_assoc_string(&tag, "tag", skipped_tag_name); + add_assoc_string(&tag, "type", "open"); + add_assoc_long(&tag, "level", parser->level); + +@@ -842,9 +844,11 @@ void _xml_endElementHandler(void *userData, const XML_Char *name) + } else { + array_init(&tag); + +- _xml_add_to_info(parser, ZSTR_VAL(tag_name) + parser->toffset); ++ char *skipped_tag_name = SKIP_TAGSTART(ZSTR_VAL(tag_name)); ++ ++ _xml_add_to_info(parser, skipped_tag_name); + +- add_assoc_string(&tag, "tag", SKIP_TAGSTART(ZSTR_VAL(tag_name))); /* cast to avoid gcc-warning */ ++ add_assoc_string(&tag, "tag", skipped_tag_name); + add_assoc_string(&tag, "type", "close"); + add_assoc_long(&tag, "level", parser->level); + +diff --git a/ext/xmlreader/php_xmlreader.c b/ext/xmlreader/php_xmlreader.c +index 06f5699..51d6bb9 100644 +--- a/ext/xmlreader/php_xmlreader.c ++++ b/ext/xmlreader/php_xmlreader.c +@@ -304,6 +304,7 @@ static xmlRelaxNGPtr _xmlreader_get_relaxNG(char *source, size_t source_len, siz + return NULL; + } + ++ PHP_LIBXML_SANITIZE_GLOBALS(parse); + if (error_func || warn_func) { + xmlRelaxNGSetParserErrors(parser, + (xmlRelaxNGValidityErrorFunc) error_func, +@@ -312,6 +313,7 @@ static xmlRelaxNGPtr _xmlreader_get_relaxNG(char *source, size_t source_len, siz + } + sptr = xmlRelaxNGParse(parser); + xmlRelaxNGFreeParserCtxt(parser); ++ PHP_LIBXML_RESTORE_GLOBALS(parse); + + return sptr; + } +@@ -881,7 +883,9 @@ PHP_METHOD(xmlreader, open) + valid_file = _xmlreader_get_valid_file_path(source, resolved_path, MAXPATHLEN ); + + if (valid_file) { ++ PHP_LIBXML_SANITIZE_GLOBALS(reader_for_file); + reader = xmlReaderForFile(valid_file, encoding, options); ++ PHP_LIBXML_RESTORE_GLOBALS(reader_for_file); + } + + if (reader == NULL) { +@@ -958,7 +962,9 @@ PHP_METHOD(xmlreader, setSchema) + + intern = Z_XMLREADER_P(id); + if (intern && intern->ptr) { ++ PHP_LIBXML_SANITIZE_GLOBALS(schema); + retval = xmlTextReaderSchemaValidate(intern->ptr, source); ++ PHP_LIBXML_RESTORE_GLOBALS(schema); + + if (retval == 0) { + RETURN_TRUE; +@@ -1038,7 +1044,7 @@ PHP_METHOD(xmlreader, XML) + xmlreader_object *intern = NULL; + char *source, *uri = NULL, *encoding = NULL; + int resolved_path_len, ret = 0; +- char *directory=NULL, resolved_path[MAXPATHLEN]; ++ char *directory=NULL, resolved_path[MAXPATHLEN + 1]; + xmlParserInputBufferPtr inputbfr; + xmlTextReaderPtr reader; + +@@ -1082,6 +1088,7 @@ PHP_METHOD(xmlreader, XML) + } + uri = (char *) xmlCanonicPath((const xmlChar *) resolved_path); + } ++ PHP_LIBXML_SANITIZE_GLOBALS(text_reader); + reader = xmlNewTextReader(inputbfr, uri); + + if (reader != NULL) { +@@ -1100,9 +1107,11 @@ PHP_METHOD(xmlreader, XML) + xmlFree(uri); + } + ++ PHP_LIBXML_RESTORE_GLOBALS(text_reader); + return; + } + } ++ PHP_LIBXML_RESTORE_GLOBALS(text_reader); + } + + if (uri) { +diff --git a/ext/xmlreader/tests/libxml_global_state_entity_loader_bypass.phpt b/ext/xmlreader/tests/libxml_global_state_entity_loader_bypass.phpt +new file mode 100644 +index 0000000..b0120b3 +--- /dev/null ++++ b/ext/xmlreader/tests/libxml_global_state_entity_loader_bypass.phpt +@@ -0,0 +1,36 @@ ++--TEST-- ++GHSA-3qrf-m4j2-pcrr (libxml global state entity loader bypass) ++--SKIPIF-- ++ ++--FILE-- ++ %bork;]>"; ++ ++libxml_use_internal_errors(true); ++zend_test_override_libxml_global_state(); ++ ++echo "--- String test ---\n"; ++$reader = @XMLReader::xml($xml); ++$reader->read(); ++echo "--- File test ---\n"; ++file_put_contents("libxml_global_state_entity_loader_bypass.tmp", $xml); ++$reader = @XMLReader::open("libxml_global_state_entity_loader_bypass.tmp"); ++$reader->read(); ++ ++echo "Done\n"; ++ ++?> ++--CLEAN-- ++ ++--EXPECT-- ++--- String test --- ++--- File test --- ++Done +diff --git a/ext/xsl/xsltprocessor.c b/ext/xsl/xsltprocessor.c +index 079920d..2d95b2f 100644 +--- a/ext/xsl/xsltprocessor.c ++++ b/ext/xsl/xsltprocessor.c +@@ -398,7 +398,7 @@ PHP_FUNCTION(xsl_xsltprocessor_import_stylesheet) + xmlDoc *doc = NULL, *newdoc = NULL; + xsltStylesheetPtr sheetp, oldsheetp; + xsl_object *intern; +- int prevSubstValue, prevExtDtdValue, clone_docu = 0; ++ int clone_docu = 0; + xmlNode *nodep = NULL; + zval *cloneDocu, member, rv; + +@@ -421,13 +421,12 @@ PHP_FUNCTION(xsl_xsltprocessor_import_stylesheet) + stylesheet document otherwise the node proxies will be a mess */ + newdoc = xmlCopyDoc(doc, 1); + xmlNodeSetBase((xmlNodePtr) newdoc, (xmlChar *)doc->URL); +- prevSubstValue = xmlSubstituteEntitiesDefault(1); +- prevExtDtdValue = xmlLoadExtDtdDefaultValue; ++ PHP_LIBXML_SANITIZE_GLOBALS(parse); ++ xmlSubstituteEntitiesDefault(1); + xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; + + sheetp = xsltParseStylesheetDoc(newdoc); +- xmlSubstituteEntitiesDefault(prevSubstValue); +- xmlLoadExtDtdDefaultValue = prevExtDtdValue; ++ PHP_LIBXML_RESTORE_GLOBALS(parse); + + if (!sheetp) { + xmlFreeDoc(newdoc); +diff --git a/ext/zend_test/test.c b/ext/zend_test/test.c +index 4f81adc..cdfc155 100644 +--- a/ext/zend_test/test.c ++++ b/ext/zend_test/test.c +@@ -25,6 +25,11 @@ + #include "ext/standard/info.h" + #include "php_test.h" + ++#if defined(HAVE_LIBXML) && !defined(PHP_WIN32) ++# include ++# include ++#endif ++ + static zend_class_entry *zend_test_interface; + static zend_class_entry *zend_test_class; + static zend_class_entry *zend_test_child_class; +@@ -48,6 +53,20 @@ ZEND_BEGIN_ARG_INFO_EX(arginfo_zend_leak_variable, 0, 0, 1) + ZEND_ARG_INFO(0, variable) + ZEND_END_ARG_INFO() + ++#if defined(HAVE_LIBXML) && !defined(PHP_WIN32) ++static ZEND_FUNCTION(zend_test_override_libxml_global_state) ++{ ++ ZEND_PARSE_PARAMETERS_NONE(); ++ ++ xmlLoadExtDtdDefaultValue = 1; ++ xmlDoValidityCheckingDefaultValue = 1; ++ (void) xmlPedanticParserDefault(1); ++ (void) xmlSubstituteEntitiesDefault(1); ++ (void) xmlLineNumbersDefault(1); ++ (void) xmlKeepBlanksDefault(0); ++} ++#endif ++ + ZEND_FUNCTION(zend_test_func) + { + /* dummy */ +@@ -297,6 +316,9 @@ static const zend_function_entry zend_test_functions[] = { + ZEND_FE(zend_terminate_string, arginfo_zend_terminate_string) + ZEND_FE(zend_leak_bytes, NULL) + ZEND_FE(zend_leak_variable, arginfo_zend_leak_variable) ++#if defined(HAVE_LIBXML) && !defined(PHP_WIN32) ++ ZEND_FE(zend_test_override_libxml_global_state, NULL) ++#endif + ZEND_FE_END + }; + +diff --git a/main/SAPI.c b/main/SAPI.c +index 1c320f6..a375503 100644 +--- a/main/SAPI.c ++++ b/main/SAPI.c +@@ -195,7 +195,7 @@ static void sapi_read_post_data(void) + *p = 0; + break; + default: +- *p = tolower(*p); ++ *p = tolower((unsigned char)*p); + break; + } + } +@@ -709,10 +709,10 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg) + header_line = estrndup(header_line, header_line_len); + + /* cut off trailing spaces, linefeeds and carriage-returns */ +- if (header_line_len && isspace(header_line[header_line_len-1])) { ++ if (header_line_len && isspace((unsigned char)header_line[header_line_len - 1])) { + do { + header_line_len--; +- } while(header_line_len && isspace(header_line[header_line_len-1])); ++ } while(header_line_len && isspace((unsigned char)header_line[header_line_len - 1])); + header_line[header_line_len]='\0'; + } + +diff --git a/main/fastcgi.c b/main/fastcgi.c +index f8044ff..03c4aaf 100644 +--- a/main/fastcgi.c ++++ b/main/fastcgi.c +@@ -1343,7 +1343,7 @@ static int fcgi_is_allowed() { + if (client_sa.sa.sa_family == AF_INET6) { + for (i = 0; allowed_clients[i].sa.sa_family ; i++) { + if (allowed_clients[i].sa.sa_family == AF_INET6 +- && !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, 12)) { ++ && !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, sizeof(client_sa.sa_inet6.sin6_addr))) { + return 1; + } + #ifdef IN6_IS_ADDR_V4MAPPED +diff --git a/main/fopen_wrappers.c b/main/fopen_wrappers.c +index 2713502..b7173df 100644 +--- a/main/fopen_wrappers.c ++++ b/main/fopen_wrappers.c +@@ -138,10 +138,10 @@ PHPAPI ZEND_INI_MH(OnUpdateBaseDir) + */ + PHPAPI int php_check_specific_open_basedir(const char *basedir, const char *path) + { +- char resolved_name[MAXPATHLEN]; +- char resolved_basedir[MAXPATHLEN]; ++ char resolved_name[MAXPATHLEN + 1]; ++ char resolved_basedir[MAXPATHLEN + 1]; + char local_open_basedir[MAXPATHLEN]; +- char path_tmp[MAXPATHLEN]; ++ char path_tmp[MAXPATHLEN + 1]; + char *path_file; + size_t resolved_basedir_len; + size_t resolved_name_len; +@@ -493,7 +493,7 @@ PHPAPI zend_string *php_resolve_path(const char *filename, size_t filename_lengt + } + + /* Don't resolve paths which contain protocol (except of file://) */ +- for (p = filename; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++); ++ for (p = filename; isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.'; p++); + if ((*p == ':') && (p - filename > 1) && (p[1] == '/') && (p[2] == '/')) { + wrapper = php_stream_locate_url_wrapper(filename, &actual_path, STREAM_OPEN_FOR_INCLUDE); + if (wrapper == &php_plain_files_wrapper) { +@@ -529,7 +529,7 @@ PHPAPI zend_string *php_resolve_path(const char *filename, size_t filename_lengt + /* Check for stream wrapper */ + int is_stream_wrapper = 0; + +- for (p = ptr; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++); ++ for (p = ptr; isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.'; p++); + if ((*p == ':') && (p - ptr > 1) && (p[1] == '/') && (p[2] == '/')) { + /* .:// or ..:// is not a stream wrapper */ + if (p[-1] != '.' || p[-2] != '.' || p - 2 != ptr) { +@@ -598,7 +598,7 @@ PHPAPI zend_string *php_resolve_path(const char *filename, size_t filename_lengt + actual_path = trypath; + + /* Check for stream wrapper */ +- for (p = trypath; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++); ++ for (p = trypath; isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.'; p++); + if ((*p == ':') && (p - trypath > 1) && (p[1] == '/') && (p[2] == '/')) { + wrapper = php_stream_locate_url_wrapper(trypath, &actual_path, STREAM_OPEN_FOR_INCLUDE); + if (!wrapper) { +diff --git a/main/php_ini.c b/main/php_ini.c +index cc2cf16..8d5b581 100644 +--- a/main/php_ini.c ++++ b/main/php_ini.c +@@ -42,7 +42,7 @@ + char *tmp = path; \ + while (*tmp) { \ + if (*tmp == '\\') *tmp = '/'; \ +- else *tmp = tolower(*tmp); \ ++ else *tmp = tolower((unsigned char)*tmp); \ + tmp++; \ + } \ + } +diff --git a/main/php_variables.c b/main/php_variables.c +index c920e4d..7d61e9e 100644 +--- a/main/php_variables.c ++++ b/main/php_variables.c +@@ -65,6 +65,21 @@ static zend_always_inline void php_register_variable_quick(const char *name, siz + zend_string_release_ex(key, 0); + } + ++/* Discard variable if mangling made it start with __Host-, where pre-mangling it did not start with __Host- ++ * Discard variable if mangling made it start with __Secure-, where pre-mangling it did not start with __Secure- */ ++static zend_bool php_is_forbidden_variable_name(const char *mangled_name, size_t mangled_name_len, const char *pre_mangled_name) ++{ ++ if (mangled_name_len >= sizeof("__Host-")-1 && strncmp(mangled_name, "__Host-", sizeof("__Host-")-1) == 0 && strncmp(pre_mangled_name, "__Host-", sizeof("__Host-")-1) != 0) { ++ return 1; ++ } ++ ++ if (mangled_name_len >= sizeof("__Secure-")-1 && strncmp(mangled_name, "__Secure-", sizeof("__Secure-")-1) == 0 && strncmp(pre_mangled_name, "__Secure-", sizeof("__Secure-")-1) != 0) { ++ return 1; ++ } ++ ++ return 0; ++} ++ + PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars_array) + { + char *p = NULL; +@@ -115,20 +130,6 @@ PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars + } + var_len = p - var; + +- /* Discard variable if mangling made it start with __Host-, where pre-mangling it did not start with __Host- */ +- if (strncmp(var, "__Host-", sizeof("__Host-")-1) == 0 && strncmp(var_name, "__Host-", sizeof("__Host-")-1) != 0) { +- zval_ptr_dtor_nogc(val); +- free_alloca(var_orig, use_heap); +- return; +- } +- +- /* Discard variable if mangling made it start with __Secure-, where pre-mangling it did not start with __Secure- */ +- if (strncmp(var, "__Secure-", sizeof("__Secure-")-1) == 0 && strncmp(var_name, "__Secure-", sizeof("__Secure-")-1) != 0) { +- zval_ptr_dtor_nogc(val); +- free_alloca(var_orig, use_heap); +- return; +- } +- + if (var_len==0) { /* empty variable name, or variable name with a space in it */ + zval_ptr_dtor_nogc(val); + free_alloca(var_orig, use_heap); +@@ -195,7 +196,7 @@ PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars + + ip++; + index_s = ip; +- if (isspace(*ip)) { ++ if (isspace((unsigned char)*ip)) { + ip++; + } + if (*ip==']') { +@@ -226,6 +227,12 @@ PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars + return; + } + } else { ++ if (php_is_forbidden_variable_name(index, index_len, var_name)) { ++ zval_ptr_dtor_nogc(val); ++ free_alloca(var_orig, use_heap); ++ return; ++ } ++ + gpc_element_p = zend_symtable_str_find(symtable1, index, index_len); + if (!gpc_element_p) { + zval tmp; +@@ -263,6 +270,12 @@ plain_var: + zval_ptr_dtor_nogc(val); + } + } else { ++ if (php_is_forbidden_variable_name(index, index_len, var_name)) { ++ zval_ptr_dtor_nogc(val); ++ free_alloca(var_orig, use_heap); ++ return; ++ } ++ + zend_ulong idx; + + /* +@@ -500,7 +513,7 @@ SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data) + + if (arg == PARSE_COOKIE) { + /* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */ +- while (isspace(*var)) { ++ while (isspace((unsigned char)*var)) { + var++; + } + if (var == val || *var == '\0') { +diff --git a/main/rfc1867.c b/main/rfc1867.c +index 4946df0..2aabb20 100644 +--- a/main/rfc1867.c ++++ b/main/rfc1867.c +@@ -429,7 +429,7 @@ static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header) + } + + /* space in the beginning means same header */ +- if (!isspace(line[0])) { ++ if (!isspace((unsigned char)line[0])) { + value = strchr(line, ':'); + } + +@@ -445,7 +445,6 @@ static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header) + } + + *value = '\0'; +- + /* Keep only headers we use, and ignore duplicates */ + if (!php_mime_should_save_hdr(line) + || php_mime_get_hdr_value(*header, line)) { +@@ -548,7 +547,7 @@ static char *substring_conf(char *start, size_t len, char quote) + + static char *php_ap_getword_conf(const zend_encoding *encoding, char *str) + { +- while (*str && isspace(*str)) { ++ while (*str && isspace((unsigned char)*str)) { + ++str; + } + +@@ -564,7 +563,7 @@ static char *php_ap_getword_conf(const zend_encoding *encoding, char *str) + } else { + char *strend = str; + +- while (*strend && !isspace(*strend)) { ++ while (*strend && !isspace((unsigned char)*strend)) { + ++strend; + } + return substring_conf(str, (size_t)(strend - str), 0); +@@ -773,6 +772,13 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ + boundary_len = boundary_end-boundary; + } + ++ /* Boundaries larger than FILLUNIT-strlen("\r\n--") characters lead to ++ * erroneous parsing */ ++ if (boundary_len > FILLUNIT-strlen("\r\n--")) { ++ sapi_module.sapi_error(E_WARNING, "Boundary too large in multipart/form-data POST data"); ++ return; ++ } ++ + /* Initialize the buffer */ + if (!(mbuff = multipart_buffer_new(boundary, boundary_len))) { + sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer"); +@@ -824,7 +830,7 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ + goto fileupload_done; + } + +- while (isspace(*cd)) { ++ while (isspace((unsigned char)*cd)) { + ++cd; + } + +@@ -832,7 +838,7 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ + { + char *key = NULL, *word = pair; + +- while (isspace(*cd)) { ++ while (isspace((unsigned char)*cd)) { + ++cd; + } + +@@ -947,7 +953,10 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ + skip_upload = 1; + } else if (upload_cnt <= 0) { + skip_upload = 1; +- sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded"); ++ if (upload_cnt == 0) { ++ --upload_cnt; ++ sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded"); ++ } + } + + /* Return with an error if the posted data is garbled */ +diff --git a/main/snprintf.c b/main/snprintf.c +index 61a5dff..01d605c 100644 +--- a/main/snprintf.c ++++ b/main/snprintf.c +@@ -391,7 +391,7 @@ PHPAPI char * php_conv_fp(register char format, register double num, + /* + * Check for Infinity and NaN + */ +- if (isalpha((int)*p)) { ++ if (isalpha((unsigned char)*p)) { + *len = strlen(p); + memcpy(buf, p, *len + 1); + *is_negative = FALSE; +@@ -538,11 +538,11 @@ typedef struct buf_area buffy; + #define NUM( c ) ( c - '0' ) + + #define STR_TO_DEC( str, num ) \ +- num = NUM( *str++ ) ; \ +- while ( isdigit((int)*str ) ) \ ++ num = NUM( *(str)++ ) ; \ ++ while ( isdigit((unsigned char)*(str) ) ) \ + { \ + num *= 10 ; \ +- num += NUM( *str++ ) ; \ ++ num += NUM( *(str)++ ) ; \ + } + + /* +@@ -646,7 +646,7 @@ static int format_converter(register buffy * odp, const char *fmt, va_list ap) / + /* + * Try to avoid checking for flags, width or precision + */ +- if (isascii((int)*fmt) && !islower((int)*fmt)) { ++ if (isascii((unsigned char)*fmt) && !islower((unsigned char)*fmt)) { + /* + * Recognize flags: -, #, BLANK, + + */ +@@ -668,7 +668,7 @@ static int format_converter(register buffy * odp, const char *fmt, va_list ap) / + /* + * Check if a width was specified + */ +- if (isdigit((int)*fmt)) { ++ if (isdigit((unsigned char)*fmt)) { + STR_TO_DEC(fmt, min_width); + adjust_width = YES; + } else if (*fmt == '*') { +@@ -688,7 +688,7 @@ static int format_converter(register buffy * odp, const char *fmt, va_list ap) / + if (*fmt == '.') { + adjust_precision = YES; + fmt++; +- if (isdigit((int)*fmt)) { ++ if (isdigit((unsigned char)*fmt)) { + STR_TO_DEC(fmt, precision); + } else if (*fmt == '*') { + precision = va_arg(ap, int); +diff --git a/main/spprintf.c b/main/spprintf.c +index a207050..ef90f9b 100644 +--- a/main/spprintf.c ++++ b/main/spprintf.c +@@ -152,12 +152,12 @@ + #define NUM(c) (c - '0') + + #define STR_TO_DEC(str, num) do { \ +- num = NUM(*str++); \ +- while (isdigit((int)*str)) { \ ++ num = NUM(*(str)++); \ ++ while (isdigit((unsigned char)*(str))) {\ + num *= 10; \ +- num += NUM(*str++); \ ++ num += NUM(*(str)++); \ + if (num >= INT_MAX / 10) { \ +- while (isdigit((int)*str++)); \ ++ while (isdigit((unsigned char)*(str)++)); \ + break; \ + } \ + } \ +@@ -246,7 +246,7 @@ static void xbuf_format_converter(void *xbuf, zend_bool is_char, const char *fmt + /* + * Try to avoid checking for flags, width or precision + */ +- if (isascii((int)*fmt) && !islower((int)*fmt)) { ++ if (isascii((unsigned char)*fmt) && !islower((unsigned char)*fmt)) { + /* + * Recognize flags: -, #, BLANK, + + */ +@@ -268,7 +268,7 @@ static void xbuf_format_converter(void *xbuf, zend_bool is_char, const char *fmt + /* + * Check if a width was specified + */ +- if (isdigit((int)*fmt)) { ++ if (isdigit((unsigned char)*fmt)) { + STR_TO_DEC(fmt, min_width); + adjust_width = YES; + } else if (*fmt == '*') { +@@ -288,7 +288,7 @@ static void xbuf_format_converter(void *xbuf, zend_bool is_char, const char *fmt + if (*fmt == '.') { + adjust_precision = YES; + fmt++; +- if (isdigit((int)*fmt)) { ++ if (isdigit((unsigned char)*fmt)) { + STR_TO_DEC(fmt, precision); + } else if (*fmt == '*') { + precision = va_arg(ap, int); +diff --git a/main/streams/streams.c b/main/streams/streams.c +index a320a90..8f368d4 100644 +--- a/main/streams/streams.c ++++ b/main/streams/streams.c +@@ -1750,7 +1750,7 @@ static inline int php_stream_wrapper_scheme_validate(const char *protocol, unsig + unsigned int i; + + for(i = 0; i < protocol_len; i++) { +- if (!isalnum((int)protocol[i]) && ++ if (!isalnum((unsigned char)protocol[i]) && + protocol[i] != '+' && + protocol[i] != '-' && + protocol[i] != '.') { +@@ -1830,7 +1830,7 @@ PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, const + return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper); + } + +- for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { ++ for (p = path; isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { + n++; + } + +diff --git a/main/streams/transports.c b/main/streams/transports.c +index 74fbef5..51f0ab3 100644 +--- a/main/streams/transports.c ++++ b/main/streams/transports.c +@@ -95,7 +95,7 @@ PHPAPI php_stream *_php_stream_xport_create(const char *name, size_t namelen, in + } + } + +- for (p = name; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { ++ for (p = name; isalnum((unsigned char)*p) || *p == '+' || *p == '-' || *p == '.'; p++) { + n++; + } + +diff --git a/main/streams/xp_socket.c b/main/streams/xp_socket.c +index 46b23b6..7a192ea 100644 +--- a/main/streams/xp_socket.c ++++ b/main/streams/xp_socket.c +@@ -580,12 +580,15 @@ static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *po + char *colon; + char *host = NULL; + +-#ifdef HAVE_IPV6 +- char *p; ++ if (memchr(str, '\0', str_len)) { ++ *err = strpprintf(0, "The hostname must not contain null bytes"); ++ return NULL; ++ } + ++#ifdef HAVE_IPV6 + if (*(str) == '[' && str_len > 1) { + /* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */ +- p = memchr(str + 1, ']', str_len - 2); ++ char *p = memchr(str + 1, ']', str_len - 2); + if (!p || *(p + 1) != ':') { + if (get_err) { + *err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str); +diff --git a/sapi/cgi/cgi_main.c b/sapi/cgi/cgi_main.c +index a36f426..ebce630 100644 +--- a/sapi/cgi/cgi_main.c ++++ b/sapi/cgi/cgi_main.c +@@ -1777,7 +1777,6 @@ int main(int argc, char *argv[]) + int status = 0; + #endif + char *query_string; +- char *decoded_query_string; + int skip_getopt = 0; + + #if defined(SIGPIPE) && defined(SIG_IGN) +@@ -1827,10 +1826,20 @@ int main(int argc, char *argv[]) + } + } + ++ /* Apache CGI will pass the query string to the command line if it doesn't contain a '='. ++ * This can create an issue where a malicious request can pass command line arguments to ++ * the executable. Ideally we skip argument parsing when we're in cgi or fastcgi mode, ++ * but that breaks PHP scripts on Linux with a hashbang: `#!/php-cgi -d option=value`. ++ * Therefore, this code only prevents passing arguments if the query string starts with a '-'. ++ * Similarly, scripts spawned in subprocesses on Windows may have the same issue. ++ * However, Windows has lots of conversion rules and command line parsing rules that ++ * are too difficult and dangerous to reliably emulate. */ + if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) { +- /* we've got query string that has no = - apache CGI will pass it to command line */ ++#ifdef PHP_WIN32 ++ skip_getopt = cgi || fastcgi; ++#else + unsigned char *p; +- decoded_query_string = strdup(query_string); ++ char *decoded_query_string = strdup(query_string); + php_url_decode(decoded_query_string, strlen(decoded_query_string)); + for (p = (unsigned char *)decoded_query_string; *p && *p <= ' '; p++) { + /* skip all leading spaces */ +@@ -1838,7 +1847,9 @@ int main(int argc, char *argv[]) + if(*p == '-') { + skip_getopt = 1; + } ++ + free(decoded_query_string); ++#endif + } + + while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { +@@ -1928,18 +1939,17 @@ int main(int argc, char *argv[]) + + /* check force_cgi after startup, so we have proper output */ + if (cgi && CGIG(force_redirect)) { +- /* Apache will generate REDIRECT_STATUS, +- * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS. +- * redirect.so and installation instructions available from +- * http://www.koehntopp.de/php. +- * -- kk@netuse.de +- */ +- if (!getenv("REDIRECT_STATUS") && +- !getenv ("HTTP_REDIRECT_STATUS") && +- /* this is to allow a different env var to be configured +- * in case some server does something different than above */ +- (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env))) +- ) { ++ /* This is to allow a different environment variable to be configured ++ * in case the we cannot auto-detect which environment variable to use. ++ * Checking this first to allow user overrides in case the environment ++ * variable can be set by an untrusted party. */ ++ const char *redirect_status_env = CGIG(redirect_status_env); ++ if (!redirect_status_env) { ++ /* Apache will generate REDIRECT_STATUS. */ ++ redirect_status_env = "REDIRECT_STATUS"; ++ } ++ ++ if (!getenv(redirect_status_env)) { + zend_try { + SG(sapi_headers).http_response_code = 400; + PUTS("Security Alert! The PHP CGI cannot be accessed directly.\n\n\ +diff --git a/sapi/cgi/tests/ghsa-3qgc-jrrr-25jv.phpt b/sapi/cgi/tests/ghsa-3qgc-jrrr-25jv.phpt +new file mode 100644 +index 0000000..fd2fcdf +--- /dev/null ++++ b/sapi/cgi/tests/ghsa-3qgc-jrrr-25jv.phpt +@@ -0,0 +1,38 @@ ++--TEST-- ++GHSA-3qgc-jrrr-25jv ++--SKIPIF-- ++ ++--FILE-- ++'; ++file_put_contents($filename, $script); ++ ++$php = get_cgi_path(); ++reset_env_vars(); ++ ++putenv("SERVER_NAME=Test"); ++putenv("SCRIPT_FILENAME=$filename"); ++putenv("QUERY_STRING=%ads"); ++putenv("REDIRECT_STATUS=1"); ++ ++passthru("$php -s"); ++ ++?> ++--CLEAN-- ++ ++--EXPECTF-- ++X-Powered-By: PHP/%s ++Content-type: %s ++ ++hello world +diff --git a/sapi/cli/php_cli_server.c b/sapi/cli/php_cli_server.c +index c309786..2ea8176 100644 +--- a/sapi/cli/php_cli_server.c ++++ b/sapi/cli/php_cli_server.c +@@ -673,7 +673,7 @@ static int sapi_cli_server_register_entry_cb(char **entry, int num_args, va_list + if (key[i] == '-') { + key[i] = '_'; + } else { +- key[i] = toupper(key[i]); ++ key[i] = toupper((unsigned char)key[i]); + } + } + spprintf(&real_key, 0, "%s_%s", "HTTP", key); +@@ -1923,8 +1923,6 @@ static size_t php_cli_server_client_send_through(php_cli_server_client *client, + + static void php_cli_server_client_populate_request_info(const php_cli_server_client *client, sapi_request_info *request_info) /* {{{ */ + { +- char *val; +- + request_info->request_method = php_http_method_str(client->request.request_method); + request_info->proto_num = client->request.protocol_version; + request_info->request_uri = client->request.request_uri; +@@ -1932,9 +1930,7 @@ static void php_cli_server_client_populate_request_info(const php_cli_server_cli + request_info->query_string = client->request.query_string; + request_info->content_length = client->request.content_len; + request_info->auth_user = request_info->auth_password = request_info->auth_digest = NULL; +- if (NULL != (val = zend_hash_str_find_ptr(&client->request.headers, "content-type", sizeof("content-type")-1))) { +- request_info->content_type = val; +- } ++ request_info->content_type = zend_hash_str_find_ptr(&client->request.headers, "content-type", sizeof("content-type")-1); + } /* }}} */ + + static void destroy_request_info(sapi_request_info *request_info) /* {{{ */ +diff --git a/sapi/cli/tests/ghsa-4w77-75f9-2c8w.phpt b/sapi/cli/tests/ghsa-4w77-75f9-2c8w.phpt +new file mode 100644 +index 0000000..80944c3 +--- /dev/null ++++ b/sapi/cli/tests/ghsa-4w77-75f9-2c8w.phpt +@@ -0,0 +1,41 @@ ++--TEST-- ++GHSA-4w77-75f9-2c8w (Heap-Use-After-Free in sapi_read_post_data Processing in CLI SAPI Interface) ++--INI-- ++allow_url_fopen=1 ++--SKIPIF-- ++ ++--FILE-- ++ [ ++ "method" => "POST", ++ "header" => "Content-Type: application/x-www-form-urlencoded", ++ "content" => "AAAAA", ++ ], ++]; ++$context = stream_context_create($options); ++ ++echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/", false, $context); ++ ++$options = [ ++ "http" => [ ++ "method" => "POST", ++ ], ++]; ++$context = stream_context_create($options); ++ ++echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/", false, $context); ++?> ++--EXPECT-- ++string(5) "AAAAA" ++string(0) "" +diff --git a/sapi/fpm/fpm/fpm_conf.c b/sapi/fpm/fpm/fpm_conf.c +index 7a05286..d7af7bf 100644 +--- a/sapi/fpm/fpm/fpm_conf.c ++++ b/sapi/fpm/fpm/fpm_conf.c +@@ -875,7 +875,7 @@ static int fpm_conf_process_all_pools() /* {{{ */ + } + + for (i = 0; i < strlen(status); i++) { +- if (!isalnum(status[i]) && status[i] != '/' && status[i] != '-' && status[i] != '_' && status[i] != '.' && status[i] != '~') { ++ if (!isalnum((unsigned char)status[i]) && status[i] != '/' && status[i] != '-' && status[i] != '_' && status[i] != '.' && status[i] != '~') { + zlog(ZLOG_ERROR, "[pool %s] the status path '%s' must contain only the following characters '[alphanum]/_-.~'", wp->config->name, status); + return -1; + } +@@ -898,7 +898,7 @@ static int fpm_conf_process_all_pools() /* {{{ */ + } + + for (i = 0; i < strlen(ping); i++) { +- if (!isalnum(ping[i]) && ping[i] != '/' && ping[i] != '-' && ping[i] != '_' && ping[i] != '.' && ping[i] != '~') { ++ if (!isalnum((unsigned char)ping[i]) && ping[i] != '/' && ping[i] != '-' && ping[i] != '_' && ping[i] != '.' && ping[i] != '~') { + zlog(ZLOG_ERROR, "[pool %s] the ping path '%s' must containt only the following characters '[alphanum]/_-.~'", wp->config->name, ping); + return -1; + } +diff --git a/sapi/fpm/fpm/fpm_status.c b/sapi/fpm/fpm/fpm_status.c +index de8db9d..9926ebd 100644 +--- a/sapi/fpm/fpm/fpm_status.c ++++ b/sapi/fpm/fpm/fpm_status.c +@@ -483,8 +483,8 @@ int fpm_status_handle_request(void) /* {{{ */ + if (full_syntax) { + unsigned int i; + int first; +- zend_string *tmp_query_string; +- char *query_string; ++ zend_string *tmp_query_string, *tmp_request_uri_string; ++ char *query_string, *request_uri_string; + struct timeval duration, now; + #ifdef HAVE_FPM_LQ + float cpu; +@@ -511,13 +511,30 @@ int fpm_status_handle_request(void) /* {{{ */ + } + } + ++ request_uri_string = NULL; ++ tmp_request_uri_string = NULL; ++ if (proc.request_uri[0] != '\0') { ++ if (encode) { ++ tmp_request_uri_string = php_escape_html_entities_ex( ++ (unsigned char*)proc.request_uri, ++ strlen(proc.request_uri), 1, ENT_DISALLOWED | ENT_HTML_DOC_XML1 | ENT_COMPAT, ++ NULL, /* double_encode */ 1); ++ request_uri_string = ZSTR_VAL(tmp_request_uri_string); ++ } else { ++ request_uri_string = proc.request_uri; ++ } ++ } ++ + query_string = NULL; + tmp_query_string = NULL; + if (proc.query_string[0] != '\0') { + if (!encode) { + query_string = proc.query_string; + } else { +- tmp_query_string = php_escape_html_entities_ex((unsigned char *)proc.query_string, strlen(proc.query_string), 1, ENT_HTML_IGNORE_ERRORS & ENT_COMPAT, NULL, 1); ++ tmp_query_string = php_escape_html_entities_ex( ++ (unsigned char*)proc.query_string, ++ strlen(proc.query_string), 1, ENT_DISALLOWED | ENT_HTML_DOC_XML1 | ENT_COMPAT, ++ NULL, /* double_encode */ 1); + query_string = ZSTR_VAL(tmp_query_string); + } + } +@@ -545,7 +562,7 @@ int fpm_status_handle_request(void) /* {{{ */ + proc.requests, + duration.tv_sec * 1000000UL + duration.tv_usec, + proc.request_method[0] != '\0' ? proc.request_method : "-", +- proc.request_uri[0] != '\0' ? proc.request_uri : "-", ++ request_uri_string ? request_uri_string : "-", + query_string ? "?" : "", + query_string ? query_string : "", + proc.content_length, +@@ -558,6 +575,9 @@ int fpm_status_handle_request(void) /* {{{ */ + PUTS(buffer); + efree(buffer); + ++ if (tmp_request_uri_string) { ++ zend_string_free(tmp_request_uri_string); ++ } + if (tmp_query_string) { + zend_string_free(tmp_query_string); + } +diff --git a/sapi/fpm/fpm/fpm_stdio.c b/sapi/fpm/fpm/fpm_stdio.c +index ddedfb4..9d87273 100644 +--- a/sapi/fpm/fpm/fpm_stdio.c ++++ b/sapi/fpm/fpm/fpm_stdio.c +@@ -177,7 +177,7 @@ stdio_read: + if ((sizeof(FPM_STDIO_CMD_FLUSH) - cmd_pos) <= in_buf && + !memcmp(buf, &FPM_STDIO_CMD_FLUSH[cmd_pos], sizeof(FPM_STDIO_CMD_FLUSH) - cmd_pos)) { + zlog_stream_finish(log_stream); +- start = cmd_pos; ++ start = sizeof(FPM_STDIO_CMD_FLUSH) - cmd_pos; + } else { + zlog_stream_str(log_stream, &FPM_STDIO_CMD_FLUSH[0], cmd_pos); + } +diff --git a/sapi/fpm/tests/ghsa-62xp-839h-2637-ipv6-allowed-clients.phpt b/sapi/fpm/tests/ghsa-62xp-839h-2637-ipv6-allowed-clients.phpt +new file mode 100644 +index 0000000..c72f9bc +--- /dev/null ++++ b/sapi/fpm/tests/ghsa-62xp-839h-2637-ipv6-allowed-clients.phpt +@@ -0,0 +1,52 @@ ++--TEST-- ++GHSA-62xp-839h-2637: IPv6 allowed client compared on all 128 bits ++--SKIPIF-- ++ ++--FILE-- ++start(); ++$tester->expectLogStartNotices(); ++$tester->checkRequest('{{ADDR:IPv6[exact]}}', 'exact: ok', 'exact: error'); ++$tester->checkRequest('{{ADDR:IPv6[prefix]}}', 'prefix: ok', 'prefix: error'); ++$tester->terminate(); ++$tester->expectLogWarning( ++ 'child %d said into stderr: "ERROR: Connection disallowed: IP address \'::1\' has been dropped."', ++ 'prefix' ++); ++$tester->expectLogTerminatingNotices(); ++$tester->close(); ++ ++?> ++Done ++--EXPECT-- ++exact: ok ++prefix: error ++Done ++--CLEAN-- ++ +diff --git a/sapi/fpm/tests/ghsa-62xp-839h-2637-v4mapped-allowed-clients.phpt b/sapi/fpm/tests/ghsa-62xp-839h-2637-v4mapped-allowed-clients.phpt +new file mode 100644 +index 0000000..1bbb7c1 +--- /dev/null ++++ b/sapi/fpm/tests/ghsa-62xp-839h-2637-v4mapped-allowed-clients.phpt +@@ -0,0 +1,52 @@ ++--TEST-- ++GHSA-62xp-839h-2637: IPv4-mapped allowed client compared on all 128 bits ++--SKIPIF-- ++ ++--FILE-- ++start(); ++$tester->expectLogStartNotices(); ++$tester->checkRequest('{{ADDR:IPv4[exact]}}', 'exact: ok', 'exact: error'); ++$tester->checkRequest('{{ADDR:IPv4[prefix]}}', 'prefix: ok', 'prefix: error'); ++$tester->terminate(); ++$tester->expectLogWarning( ++ 'child %d said into stderr: "ERROR: Connection disallowed: IP address \'127.0.0.1\' has been dropped."', ++ 'prefix' ++); ++$tester->expectLogTerminatingNotices(); ++$tester->close(); ++ ++?> ++Done ++--EXPECT-- ++exact: ok ++prefix: error ++Done ++--CLEAN-- ++ +diff --git a/sapi/fpm/tests/ghsa-7qg2-v9fj-4mwv-status-xss.phpt b/sapi/fpm/tests/ghsa-7qg2-v9fj-4mwv-status-xss.phpt +new file mode 100644 +index 0000000..475bc13 +--- /dev/null ++++ b/sapi/fpm/tests/ghsa-7qg2-v9fj-4mwv-status-xss.phpt +@@ -0,0 +1,48 @@ ++--TEST-- ++FPM: GHSA-7qg2-v9fj-4mwv - status xss ++--SKIPIF-- ++ ++--FILE-- ++start(); ++$tester->expectLogStartNotices(); ++$responses = $tester ++ ->multiRequest([ ++ ['uri' => '/', 'query' => ''], ++ ['uri' => '/status', 'query' => 'full&html', 'delay' => 100000], ++ ]); ++var_dump(strpos($responses[1]->getBody(), '