[php-src] PHP-8.6: Merge branch 'PHP-8.5' into PHP-8.6

From: Date: Thu, 19 Nov 2026 15:27:52 +0000
Subject: [php-src] PHP-8.6: Merge branch 'PHP-8.5' into PHP-8.6
Groups: php.cvs 
Request: Send a blank email to php-cvs+get-143925@lists.php.net to get a copy of this message
Author: Jakub Zelenka (bukka) Date: 2026-11-19T16:11:39+01:00 Commit: https://github.com/php/php-src/commit/cb5c461cfdd3265367b79ec467ff5ad3683f5ae8 Raw diff: https://github.com/php/php-src/commit/cb5c461cfdd3265367b79ec467ff5ad3683f5ae8.diff Merge branch 'PHP-8.5' into PHP-8.6 * PHP-8.5: (22 commits) Fix GHSA-2fjv-p558-g82m: do not set last_fatal_error_backtrace during shutdown Fix GHSA-mg3p-mxj9-g2mm: handle uriparser failures in php_uri_parser_rfc3986_to_string() Fix GHSA-8mjj-2r7p-4hg2: UAF in debug_backtrace_get_args() on trampoline calls Fix GHSA-x8r7-mg3g-74hg: Lifetime issue in Dom\XMLDocument serialiser Revert "ext/session: Truncate session file after successful write" Skip header_over_4gib.phpt when available memory is insufficient PHP-8.3 is now for PHP 8.3.38-dev Fix GHSA-g3vh-838c-65v7: Zero PS(session_started_filename) early PHP-8.2 is now for PHP 8.2.37-dev Add NEWS entries Fix GHSA-jm4m-qfqx-967m: FPM worker stdio pipe fd closed twice Fix GHSA-mmf9-xm3v-hg2x: quadratic folded header concatenation Fix GHSA-f6gg-rchx-xw8j: mixed case HTTPS and FTPS Fix GHSA-658j-r8rw-q6mx: session.upload_progress.enabled is off by default Fix GHSA-fm2m-fjf5-v3cp: RCE via corrupted session file Fix GHSA-gr4f-wgx5-jpfv: DATEG(tzcache) use-after-free Fix GHSA-4646-p932-gw34: keep SOAP DTD alive during cleanup Fix GHSA-qc49-hpvq-g2w6: Drain unread request bodies Fix GHSA-3mg3-cr28-46gc: FPM XSS within status endpoint via user and script Fix GHSA-5j3f-64r7-f564: PATH_INFO underflow in CGI init_request_info() ... # Conflicts: # NEWS # ext/session/session.c # ext/standard/ftp_fopen_wrapper.c # ext/standard/http_fopen_wrapper.c Changed paths: A Zend/tests/GHSA-8mjj-2r7p-4hg2.phpt A ext/date/tests/GHSA-gr4f-wgx5-jpfv.phpt A ext/dom/tests/modern/xml/GHSA-x8r7-mg3g-74hg.phpt A ext/phar/tests/ghsa-68fq-fh7h-f8gr.phpt A ext/session/tests/session_ini_set_upload_progress_enabled.phpt A ext/soap/tests/GHSA-4646-p932-gw34.phpt A ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.phpt A ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.wsdl A ext/soap/tests/GHSA-q23r-hr55-xmpg.phpt A ext/standard/tests/http/ghsa-f6gg-rchx-xw8j.phpt A ext/standard/tests/streams/ghsa-f6gg-rchx-xw8j.phpt A ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-1.phpt A ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-2.phpt A ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-3.phpt A sapi/cgi/tests/ghsa-5j3f-64r7-f564.phpt A sapi/fpm/tests/ghsa-2fjv-p558-g82m-memory-limit.phpt A sapi/fpm/tests/ghsa-2fjv-p558-g82m-zlib.phpt A sapi/fpm/tests/ghsa-3mg3-cr28-46gc-status-xss.phpt A sapi/fpm/tests/ghsa-g3vh-838c-65v7.phpt A sapi/fpm/tests/unread-body-keep-conn.phpt A sapi/fpm/tests/unread-body-partial-record.phpt A sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-001.phpt A sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-002.phpt D ext/session/tests/session_files_repeated_write.phpt D ext/session/tests/session_write_failure_keeps_data.phpt M Zend/zend.c M Zend/zend_API.c M Zend/zend_builtin_functions.c M ext/dom/xml_serializer.c M ext/phar/util.c M ext/session/mod_files.c M ext/session/session.c M ext/soap/php_encoding.c M ext/soap/php_xml.c M ext/standard/ftp_fopen_wrapper.c M ext/standard/http_fopen_wrapper.c M ext/standard/tests/general_functions/header_over_4gib.phpt M ext/uri/uri_parser_rfc3986.c M ext/zend_test/php_test.h M ext/zend_test/test.c M main/SAPI.c M main/fastcgi.c M main/main.c M sapi/cgi/cgi_main.c M sapi/fpm/fpm/fpm_status.c M sapi/phpdbg/phpdbg.c M sapi/phpdbg/phpdbg_frame.c Diff: diff --git a/Zend/tests/GHSA-8mjj-2r7p-4hg2.phpt b/Zend/tests/GHSA-8mjj-2r7p-4hg2.phpt new file mode 100644 index 000000000000..1f5f34faf960 --- /dev/null +++ b/Zend/tests/GHSA-8mjj-2r7p-4hg2.phpt @@ -0,0 +1,31 @@ +--TEST-- +GHSA-8mjj-2r7p-4hg2 +--INI-- +fatal_error_backtraces=1 +zend.exception_ignore_args=0 +memory_limit=4M +opcache.jit=disable +--SKIPIF-- +<?php +if (getenv("USE_ZEND_ALLOC") === "0") die("skip requires ZendMM"); +?> +--FILE-- +<?php + +class C { + static function __callStatic($name, $args) + { + } +} + +$a = str_repeat('a', 1*1024*1024); + +// Soft OOM during CONCAT will be handled by DO_FCALL +C::test(1, 2, 3, 4, $a.$a); + +?> +--EXPECTF-- +Fatal error: Allowed memory size of %d bytes exhausted %S(tried to allocate %d bytes) in %s on line 12 +Stack trace: +#0 %s(12): C::test(1, 2, 3, 4, 'aaaaaaaaaaaaaaa...') +#1 {main} diff --git a/Zend/zend.c b/Zend/zend.c index ad08fe1a630d..4598fc63d005 100644 --- a/Zend/zend.c +++ b/Zend/zend.c @@ -1512,7 +1512,9 @@ ZEND_API ZEND_COLD void zend_error_zstr_at( } // Always clear the last backtrace. - zval_ptr_dtor(&EG(last_fatal_error_backtrace)); + if (EG(active)) { + zval_ptr_dtor(&EG(last_fatal_error_backtrace)); + } ZVAL_UNDEF(&EG(last_fatal_error_backtrace)); /* Report about uncaught exception in case of fatal errors */ @@ -1535,7 +1537,11 @@ ZEND_API ZEND_COLD void zend_error_zstr_at( } } } else if (EG(fatal_error_backtrace_on) && (type & E_FATAL_ERRORS)) { - zend_fetch_debug_backtrace(&EG(last_fatal_error_backtrace), 0, EG(exception_ignore_args) ? DEBUG_BACKTRACE_IGNORE_ARGS : 0, 0); + // EG(last_fatal_error_backtrace) is useless when the executor is + // inactive, and setting it at this point would leak. + if (EG(active)) { + zend_fetch_debug_backtrace(&EG(last_fatal_error_backtrace), 0, EG(exception_ignore_args) ? DEBUG_BACKTRACE_IGNORE_ARGS : 0, 0); + } } zend_observer_error_notify(type, error_filename, error_lineno, message); diff --git a/Zend/zend_API.c b/Zend/zend_API.c index 55aa6ae84977..0877d34c9ad0 100644 --- a/Zend/zend_API.c +++ b/Zend/zend_API.c @@ -3489,6 +3489,9 @@ ZEND_API void zend_deactivate_modules(void) /* {{{ */ if (module->request_shutdown_func) { zend_try { module->request_shutdown_func(module->type, module->module_number); + } zend_catch { + /* module shutdown is incomplete */ + _exit(1); } zend_end_try(); } } ZEND_HASH_FOREACH_END(); @@ -3499,6 +3502,9 @@ ZEND_API void zend_deactivate_modules(void) /* {{{ */ const zend_module_entry *module = *p; zend_try { module->request_shutdown_func(module->type, module->module_number); + } zend_catch { + /* module shutdown is incomplete */ + _exit(1); } zend_end_try(); p++; } diff --git a/Zend/zend_builtin_functions.c b/Zend/zend_builtin_functions.c index ad2c0dd2009a..2f37007f4be4 100644 --- a/Zend/zend_builtin_functions.c +++ b/Zend/zend_builtin_functions.c @@ -1735,7 +1735,11 @@ static bool debug_backtrace_get_args(zend_execute_data *call, zval *arg_array) / return false; } ZEND_HASH_FILL_PACKED(Z_ARRVAL_P(arg_array)) { - if (call->func->type == ZEND_USER_FUNCTION) { + /* Extra args are moved after CVs and TMPs in user functions, except + * for trampoline frames (see i_init_func_execute_data()). + */ + if (call->func->type == ZEND_USER_FUNCTION + && !(call->func->op_array.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { uint32_t first_extra_arg = MIN(num_args, call->func->op_array.num_args); if (UNEXPECTED(ZEND_CALL_INFO(call) & ZEND_CALL_HAS_SYMBOL_TABLE)) { diff --git a/ext/date/tests/GHSA-gr4f-wgx5-jpfv.phpt b/ext/date/tests/GHSA-gr4f-wgx5-jpfv.phpt new file mode 100644 index 000000000000..bb81c93ddb27 --- /dev/null +++ b/ext/date/tests/GHSA-gr4f-wgx5-jpfv.phpt @@ -0,0 +1,22 @@ +--TEST-- +GHSA-gr4f-wgx5-jpfv: DATEG(tzcache) use-after-free +--CREDITS-- +Sebastian Bergmann +--CGI-- +--ENV-- +QUERY_STRING=a=1&b=2 +--EXTENSIONS-- +session +zend_test +--INI-- +error_log="{TMP}/GHSA-gr4f-wgx5-jpfv.log" +log_errors=1 +max_input_vars=1 +zend_test.warn_on_startup=1 +--FILE-- +<?php +echo "Hello world\n"; +?> +--EXPECTF-- +Warning: PHP Request Startup: Input variables exceeded 1. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 +Hello world%r(?:\n\nWarning: Test startup warning from zend_test in Unknown on line 0)?%r diff --git a/ext/dom/tests/modern/xml/GHSA-x8r7-mg3g-74hg.phpt b/ext/dom/tests/modern/xml/GHSA-x8r7-mg3g-74hg.phpt new file mode 100644 index 000000000000..ae30e129b50c --- /dev/null +++ b/ext/dom/tests/modern/xml/GHSA-x8r7-mg3g-74hg.phpt @@ -0,0 +1,23 @@ +--TEST-- +GHSA-x8r7-mg3g-74hg (Lifetime issue in Dom\XMLDocument serialiser) +--EXTENSIONS-- +dom +--CREDITS-- +EliseZeroTwo +--FILE-- +<?php + +$doc = Dom\HTMLDocument::createFromString('<!DOCTYPE html><svg xmlns:xlink="urn:x" xlink:href="a"><g xmlns:xlink="http://www.w3.org/1999/xlink"/></svg><svg/>', LIBXML_NOERROR); +echo $doc->saveXml(), "\n"; + +$doc = Dom\XMLDocument::createFromString('<cat><kitten xmlns:cat="meow"/></cat>'); +$doc->documentElement->setAttributeNS('meow', 'miau', 'miaou'); +echo $doc->saveXml(), "\n"; + +?> +--EXPECT-- +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<!DOCTYPE html> +<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="urn:x" xmlns:ns1="http://www.w3.org/1999/xlink" ns1:href="a"><g xmlns:xlink="http://www.w3.org/1999/xlink"/></svg><svg xmlns="http://www.w3.org/2000/svg"/></body></html> +<?xml version="1.0" encoding="UTF-8"?> +<cat xmlns:ns1="meow" ns1:miau="miaou"><kitten xmlns:cat="meow"/></cat> diff --git a/ext/dom/xml_serializer.c b/ext/dom/xml_serializer.c index 72381ae4c5b4..9547a256fa37 100644 --- a/ext/dom/xml_serializer.c +++ b/ext/dom/xml_serializer.c @@ -242,6 +242,10 @@ static void dom_xml_ns_prefix_map_add( } else if (GC_REFCOUNT(list) > 1) { GC_DELREF(list); list = zend_array_dup(list); + ZEND_HASH_PACKED_FOREACH_VAL(list, zval *val) { + /* Descendant does not own the data. */ + DOM_Z_UNOWNED(val, Z_PTR_P(val)); + } ZEND_HASH_FOREACH_END(); zend_hash_str_update_ptr(map->ht, (const char *) ns, ns_length, list); } diff --git a/ext/phar/tests/ghsa-68fq-fh7h-f8gr.phpt b/ext/phar/tests/ghsa-68fq-fh7h-f8gr.phpt new file mode 100644 index 000000000000..e03123fcab2f --- /dev/null +++ b/ext/phar/tests/ghsa-68fq-fh7h-f8gr.phpt @@ -0,0 +1,122 @@ +--TEST-- +GHSA-68fq-fh7h-f8gr (OpenSSL signature bypass by downgrading the algorithm to a keyless one) +--EXTENSIONS-- +phar +openssl +--SKIPIF-- +<?php +if (!in_array("OpenSSL", Phar::getSupportedSignatures())) die("skip openssl support required"); +?> +--INI-- +phar.readonly=0 +phar.require_hash=1 +--FILE-- +<?php +$base = __DIR__ . '/' . basename(__FILE__, '.php'); +$private = openssl_pkey_get_private(file_get_contents(__DIR__ . '/files/private.pem')); +$pkey = ''; +openssl_pkey_export($private, $pkey, null, ['config' => __DIR__ . '/files/openssl.cnf']); +$pubkey = openssl_pkey_get_details($private)['key']; + +function build(string $file, string $pkey): string +{ + $phar = new Phar($file); + $phar['main.php'] = '<?php echo "GENUINE\n";'; + $phar->setStub('<?php __HALT_COMPILER();'); + $phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey); + + return file_get_contents($file); +} + +// a phar built in this process comes back from the cache, so each case is read under its own name +function open(string $file, string $archive, ?string $pubkey): void +{ + file_put_contents($file, $archive); + if ($pubkey !== null) { + file_put_contents($file . '.pubkey', $pubkey); + } + + try { + echo (new Phar($file))->getSignature()['hash_type'], "\n"; + } catch (UnexpectedValueException $e) { + echo $e->getMessage(), "\n"; + } +} + +function downgrade_phar(string $archive): string +{ + // the last 12 bytes are [length][algorithm]["GBMB"], the signature sits just before them + $siglen = unpack('V', substr($archive, -12, 4))[1]; + $message = substr($archive, 0, strlen($archive) - 12 - $siglen); + + return $message . hash('sha256', $message, true) . pack('V', 0x0003) . 'GBMB'; // 0x0003 is PHAR_SIG_SHA256 +} + +function downgrade_tar(string $archive): string +{ + for ($offset = 0; $offset + 512 <= strlen($archive); ) { + $size = (int) octdec(trim(substr($archive, $offset + 124, 12), " \0")); // octal size field of a 512 byte header + + if (rtrim(substr($archive, $offset, 100), "\0") === '.phar/signature.bin') { + // the signed message stops at this header, so rewriting the entry content leaves it alone + $blob = pack('VV', 0x0003, 32) . hash('sha256', substr($archive, 0, $offset), true); // [algorithm][digest length][digest] + + return substr_replace($archive, str_pad($blob, $size, "\0"), $offset + 512, $size); + } + + $offset += 512 + (($size + 511) & ~511); + } + + throw new RuntimeException('no signature entry'); +} + +function downgrade_zip(string $archive): string +{ + $eocd = strrpos($archive, "PK\x05\x06"); + $cdir = unpack('V', substr($archive, $eocd + 16, 4))[1]; // the eocd holds the directory offset at +16 and the archive comment length at +20 + $comment = substr($archive, $eocd + 22, unpack('v', substr($archive, $eocd + 20, 2))[1]); + + for ($record = $cdir; substr($archive, $record, 4) === "PK\x01\x02"; ) { + $namelen = unpack('v', substr($archive, $record + 28, 2))[1]; + + if (substr($archive, $record + 46, $namelen) === '.phar/signature.bin') { + $size = unpack('V', substr($archive, $record + 24, 4))[1]; + $local = unpack('V', substr($archive, $record + 42, 4))[1]; + $content = $local + 30 + unpack('v', substr($archive, $local + 26, 2))[1] + unpack('v', substr($archive, $local + 28, 2))[1]; + // the signed message is everything before the local entry plus the directory up to this record + $message = substr($archive, 0, $local) . substr($archive, $cdir, $record - $cdir) . $comment; + $blob = pack('VV', 0x0003, 32) . hash('sha256', $message, true); + + return substr_replace($archive, str_pad($blob, $size, "\0"), $content, $size); + } + + $record += 46 + $namelen + unpack('v', substr($archive, $record + 30, 2))[1] + unpack('v', substr($archive, $record + 32, 2))[1]; + } + + throw new RuntimeException('no signature entry'); +} + +foreach (['phar' => 'downgrade_phar', 'phar.tar' => 'downgrade_tar', 'phar.zip' => 'downgrade_zip'] as $suffix => $downgrade) { + $archive = build($base . '.source.' . $suffix, $pkey); + open($base . '.signed.' . $suffix, $archive, $pubkey); + open($base . '.tampered.' . $suffix, $downgrade($archive), $pubkey); + open($base . '.nokey.' . $suffix, $downgrade($archive), null); +} +?> +--CLEAN-- +<?php +$base = __DIR__ . '/' . basename(__FILE__, '.clean.php'); +foreach (glob($base . '.*.phar*') as $file) { + unlink($file); +} +?> +--EXPECTF-- +OpenSSL +phar "%stampered.phar" SHA256 signature could not be verified: openssl public key found, but the signature does not use openssl +SHA-256 +OpenSSL +phar error: tar-based phar "%stampered.phar.tar" signature cannot be verified: openssl public key found, but the signature does not use openssl +SHA-256 +OpenSSL +phar error: signature cannot be verified: openssl public key found, but the signature does not use openssl in zip-based phar "%stampered.phar.zip" +SHA-256 diff --git a/ext/phar/util.c b/ext/phar/util.c index 539b927657b3..fafe5282fda0 100644 --- a/ext/phar/util.c +++ b/ext/phar/util.c @@ -1503,6 +1503,23 @@ zend_result phar_verify_signature(php_stream *fp, size_t end_of_phar, uint32_t s php_stream_rewind(fp); + if (sig_type != PHAR_SIG_OPENSSL && sig_type != PHAR_SIG_OPENSSL_SHA256 && sig_type != PHAR_SIG_OPENSSL_SHA512) { + php_stream_statbuf ssb; + char *pfile; + bool has_pubkey; + + spprintf(&pfile, 0, "%s.pubkey", fname); + has_pubkey = php_stream_stat_path_ex(pfile, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL) == 0; + efree(pfile); + + if (has_pubkey) { + if (error) { + spprintf(error, 0, "openssl public key found, but the signature does not use openssl"); + } + return FAILURE; + } + } + switch (sig_type) { case PHAR_SIG_OPENSSL_SHA512: case PHAR_SIG_OPENSSL_SHA256: diff --git a/ext/session/mod_files.c b/ext/session/mod_files.c index 9b5b8f331dc7..15214c215d11 100644 --- a/ext/session/mod_files.c +++ b/ext/session/mod_files.c @@ -233,6 +233,11 @@ static zend_result ps_files_write(ps_files *data, zend_string *key, zend_string return FAILURE; } + if (ftruncate(data->fd, 0) != 0) { + php_error_docref(NULL, E_WARNING, "ftruncate() failed: %s (%d)", strerror(errno), errno); + return FAILURE; + } + #ifdef HAVE_PWRITE n = pwrite(data->fd, ZSTR_VAL(val), ZSTR_LEN(val), 0); #else @@ -266,12 +271,6 @@ static zend_result ps_files_write(ps_files *data, zend_string *key, zend_string return FAILURE; } - if (ZSTR_LEN(val) < data->st_size) { - php_ignore_value(ftruncate(data->fd, ZSTR_LEN(val))); - } - - data->st_size = ZSTR_LEN(val); - return SUCCESS; } diff --git a/ext/session/session.c b/ext/session/session.c index ef5e35f6669b..dbd0310d2788 100644 --- a/ext/session/session.c +++ b/ext/session/session.c @@ -94,6 +94,12 @@ zend_class_entry *php_session_update_timestamp_iface_entry; return FAILURE; \ } +#define SESSION_CHECK_UPLOAD_PROGRESS_STATE \ + if (PS(rfc1867_enabled) && stage == ZEND_INI_STAGE_RUNTIME) { \ + zend_throw_error(NULL, "Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On"); \ + return FAILURE; \ + } + #define SESSION_FORBIDDEN_CHARS "=,;.[ \t\r\n\013\014" #define SESSION_FORBIDDEN_CHARS_FOR_ERROR_MSG "=,;.[ \\t\\r\\n\\013\\014" @@ -122,6 +128,8 @@ static inline void php_rinit_session_globals(void) PS(module_number) = my_module_number; PS(in_rfc1867_update) = false; ZVAL_UNDEF(&PS(http_session_vars)); + PS(session_started_filename) = NULL; + PS(session_started_lineno) = 0; } static inline void php_session_headers_already_sent_error(int severity, const char *message) { @@ -601,6 +609,7 @@ static PHP_INI_MH(OnUpdateSaveHandler) const ps_module *new_module; int err_type = E_ERROR; + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -635,6 +644,7 @@ static PHP_INI_MH(OnUpdateSerializer) { const ps_serializer *new_serializer; + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -663,6 +673,7 @@ static PHP_INI_MH(OnUpdateSerializer) static PHP_INI_MH(OnUpdateSaveDir) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -698,6 +709,7 @@ static PHP_INI_MH(OnUpdateSaveDir) static PHP_INI_MH(OnUpdateName) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -728,6 +740,7 @@ static PHP_INI_MH(OnUpdateName) static PHP_INI_MH(OnUpdateCookieLifetime) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -757,6 +770,7 @@ static PHP_INI_MH(OnUpdateCookieLifetime) static PHP_INI_MH(OnUpdateSessionLong) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -765,6 +779,7 @@ static PHP_INI_MH(OnUpdateSessionLong) static PHP_INI_MH(OnUpdateSessionStr) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -780,6 +795,7 @@ static PHP_INI_MH(OnUpdateSessionStr) static PHP_INI_MH(OnUpdateSessionSameSite) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -794,6 +810,7 @@ static PHP_INI_MH(OnUpdateSessionSameSite) static PHP_INI_MH(OnUpdateSessionBool) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -805,6 +822,7 @@ static PHP_INI_MH(OnUpdateSidLength) zend_long val; char *endptr = NULL; + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -829,6 +847,7 @@ static PHP_INI_MH(OnUpdateSidBits) zend_long val; char *endptr = NULL; + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -850,6 +869,7 @@ static PHP_INI_MH(OnUpdateSidBits) static PHP_INI_MH(OnUpdateSessionGcProbability) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -868,6 +888,7 @@ static PHP_INI_MH(OnUpdateSessionGcProbability) static PHP_INI_MH(OnUpdateSessionDivisor) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -908,6 +929,7 @@ static PHP_INI_MH(OnUpdateRfc1867Freq) static PHP_INI_MH(OnUpdateUseOnlyCookies) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -923,6 +945,7 @@ static PHP_INI_MH(OnUpdateUseOnlyCookies) static PHP_INI_MH(OnUpdateUseTransSid) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -938,6 +961,7 @@ static PHP_INI_MH(OnUpdateUseTransSid) static PHP_INI_MH(OnUpdateRefererCheck) { + SESSION_CHECK_UPLOAD_PROGRESS_STATE; SESSION_CHECK_ACTIVE_STATE; SESSION_CHECK_OUTPUT_STATE; @@ -984,7 +1008,7 @@ PHP_INI_BEGIN() /* Upload progress */ STD_PHP_INI_BOOLEAN("session.upload_progress.enabled", - "1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals) + "0", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals) STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup", "1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_cleanup, php_ps_globals, ps_globals) STD_PHP_INI_ENTRY("session.upload_progress.prefix", @@ -2952,6 +2976,7 @@ static PHP_GINIT_FUNCTION(ps) ps_globals->serializer = NULL; ps_globals->mod_data = NULL; ps_globals->in_rfc1867_update = false; + ps_globals->rfc1867_enabled = false; ps_globals->session_status = php_session_none; ps_globals->default_mod = NULL; ps_globals->mod_user_implemented = false; diff --git a/ext/session/tests/session_files_repeated_write.phpt b/ext/session/tests/session_files_repeated_write.phpt deleted file mode 100644 index d6f3446ba27f..000000000000 --- a/ext/session/tests/session_files_repeated_write.phpt +++ /dev/null @@ -1,54 +0,0 @@ ---TEST-- -Session files handler truncates repeated writes to the current data length ---EXTENSIONS-- -session ---INI-- -session.save_handler=files -session.save_path={PWD} -session.use_cookies=0 -session.cache_limiter= -session.gc_probability=0 ---FILE-- -<?php -$id = 'session-files-repeated-write'; -$file = __DIR__ . '/sess_' . $id; -$handler = new SessionHandler(); -session_set_save_handler($handler); -$values = ['longer data', 'short', 'SHORT', 'much longer data', '']; - -for ($count = 1; $count <= count($values); $count++) { - file_put_contents($file, ''); - session_id($id); - session_start(); - foreach (array_slice($values, 0, $count) as $value) { - var_dump($handler->write($id, $value)); - } - session_abort(); - var_dump(file_get_contents($file)); -} -?> ---CLEAN-- -<?php -unlink(__DIR__ . '/sess_session-files-repeated-write'); -?> ---EXPECT-- -bool(true) -string(11) "longer data" -bool(true) -bool(true) -string(5) "short" -bool(true) -bool(true) -bool(true) -string(5) "SHORT" -bool(true) -bool(true) -bool(true) -bool(true) -string(16) "much longer data" -bool(true) -bool(true) -bool(true) -bool(true) -bool(true) -string(0) "" diff --git a/ext/session/tests/session_ini_set_upload_progress_enabled.phpt b/ext/session/tests/session_ini_set_upload_progress_enabled.phpt new file mode 100644 index 000000000000..92c35f9a3c51 --- /dev/null +++ b/ext/session/tests/session_ini_set_upload_progress_enabled.phpt @@ -0,0 +1,128 @@ +--TEST-- +ini_set() for session.* is not allowed when session.upload_progress.enabled is On +--EXTENSIONS-- +session +--SKIPIF-- +<?php include('skipif.inc'); ?> +--INI-- +error_reporting=E_ALL & ~E_DEPRECATED +session.upload_progress.enabled=1 +session.save_path= +session.name=NOTPHPSESSID +session.save_handler=files +session.serialize_handler=php_serialize +session.cookie_lifetime=42 +session.gc_probability=2 +session.cookie_path=/startup +session.cookie_secure=1 +session.sid_length=40 +session.sid_bits_per_character=5 +--FILE-- +<?php +/* The INI section above is applied at the startup stage, so these values must + * have been applied even though session.upload_progress.enabled is On. */ +echo "*** Settings applied at startup ***\n"; +foreach ([ + "session.name", + "session.serialize_handler", + "session.cookie_lifetime", + "session.gc_probability", + "session.cookie_path", + "session.cookie_secure", + "session.sid_length", + "session.sid_bits_per_character", +] as $name) { + printf("%s=%s\n", $name, var_export(ini_get($name), true)); +} + +echo "\n*** ini_set() is rejected at runtime ***\n"; + +function try_ini_set($name, $value) { + try { + var_dump(ini_set($name, $value)); + } catch (\Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; + } +} + +/* One entry per ini modify handler guarded by the check. */ +try_ini_set("session.save_path", "/tmp"); +try_ini_set("session.name", "PHPSESSID"); +try_ini_set("session.save_handler", "user"); +try_ini_set("session.serialize_handler", "php"); +try_ini_set("session.cookie_lifetime", "1"); +try_ini_set("session.gc_probability", "1"); +try_ini_set("session.cookie_path", "/runtime"); +try_ini_set("session.cookie_secure", "0"); +try_ini_set("session.sid_length", "32"); +try_ini_set("session.sid_bits_per_character", "4"); + +echo "\n*** ini_restore() is rejected at runtime ***\n"; +try { + var_dump(ini_restore("session.name")); +} catch (\Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} +var_dump(ini_get("session.name")); + +echo "\n*** Values are unchanged ***\n"; +foreach ([ + "session.name", + "session.serialize_handler", + "session.cookie_lifetime", + "session.gc_probability", + "session.cookie_path", + "session.cookie_secure", + "session.sid_length", + "session.sid_bits_per_character", +] as $name) { + printf("%s=%s\n", $name, var_export(ini_get($name), true)); +} + +echo "\n*** Non-session ini settings are unaffected ***\n"; +var_dump(ini_set("precision", "10")); +var_dump(ini_get("precision")); + +echo "Done\n"; +?> +--EXPECT-- +*** Settings applied at startup *** +session.name='NOTPHPSESSID' +session.serialize_handler='php_serialize' +session.cookie_lifetime='42' +session.gc_probability='2' +session.cookie_path='/startup' +session.cookie_secure='1' +session.sid_length='40' +session.sid_bits_per_character='5' + +*** ini_set() is rejected at runtime *** +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On + +*** ini_restore() is rejected at runtime *** +Error: Session ini settings cannot be changed at runtime when session.upload_progress.enabled is On +string(12) "NOTPHPSESSID" + +*** Values are unchanged *** +session.name='NOTPHPSESSID' +session.serialize_handler='php_serialize' +session.cookie_lifetime='42' +session.gc_probability='2' +session.cookie_path='/startup' +session.cookie_secure='1' +session.sid_length='40' +session.sid_bits_per_character='5' + +*** Non-session ini settings are unaffected *** +string(2) "14" +string(2) "10" +Done diff --git a/ext/session/tests/session_write_failure_keeps_data.phpt b/ext/session/tests/session_write_failure_keeps_data.phpt deleted file mode 100644 index 232b3e5313cf..000000000000 --- a/ext/session/tests/session_write_failure_keeps_data.phpt +++ /dev/null @@ -1,62 +0,0 @@ ---TEST-- -Session files handler must not truncate session file when write fails ---EXTENSIONS-- -session -posix -pcntl ---INI-- -error_reporting=E_ALL -display_errors=1 -session.use_strict_mode=0 -session.save_handler=files -session.serialize_handler=php ---FILE-- -<?php -$dir = __DIR__ . '/session_write_failure_keeps_data'; -mkdir($dir); -ini_set('session.save_path', $dir); - -$sid = 'write-failure'; -$file = $dir . '/sess_' . $sid; - -ob_start(); - -session_id($sid); -session_start(); -$_SESSION['data'] = 'original data'; -session_write_close(); - -$before = file_get_contents($file); -echo "Original contents: "; -var_dump($before); - -// A zero file size limit makes the next write fail before any byte lands; -// SIGXFSZ has to be ignored or the process is killed instead. -pcntl_signal(SIGXFSZ, SIG_IGN); -echo "Set file size limit to zero: "; -var_dump(posix_setrlimit(POSIX_RLIMIT_FSIZE, 0, POSIX_RLIMIT_INFINITY)); - -session_start(); -$_SESSION['data'] = 'new'; -@session_write_close(); - -// Restore the limit so that shutdown (and gcov) can write files -posix_setrlimit(POSIX_RLIMIT_FSIZE, POSIX_RLIMIT_INFINITY, POSIX_RLIMIT_INFINITY); - -echo "Contents unchanged after failed write: "; -var_dump(file_get_contents($file) === $before); - -ob_end_flush(); -?> ---CLEAN-- -<?php -$dir = __DIR__ . '/session_write_failure_keeps_data'; -foreach (glob($dir . '/sess_*') as $f) { - unlink($f); -} -rmdir($dir); -?> ---EXPECT-- -Original contents: string(26) "data|s:13:"original data";" -Set file size limit to zero: bool(true) -Contents unchanged after failed write: bool(true) diff --git a/ext/soap/php_encoding.c b/ext/soap/php_encoding.c index 05e12de5f021..0614e1d0bd86 100644 --- a/ext/soap/php_encoding.c +++ b/ext/soap/php_encoding.c @@ -2063,7 +2063,7 @@ static int calc_dimension_12(const char* str) } str++; } - return i; + return i != 0 ? i : 1; } static void soap_array_position_add_digit(int *position, int digit) diff --git a/ext/soap/php_xml.c b/ext/soap/php_xml.c index 72e562c1fd41..12a534e952d8 100644 --- a/ext/soap/php_xml.c +++ b/ext/soap/php_xml.c @@ -48,6 +48,9 @@ static void cleanup_xml_node(xmlNodePtr node) xmlUnlinkNode(trav); xmlFreeNode(trav); } + } else if (trav->type == XML_DTD_NODE) { + /* Attribute-value entity references can share content with the DTD. + * Keep it alive until the document itself is freed. */ } else if ((trav->type != XML_ELEMENT_NODE) && (trav->type != XML_CDATA_SECTION_NODE)) { xmlUnlinkNode(trav); diff --git a/ext/soap/tests/GHSA-4646-p932-gw34.phpt b/ext/soap/tests/GHSA-4646-p932-gw34.phpt new file mode 100644 index 000000000000..8e3567d9660a --- /dev/null +++ b/ext/soap/tests/GHSA-4646-p932-gw34.phpt @@ -0,0 +1,35 @@ +--TEST-- +GHSA-4646-p932-gw34: DTD entity references must not outlive their declarations +--POST-- +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE Envelope [<!ENTITY e "boom">]> +<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:ns1="urn:t"> + <SOAP-ENV:Header> + <h SOAP-ENV:actor="&e;" SOAP-ENV:mustUnderstand="1"/> + </SOAP-ENV:Header> + <SOAP-ENV:Body> + <ns1:echo_><param0 xsi:type="xsd:string">x</param0></ns1:echo_> + </SOAP-ENV:Body> +</SOAP-ENV:Envelope> +--EXTENSIONS-- +soap +--FILE-- +<?php +function echo_($x) { + return $x; +} + +$server = new SoapServer(null, [ + 'uri' => 'urn:t', + 'style' => SOAP_RPC, + 'use' => SOAP_ENCODED, +]); +$server->addFunction('echo_'); +$server->handle(); +?> +--EXPECT-- +<?xml version="1.0" encoding="UTF-8"?> +<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>DTD are not supported by SOAP</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope> diff --git a/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.phpt b/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.phpt new file mode 100644 index 000000000000..ee2591f37160 --- /dev/null +++ b/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.phpt @@ -0,0 +1,80 @@ +--TEST-- +GHSA-q23r-hr55-xmpg: Unbounded array walk on empty wsdl:arraySize +--EXTENSIONS-- +soap +--INI-- +soap.wsdl_cache_enabled=0 +--FILE-- +<?php + +const WSDL = __DIR__ . '/GHSA-q23r-hr55-xmpg-wsdl.wsdl'; + +function itemType() { return ['A', 'B', 'C']; } +function sizeOnly() { return ['A', 'B', 'C']; } + +function request(string $operation): string { + return <<<XML + <?xml version="1.0"?> + <env:Envelope + xmlns:env="http://www.w3.org/2003/05/soap-envelope" + xmlns:m="urn:arraysize"> + + <env:Body> + <m:{$operation}/> + </env:Body> + </env:Envelope> + XML; +} + +class ReplayClient extends SoapClient +{ + public function __construct(public string $arrayType) { + parent::__construct(WSDL); + } + + public function __doRequest($request, $location, $action, $version, $oneWay = false, ?string $uriParserClass = null): ?string { + return <<<XML + <?xml version="1.0"?> + <env:Envelope + xmlns:env="http://www.w3.org/2003/05/soap-envelope" + xmlns:ns1="urn:arraysize" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <env:Body> + <ns1:{$this->arrayType}Response> + <result xsi:type="ns1:{$this->arrayType}Array"> + <item xsi:type="xsd:string">A</item> + <item xsi:type="xsd:string">B</item> + <item xsi:type="xsd:string">C</item> + </result> + </ns1:{$this->arrayType}Response> + </env:Body> + </env:Envelope> + XML; + } +} + +$server = new SoapServer(WSDL); +$server->addFunction(['itemType', 'sizeOnly']); + +foreach (['itemType', 'sizeOnly'] as $operation) { + ob_start(); + $server->handle(request($operation)); + $response = ob_get_clean(); + + preg_match('/arraySize="[^"]*"/', $response, $matches); + echo 'encode ', $operation, ' => ', $matches[0] ?? 'none', "\n"; +} + +foreach (['ItemType', 'SizeOnly'] as $arrayType) { + $client = new ReplayClient($arrayType); + echo 'decode ', $arrayType, ' => ', json_encode($client->{lcfirst($arrayType)}()), "\n"; +} + +?> +--EXPECT-- +encode itemType => arraySize="3" +encode sizeOnly => arraySize="3" +decode ItemType => ["A","B","C"] +decode SizeOnly => ["A","B","C"] diff --git a/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.wsdl b/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.wsdl new file mode 100644 index 000000000000..55b5b9207f63 --- /dev/null +++ b/ext/soap/tests/GHSA-q23r-hr55-xmpg-wsdl.wsdl @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="UTF-8"?> +<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" + xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" + xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns:enc12="http://www.w3.org/2003/05/soap-encoding" + xmlns:tns="urn:arraysize" + targetNamespace="urn:arraysize"> + + <types> + <xsd:schema targetNamespace="urn:arraysize"> + <xsd:import namespace="http://www.w3.org/2003/05/soap-encoding"/> + + <xsd:complexType name="ItemTypeArray"> + <xsd:complexContent> + <xsd:restriction base="enc12:Array"> + <xsd:attribute ref="enc12:itemType" wsdl:itemType="xsd:string"/> + <xsd:attribute ref="enc12:arraySize" wsdl:arraySize=""/> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + + <xsd:complexType name="SizeOnlyArray"> + <xsd:complexContent> + <xsd:restriction base="enc12:Array"> + <xsd:attribute ref="enc12:arraySize" wsdl:arraySize=""/> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + </xsd:schema> + </types> + + <message name="emptyRequest"/> + <message name="itemTypeResponse"><part name="result" type="tns:ItemTypeArray"/></message> + <message name="sizeOnlyResponse"><part name="result" type="tns:SizeOnlyArray"/></message> + + <portType name="ArrayPortType"> + <operation name="itemType"> + <input message="tns:emptyRequest"/> + <output message="tns:itemTypeResponse"/> + </operation> + <operation name="sizeOnly"> + <input message="tns:emptyRequest"/> + <output message="tns:sizeOnlyResponse"/> + </operation> + </portType> + + <binding name="ArrayBinding" type="tns:ArrayPortType"> + <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> + <operation name="itemType"> + <soap:operation soapAction="itemType"/> + <input><soap:body use="encoded" namespace="urn:arraysize" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/></input> + <output><soap:body use="encoded" namespace="urn:arraysize" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/></output> + </operation> + <operation name="sizeOnly"> + <soap:operation soapAction="sizeOnly"/> + <input><soap:body use="encoded" namespace="urn:arraysize" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/></input> + <output><soap:body use="encoded" namespace="urn:arraysize" encodingStyle="http://www.w3.org/2003/05/soap-encoding"/></output> + </operation> + </binding> + + <service name="ArrayService"> + <port name="ArrayPort" binding="tns:ArrayBinding"> + <soap:address location="test://"/> + </port> + </service> +</definitions> diff --git a/ext/soap/tests/GHSA-q23r-hr55-xmpg.phpt b/ext/soap/tests/GHSA-q23r-hr55-xmpg.phpt new file mode 100644 index 000000000000..886b3ff9042f --- /dev/null +++ b/ext/soap/tests/GHSA-q23r-hr55-xmpg.phpt @@ -0,0 +1,65 @@ +--TEST-- +GHSA-q23r-hr55-xmpg: Out-of-bounds read on empty SOAP-ENC:arraySize +--EXTENSIONS-- +soap +--FILE-- +<?php + +function echo_back($data) { $GLOBALS['decoded'][] = $data; return null; } + +function request(string $arraySize, string $itemType = ''): string { + $itemTypeAttribute = $itemType === '' ? '' : "SOAP-ENC:itemType=\"{$itemType}\""; + + return <<<XML + <?xml version="1.0"?> + <SOAP-ENV:Envelope + xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> + <echo_back> + <data xsi:type="SOAP-ENC:Array" {$itemTypeAttribute} SOAP-ENC:arraySize="{$arraySize}"> + <item xsi:type="xsd:string">A</item> + <item xsi:type="xsd:string">B</item> + <item xsi:type="xsd:string">C</item> + </data> + </echo_back> + </SOAP-ENV:Body> + </SOAP-ENV:Envelope> + XML; +} + +function decode(SoapServer $server, string $request): string { + ob_start(); + $server->handle($request); + $response = ob_get_clean(); + + if (str_contains($response, '<SOAP-ENV:Fault>')) { + return 'fault: ' . strip_tags($response); + } + + return json_encode(array_pop($GLOBALS['decoded'])); +} + +$server = new SoapServer(null, ['uri' => 'http://test']); +$server->addFunction('echo_back'); + +$GLOBALS['decoded'] = []; + +foreach (['', ' ', 'abc', '*', '3', '2 2'] as $arraySize) { + echo var_export($arraySize, true), ' => ', decode($server, request($arraySize)), "\n"; +} + +echo "itemType => ", decode($server, request('', 'xsd:string')), "\n"; + +?> +--EXPECT-- +'' => ["A","B","C"] +' ' => ["A","B","C"] +'abc' => ["A","B","C"] +'*' => ["A","B","C"] +'3' => ["A","B","C"] +'2 2' => [["A","B"],["C"]] +itemType => ["A","B","C"] diff --git a/ext/standard/ftp_fopen_wrapper.c b/ext/standard/ftp_fopen_wrapper.c index c1341ff62662..27f665fc3491 100644 --- a/ext/standard/ftp_fopen_wrapper.c +++ b/ext/standard/ftp_fopen_wrapper.c @@ -178,7 +178,7 @@ static php_stream *php_ftp_fopen_connect(php_stream_wrapper *wrapper, const char ZEND_ASSERT(pos == NULL); #endif - use_ssl = resource->scheme && (ZSTR_LEN(resource->scheme) > 3) && ZSTR_VAL(resource->scheme)[3] == 's'; + use_ssl = resource->scheme && zend_string_equals_literal_ci(resource->scheme, "ftps"); /* use port 21 if one wasn't specified */ if (resource->port == 0) diff --git a/ext/standard/http_fopen_wrapper.c b/ext/standard/http_fopen_wrapper.c index 21a2be87571f..35d5fe01322d 100644 --- a/ext/standard/http_fopen_wrapper.c +++ b/ext/standard/http_fopen_wrapper.c @@ -252,11 +252,11 @@ static bool php_stream_http_response_header_trim(char *http_header_line, } /* 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, + * header line. It returns true if the current line was folded into the last header line, + * otherwise false. */ +static bool php_stream_http_response_headers_parse(php_stream_wrapper *wrapper, php_stream *stream, php_stream_context *context, int options, - zend_string *last_header_line, char *header_line, size_t *header_line_length, + smart_str *last_header, char *header_line, size_t *header_line_length, int response_code, zval *response_header, php_stream_http_response_header_info *header_info) { @@ -266,7 +266,7 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w 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; + return true; } /* Process folding headers if starting with a space or a tab. */ @@ -281,18 +281,15 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w /* 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_concat3( - ZSTR_VAL(last_header_line), ZSTR_LEN(last_header_line), - " ", 1, - http_folded_header_line, http_folded_header_line_length); - zend_string_efree(last_header_line); - last_header_line = extended_header_str; - /* Return new header line. */ - return last_header_line; + /* Append space and current header line to the last header line. */ + smart_str_appendc(last_header, ' '); + smart_str_appendl(last_header, http_folded_header_line, http_folded_header_line_length); + return true; } } + zend_string *last_header_line = smart_str_extract(last_header); + /* Find header separator position. */ char *last_header_value = memchr(ZSTR_VAL(last_header_line), ':', ZSTR_LEN(last_header_line)); if (last_header_value) { @@ -304,7 +301,7 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w php_stream_wrapper_log_warn(wrapper, context, options, InvalidResponse, "HTTP invalid response format (space in header name)!"); zend_string_efree(last_header_line); - return NULL; + return false; } ++last_header_name; } @@ -323,7 +320,7 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w php_stream_wrapper_log_warn(wrapper, context, options, InvalidResponse, "HTTP invalid response format (no colon in header line)!"); zend_string_efree(last_header_line); - return NULL; + return false; } bool store_header = true; @@ -348,7 +345,7 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w "HTTP Location header size is over the limit of %d bytes", HTTP_HEADER_MAX_LOCATION_SIZE); zend_string_efree(last_header_line); - return NULL; + return false; } if (header_info->location == NULL) { header_info->location = emalloc(last_header_value_len + 1); @@ -407,7 +404,7 @@ static zend_string *php_stream_http_response_headers_parse(php_stream_wrapper *w zend_string_efree(last_header_line); } - return NULL; + return false; } static inline void smart_str_append_header_value(smart_str *dest, const zend_string *value, const char *header_name) @@ -441,7 +438,7 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, zval *ua_zval = NULL, *tmpzval = NULL, ssl_proxy_peer_name; int reqok = 0; char *http_header_line = NULL; - zend_string *last_header_line_str = NULL; + smart_str last_header = {0}; php_stream_http_response_header_info header_info; char tmp_line[128]; size_t chunk_size = 0; @@ -507,7 +504,7 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, request_fulluri = zend_is_true(tmpzval); } - use_ssl = (ZSTR_LEN(resource->scheme) > 4) && ZSTR_VAL(resource->scheme)[4] == 's'; + use_ssl = zend_string_equals_literal_ci(resource->scheme, "https"); /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; @@ -1071,12 +1068,12 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, last_line = false; } - if (last_header_line_str != NULL) { + if (last_header.s != 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, + bool folded = php_stream_http_response_headers_parse(wrapper, stream, + context, options, &last_header, http_header_line, &http_header_line_length, response_code, response_header, &header_info); - if (EXPECTED(last_header_line_str == NULL)) { + if (EXPECTED(!folded)) { if (UNEXPECTED(header_info.error)) { php_stream_close(stream); stream = NULL; @@ -1100,20 +1097,20 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, } if (last_line) { /* For the last line the last header line must be NULL. */ - ZEND_ASSERT(last_header_line_str == NULL); + ZEND_ASSERT(last_header.s == 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); + smart_str_appendl(&last_header, http_header_line, http_header_line_length); } else { break; } } /* If the stream was closed early, we still want to process the last line to keep BC. */ - if (last_header_line_str != NULL) { + if (last_header.s != NULL) { php_stream_http_response_headers_parse(wrapper, stream, context, options, - last_header_line_str, NULL, NULL, response_code, response_header, &header_info); + &last_header, NULL, NULL, response_code, response_header, &header_info); } if (!reqok || (header_info.location != NULL && header_info.follow_location)) { @@ -1224,6 +1221,7 @@ static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, out: smart_str_free(&req_buf); + smart_str_free(&last_header); if (http_header_line) { efree(http_header_line); diff --git a/ext/standard/tests/general_functions/header_over_4gib.phpt b/ext/standard/tests/general_functions/header_over_4gib.phpt index 628cf9fc2516..a8bdf4b6afad 100644 --- a/ext/standard/tests/general_functions/header_over_4gib.phpt +++ b/ext/standard/tests/general_functions/header_over_4gib.phpt @@ -7,6 +7,12 @@ if (PHP_INT_SIZE != 8) die('skip this test is for 64bit platforms only'); if (getenv('SKIP_SLOW_TESTS')) die('skip slow tests excluded by request'); if (PHP_OS === 'FreeBSD') die('skip Worker does not handle OOM gracefully'); if (getenv('SKIP_MSAN')) die('skip Crashes CI with MSAN'); +// The header is duplicated, so the peak memory usage exceeds 8 GiB, which takes +// down smaller machines (e.g. 7 GB CI runners) with the OOM killer. +$memInfo = @file_get_contents('/proc/meminfo'); +if ($memInfo && preg_match('/MemAvailable:\s+(\d+) kB/', $memInfo, $m) && $m[1] < 9 * 1024 * 1024) { + die('skip Insufficient available memory (less than 9 GiB)'); +} ?> --CONFLICTS-- all diff --git a/ext/standard/tests/http/ghsa-f6gg-rchx-xw8j.phpt b/ext/standard/tests/http/ghsa-f6gg-rchx-xw8j.phpt new file mode 100644 index 000000000000..11bfa680a92e --- /dev/null +++ b/ext/standard/tests/http/ghsa-f6gg-rchx-xw8j.phpt @@ -0,0 +1,61 @@ +--TEST-- +GHSA-f6gg-rchx-xw8j: mixed-case HTTPS URLs must use TLS +--EXTENSIONS-- +openssl +--SKIPIF-- +<?php +if (!function_exists('proc_open')) die('skip proc_open() not available'); +?> +--FILE-- +<?php +$serverCode = <<<'CODE' + $server = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr); + phpt_notify_server_start($server); + + $conn = stream_socket_accept($server); + $request = fread($conn, 1); + + if ($request === "\x16") { + $result = 'TLS'; + } else { + while (($line = stream_get_line($conn, 8192, "\r\n")) !== false) { + $request .= $line . "\r\n"; + if ($line === '') { + break; + } + } + $request .= stream_get_contents($conn, strlen('opensec-sensitive-body')); + $result = str_contains($request, 'Authorization: Basic ') + && str_contains($request, 'X-Opensec-Request: validation') + && str_contains($request, 'opensec-sensitive-body') + ? 'plaintext credentials and body' + : 'unexpected plaintext request'; + } + + fclose($conn); + fclose($server); + phpt_notify(message: $result); +CODE; + +$clientCode = <<<'CODE' + $context = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'content' => 'opensec-sensitive-body', + 'header' => "X-Opensec-Request: validation\r\n", + ], + 'ssl' => [ + 'verify_peer' => false, + 'verify_peer_name' => false, + ], + ]); + var_dump(@file_get_contents('HTTPS://alice:secret@{{ ADDR }}/secret', false, $context)); + echo phpt_wait(); +CODE; + +include sprintf('%s/../../../openssl/tests/ServerClientTestCase.inc', __DIR__); +ServerClientTestCase::getInstance()->run($clientCode, $serverCode); +?> +--EXPECT-- +bool(false) +TLS diff --git a/ext/standard/tests/streams/ghsa-f6gg-rchx-xw8j.phpt b/ext/standard/tests/streams/ghsa-f6gg-rchx-xw8j.phpt new file mode 100644 index 000000000000..8c7001508c98 --- /dev/null +++ b/ext/standard/tests/streams/ghsa-f6gg-rchx-xw8j.phpt @@ -0,0 +1,34 @@ +--TEST-- +GHSA-f6gg-rchx-xw8j: mixed-case FTPS URLs must enable TLS +--EXTENSIONS-- +openssl +--SKIPIF-- +<?php +if (!function_exists('proc_open')) die('skip proc_open() not available'); +?> +--FILE-- +<?php +$serverCode = <<<'CODE' + $server = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr); + phpt_notify_server_start($server); + + $conn = stream_socket_accept($server); + fwrite($conn, "220 Ready\r\n"); + $command = stream_get_line($conn, 8192, "\r\n"); + + fclose($conn); + fclose($server); + phpt_notify(message: $command); +CODE; + +$clientCode = <<<'CODE' + var_dump(@fopen('FTPS://{{ ADDR }}/secret', 'r')); + echo phpt_wait(); +CODE; + +include sprintf('%s/../../../openssl/tests/ServerClientTestCase.inc', __DIR__); +ServerClientTestCase::getInstance()->run($clientCode, $serverCode); +?> +--EXPECT-- +bool(false) +AUTH TLS diff --git a/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-1.phpt b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-1.phpt new file mode 100644 index 000000000000..57e9e9947d40 --- /dev/null +++ b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-1.phpt @@ -0,0 +1,35 @@ +--TEST-- +GHSA-mg3p-mxj9-g2mm (Uri\Rfc3986\Uri recomposed to exactly INT_MAX characters) +--SKIPIF-- +<?php +if (!getenv('RUN_RESOURCE_HEAVY_TESTS')) die('skip resource-heavy test'); +if (getenv("SKIP_SLOW_TESTS")) die("skip slow test"); +if (PHP_INT_SIZE !== 8) die("skip this test is for 64bit platforms only"); +$memInfo = @file_get_contents('/proc/meminfo'); +if ($memInfo && preg_match('/MemAvailable:\s+(\d+) kB/', $memInfo, $m) && $m[1] < 5 * 1024 * 1024) { + die('skip Insufficient available memory (less than 5 GiB)'); +} +?> +--CONFLICTS-- +all +--INI-- +memory_limit=-1 +--FILE-- +<?php +$uri = new Uri\Rfc3986\Uri("a://b/" . str_repeat("x", 2147483647 - 6)); + +try { + $uri->toRawString(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} + +try { + $uri->toString(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} +?> +--EXPECT-- +Uri\UriError: Cannot recompose Uri\Rfc3986\Uri to a string +Uri\UriError: Cannot recompose Uri\Rfc3986\Uri to a string diff --git a/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-2.phpt b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-2.phpt new file mode 100644 index 000000000000..60755a914dfb --- /dev/null +++ b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-2.phpt @@ -0,0 +1,35 @@ +--TEST-- +GHSA-mg3p-mxj9-g2mm (Uri\Rfc3986\Uri recomposed to more than INT_MAX characters) +--SKIPIF-- +<?php +if (!getenv('RUN_RESOURCE_HEAVY_TESTS')) die('skip resource-heavy test'); +if (getenv("SKIP_SLOW_TESTS")) die("skip slow test"); +if (PHP_INT_SIZE !== 8) die("skip this test is for 64bit platforms only"); +$memInfo = @file_get_contents('/proc/meminfo'); +if ($memInfo && preg_match('/MemAvailable:\s+(\d+) kB/', $memInfo, $m) && $m[1] < 5 * 1024 * 1024) { + die('skip Insufficient available memory (less than 5 GiB)'); +} +?> +--CONFLICTS-- +all +--INI-- +memory_limit=-1 +--FILE-- +<?php +$uri = new Uri\Rfc3986\Uri("a://b/" . str_repeat("x", 2147483648 - 6)); + +try { + $uri->toRawString(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} + +try { + $uri->toString(); +} catch (Throwable $e) { + echo $e::class, ": ", $e->getMessage(), "\n"; +} +?> +--EXPECT-- +Uri\UriError: Cannot recompose Uri\Rfc3986\Uri to a string +Uri\UriError: Cannot recompose Uri\Rfc3986\Uri to a string diff --git a/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-3.phpt b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-3.phpt new file mode 100644 index 000000000000..199515635b11 --- /dev/null +++ b/ext/uri/tests/rfc3986/general/GHSA-mg3p-mxj9-g2mm-3.phpt @@ -0,0 +1,29 @@ +--TEST-- +GHSA-mg3p-mxj9-g2mm (Uri\Rfc3986\Uri recomposed to INT_MAX - 1 characters) +--SKIPIF-- +<?php +if (!getenv('RUN_RESOURCE_HEAVY_TESTS')) die('skip resource-heavy test'); +if (getenv("SKIP_SLOW_TESTS")) die("skip slow test"); +if (PHP_INT_SIZE !== 8) die("skip this test is for 64bit platforms only"); +$memInfo = @file_get_contents('/proc/meminfo'); +if ($memInfo && preg_match('/MemAvailable:\s+(\d+) kB/', $memInfo, $m) && $m[1] < 5 * 1024 * 1024) { + die('skip Insufficient available memory (less than 5 GiB)'); +} +?> +--CONFLICTS-- +all +--INI-- +memory_limit=-1 +--FILE-- +<?php +$uri = new Uri\Rfc3986\Uri("a://b/" . str_repeat("x", 2147483646 - 6)); + +$string = $uri->toRawString(); +var_dump(strlen($string)); +var_dump(substr($string, 0, 8)); +var_dump(strspn($string, "x", 6) === 2147483646 - 6); +?> +--EXPECT-- +int(2147483646) +string(8) "a://b/xx" +bool(true) diff --git a/ext/uri/uri_parser_rfc3986.c b/ext/uri/uri_parser_rfc3986.c index 94e6e0caffd3..f9e913063903 100644 --- a/ext/uri/uri_parser_rfc3986.c +++ b/ext/uri/uri_parser_rfc3986.c @@ -741,6 +741,8 @@ ZEND_ATTRIBUTE_NONNULL static void *php_uri_parser_rfc3986_clone(void *uri) ZEND_ATTRIBUTE_NONNULL static zend_string *php_uri_parser_rfc3986_to_string(void *uri, const php_uri_recomposition_mode recomposition_mode, const bool exclude_fragment) { + zend_string *uri_string = NULL; + php_uri_parser_rfc3986_uris *uriparser_uris = uri; const UriUriA *uriparser_uri; @@ -749,19 +751,30 @@ ZEND_ATTRIBUTE_NONNULL static zend_string *php_uri_parser_rfc3986_to_string(void } else { uriparser_uri = get_normalized_uri(uriparser_uris); if (UNEXPECTED(uriparser_uri == NULL)) { - return NULL; + goto fail; } } - int charsRequired = 0; - int result = uriToStringCharsRequiredA(uriparser_uri, &charsRequired); - ZEND_ASSERT(result == URI_SUCCESS); + int output_length = 0; - charsRequired++; + /* uriToStringCharsRequiredA() returns the number of characters WITHOUT the trailing NUL. */ + int result = uriToStringCharsRequiredA(uriparser_uri, &output_length); + if (UNEXPECTED(result != URI_SUCCESS)) { + goto fail; + } + if (UNEXPECTED(output_length == INT_MAX)) { + goto fail; + } - zend_string *uri_string = zend_string_alloc(charsRequired - 1, false); - result = uriToStringA(ZSTR_VAL(uri_string), uriparser_uri, charsRequired, NULL); - ZEND_ASSERT(result == URI_SUCCESS); + /* uriToStringA() expects the size of the allocation in maxChars (i.e. WITH the trailing NUL). */ + int allocation_size = output_length + 1; + + uri_string = zend_string_alloc(output_length, false); + result = uriToStringA(ZSTR_VAL(uri_string), uriparser_uri, /* maxChars */ allocation_size, /* charsWritten */ NULL); + if (UNEXPECTED(result != URI_SUCCESS)) { + /* This should be unreachable in practice. */ + goto fail; + } if (exclude_fragment) { const char *pos = zend_memrchr(ZSTR_VAL(uri_string), '#', ZSTR_LEN(uri_string)); @@ -771,6 +784,15 @@ ZEND_ATTRIBUTE_NONNULL static zend_string *php_uri_parser_rfc3986_to_string(void } } + return uri_string; + + fail: + + if (uri_string != NULL) { + zend_string_free(uri_string); + uri_string = NULL; + } + return uri_string; } diff --git a/ext/zend_test/php_test.h b/ext/zend_test/php_test.h index db6feede7caf..49061318242a 100644 --- a/ext/zend_test/php_test.h +++ b/ext/zend_test/php_test.h @@ -56,6 +56,7 @@ ZEND_BEGIN_MODULE_GLOBALS(zend_test) int register_passes; bool rearm_vm_interrupt; bool print_stderr_mshutdown; + bool warn_on_startup; zend_long limit_copy_file_range; int observe_opline_in_zendmm; zend_mm_heap* zend_orig_heap; diff --git a/ext/zend_test/test.c b/ext/zend_test/test.c index 56b0ef8bb21b..a250345f12e2 100644 --- a/ext/zend_test/test.c +++ b/ext/zend_test/test.c @@ -1669,6 +1669,17 @@ static ZEND_FUNCTION(get_open_basedir) } } +static PHP_INI_MH(OnUpdateZendTestWarnOnStartup) +{ + zend_result result = OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage); + if (result == SUCCESS) { + if (*(bool *)ZEND_INI_GET_ADDR()) { + zend_error(E_WARNING, "Test startup warning from zend_test"); + } + } + return result; +} + static ZEND_FUNCTION(zend_test_is_pcre_bundled) { ZEND_PARSE_PARAMETERS_NONE(); @@ -2271,6 +2282,7 @@ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("zend_test.str_test", "", PHP_INI_ALL, OnUpdateStr, str_test, zend_zend_test_globals, zend_test_globals) STD_PHP_INI_ENTRY("zend_test.not_empty_str_test", "val", PHP_INI_ALL, OnUpdateStrNotEmpty, not_empty_str_test, zend_zend_test_globals, zend_test_globals) STD_PHP_INI_BOOLEAN("zend_test.observe_opline_in_zendmm", "0", PHP_INI_ALL, OnUpdateZendTestObserveOplineInZendMM, observe_opline_in_zendmm, zend_zend_test_globals, zend_test_globals) + STD_PHP_INI_BOOLEAN("zend_test.warn_on_startup", "0", PHP_INI_SYSTEM, OnUpdateZendTestWarnOnStartup, warn_on_startup, zend_zend_test_globals, zend_test_globals) PHP_INI_END() void (*old_zend_execute_ex)(zend_execute_data *execute_data); diff --git a/main/SAPI.c b/main/SAPI.c index 4b84b76633c2..d43adfeac455 100644 --- a/main/SAPI.c +++ b/main/SAPI.c @@ -474,7 +474,8 @@ SAPI_API void sapi_deactivate_module(void) zend_llist_destroy(&SG(sapi_headers).headers); if (SG(request_info).request_body) { SG(request_info).request_body = NULL; - } else if (SG(server_context)) { + } + if (SG(server_context)) { if (!SG(post_read)) { /* make sure we've consumed all request input data */ char dummy[SAPI_POST_BLOCK_SIZE]; diff --git a/main/fastcgi.c b/main/fastcgi.c index 5a525a9d66be..84f5ad58d8be 100644 --- a/main/fastcgi.c +++ b/main/fastcgi.c @@ -1028,6 +1028,10 @@ static int fcgi_read_request(fcgi_request *req) int len, padding; unsigned char buf[FCGI_MAX_LENGTH+8]; + if (UNEXPECTED(req->in_len != 0)) { + return 0; + } + req->keep = 0; req->ended = 0; req->in_len = 0; @@ -1289,6 +1293,8 @@ void fcgi_close(fcgi_request *req, int force, int destroy) req->nodelay = 0; #endif req->fd = -1; + /* a partially read STDIN record does not outlive its connection */ + req->in_len = 0; req->hook.on_close(); } diff --git a/main/main.c b/main/main.c index 815edf52daee..f75223e6cc89 100644 --- a/main/main.c +++ b/main/main.c @@ -1005,15 +1005,7 @@ PHPAPI ZEND_COLD void php_log_err_with_severity(const char *log_message, int sys zend_string *error_time_str; time(&error_time); -#ifdef ZTS - if (!php_during_module_startup()) { - error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1); - } else { - error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 0); - } -#else - error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1); -#endif + error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, PG(modules_activated) && EG(active)); len = spprintf(&tmp, 0, "[%s] %s%s", ZSTR_VAL(error_time_str), log_message, PHP_EOL); #ifdef PHP_WIN32 php_flock(fd, LOCK_EX); @@ -1387,7 +1379,7 @@ static ZEND_COLD void php_error_cb(int orig_type, zend_string *error_filename, c } } - if (!Z_ISUNDEF(EG(last_fatal_error_backtrace))) { + if (EG(active) && !Z_ISUNDEF(EG(last_fatal_error_backtrace))) { backtrace = zend_trace_to_string(Z_ARRVAL(EG(last_fatal_error_backtrace)), /* include_main */ true); } diff --git a/sapi/cgi/cgi_main.c b/sapi/cgi/cgi_main.c index a79eada2728b..55e195a25442 100644 --- a/sapi/cgi/cgi_main.c +++ b/sapi/cgi/cgi_main.c @@ -1282,9 +1282,9 @@ static void init_request_info(fcgi_request *request) */ size_t slen = len - strlen(pt); size_t pilen = env_path_info ? strlen(env_path_info) : 0; - char *path_info = env_path_info ? env_path_info + pilen - slen : NULL; + char *path_info = (env_path_info && pilen > slen) ? env_path_info + pilen - slen : NULL; - if (orig_path_info != path_info) { + if (path_info && orig_path_info != path_info) { if (orig_path_info) { char old; diff --git a/sapi/cgi/tests/ghsa-5j3f-64r7-f564.phpt b/sapi/cgi/tests/ghsa-5j3f-64r7-f564.phpt new file mode 100644 index 000000000000..cab27ad5857e --- /dev/null +++ b/sapi/cgi/tests/ghsa-5j3f-64r7-f564.phpt @@ -0,0 +1,60 @@ +--TEST-- +GHSA-5j3f-64r7-f564 (PATH_INFO underflow when the stripped suffix is longer than PATH_INFO) +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php +include "include.inc"; + +$php = get_cgi_path(); +$script = __DIR__ . "/ghsa-5j3f-64r7-f564.target.php"; +file_put_contents($script, '<?php var_dump($_SERVER["PATH_INFO"] ?? null, $_SERVER["ORIG_PATH_INFO"] ?? null);'); + +function run_cgi(string $php, array $env): void { + /* Keep what is needed to start the binary (e.g. sanitizer runtime on Windows). */ + $base_env = array_filter([ + "PATH" => getenv("PATH"), + "SystemRoot" => getenv("SystemRoot"), + ], 'is_string'); + $p = proc_open( + [$php, "-n", "-d", "cgi.fix_pathinfo=1"], + [0 => ["pipe", "r"], 1 => ["pipe", "w"]], + $pipes, + null, + $env + ["REDIRECT_STATUS" => "1", "REQUEST_METHOD" => "GET"] + $base_env + ); + fclose($pipes[0]); + $out = stream_get_contents($pipes[1]); + fclose($pipes[1]); + proc_close($p); + echo substr($out, strpos($out, "\r\n\r\n") + 4); +} + +echo "Suffix shorter than PATH_INFO\n"; +run_cgi($php, ["SCRIPT_FILENAME" => "$script/b", "PATH_INFO" => "/a/b"]); + +echo "Suffix longer than PATH_INFO\n"; +run_cgi($php, ["SCRIPT_FILENAME" => "$script/xxxxxxxxxxxxxxxx", "PATH_INFO" => "/x"]); + +echo "Suffix taken from PATH_TRANSLATED\n"; +run_cgi($php, [ + "SCRIPT_FILENAME" => $php, + "PATH_TRANSLATED" => "$script/xxxxxxxxxxxxxxxx", + "REDIRECT_URL" => "/redirected", + "PATH_INFO" => "/x", +]); +?> +--CLEAN-- +<?php +@unlink(__DIR__ . "/ghsa-5j3f-64r7-f564.target.php"); +?> +--EXPECT-- +Suffix shorter than PATH_INFO +string(2) "/b" +string(4) "/a/b" +Suffix longer than PATH_INFO +string(2) "/x" +NULL +Suffix taken from PATH_TRANSLATED +string(2) "/x" +NULL diff --git a/sapi/fpm/fpm/fpm_status.c b/sapi/fpm/fpm/fpm_status.c index 118be47bfeee..0506ca102d96 100644 --- a/sapi/fpm/fpm/fpm_status.c +++ b/sapi/fpm/fpm/fpm_status.c @@ -45,6 +45,32 @@ int fpm_status_init_child(struct fpm_worker_pool_s *wp) /* {{{ */ } /* }}} */ +static char *fpm_status_escape(const char *str, bool encode_html, bool encode_json, zend_string **tmp) +{ + char *escaped; + + *tmp = NULL; + if (str[0] == '\0') { + return NULL; + } + if (encode_html) { + *tmp = php_escape_html_entities_ex((const unsigned char *) str, strlen(str), 1, + ENT_DISALLOWED | ENT_HTML_DOC_XML1 | ENT_COMPAT, NULL, /* double_encode */ 1, /* quiet */ 0); + return ZSTR_VAL(*tmp); + } + if (encode_json) { + *tmp = php_json_encode_string(str, strlen(str), PHP_JSON_INVALID_UTF8_IGNORE); + escaped = ZSTR_VAL(*tmp); + /* remove quotes around the string */ + if (ZSTR_LEN(*tmp) >= 2) { + escaped[ZSTR_LEN(*tmp) - 1] = '\0'; + ++escaped; + } + return escaped; + } + return (char *) str; +} + int fpm_status_export_to_zval(zval *status) { struct fpm_scoreboard_s *scoreboard_p; @@ -528,8 +554,10 @@ int fpm_status_handle_request(void) /* {{{ */ if (full_syntax) { unsigned int i; int first; - zend_string *tmp_query_string, *tmp_request_uri_string; - char *query_string, *request_uri_string; + zend_string *tmp_request_method_string, *tmp_request_uri_string, *tmp_query_string; + zend_string *tmp_auth_user_string, *tmp_script_filename_string; + char *request_method_string, *request_uri_string, *query_string; + char *auth_user_string, *script_filename_string; struct timeval duration, now; float cpu; @@ -554,52 +582,11 @@ int fpm_status_handle_request(void) /* {{{ */ } } - request_uri_string = NULL; - tmp_request_uri_string = NULL; - if (proc->request_uri[0] != '\0') { - if (encode_html) { - tmp_request_uri_string = php_escape_html_entities_ex( - (const unsigned char *) proc->request_uri, - strlen(proc->request_uri), 1, ENT_DISALLOWED | ENT_HTML_DOC_XML1 | ENT_COMPAT, - NULL, /* double_encode */ 1, /* quiet */ 0); - request_uri_string = ZSTR_VAL(tmp_request_uri_string); - } else if (encode_json) { - tmp_request_uri_string = php_json_encode_string(proc->request_uri, - strlen(proc->request_uri), PHP_JSON_INVALID_UTF8_IGNORE); - request_uri_string = ZSTR_VAL(tmp_request_uri_string); - /* remove quotes around the string */ - if (ZSTR_LEN(tmp_request_uri_string) >= 2) { - request_uri_string[ZSTR_LEN(tmp_request_uri_string) - 1] = '\0'; - ++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_html) { - tmp_query_string = php_escape_html_entities_ex( - (const unsigned char *) proc->query_string, - strlen(proc->query_string), 1, ENT_DISALLOWED | ENT_HTML_DOC_XML1 | ENT_COMPAT, - NULL, /* double_encode */ 1, /* quiet */ 0); - } else if (encode_json) { - tmp_query_string = php_json_encode_string(proc->query_string, - strlen(proc->query_string), PHP_JSON_INVALID_UTF8_IGNORE); - } else { - query_string = proc->query_string; - } - if (tmp_query_string) { - query_string = ZSTR_VAL(tmp_query_string); - /* remove quotes around the string */ - if (encode_json && ZSTR_LEN(tmp_query_string) >= 2) { - query_string[ZSTR_LEN(tmp_query_string) - 1] = '\0'; - ++query_string; - } - } - } + request_method_string = fpm_status_escape(proc->request_method, encode_html, encode_json, &tmp_request_method_string); + request_uri_string = fpm_status_escape(proc->request_uri, encode_html, encode_json, &tmp_request_uri_string); + query_string = fpm_status_escape(proc->query_string, encode_html, encode_json, &tmp_query_string); + auth_user_string = fpm_status_escape(proc->auth_user, encode_html, encode_json, &tmp_auth_user_string); + script_filename_string = fpm_status_escape(proc->script_filename, encode_html, encode_json, &tmp_script_filename_string); /* prevent NaN */ if (proc->cpu_duration.tv_sec == 0 && proc->cpu_duration.tv_usec == 0) { @@ -621,24 +608,33 @@ int fpm_status_handle_request(void) /* {{{ */ (unsigned long) (now_epoch - proc->start_epoch), proc->requests, (unsigned long) (duration.tv_sec * 1000000UL + duration.tv_usec), - proc->request_method[0] != '\0' ? proc->request_method : "-", + request_method_string ? request_method_string : "-", request_uri_string ? request_uri_string : "-", query_string ? "?" : "", query_string ? query_string : "", proc->content_length, - proc->auth_user[0] != '\0' ? proc->auth_user : "-", - proc->script_filename[0] != '\0' ? proc->script_filename : "-", + auth_user_string ? auth_user_string : "-", + script_filename_string ? script_filename_string : "-", proc->request_stage == FPM_REQUEST_ACCEPTING ? cpu : 0., proc->request_stage == FPM_REQUEST_ACCEPTING ? proc->memory : 0); PUTS(buffer); efree(buffer); + if (tmp_request_method_string) { + zend_string_free(tmp_request_method_string); + } if (tmp_request_uri_string) { zend_string_free(tmp_request_uri_string); } if (tmp_query_string) { zend_string_free(tmp_query_string); } + if (tmp_auth_user_string) { + zend_string_free(tmp_auth_user_string); + } + if (tmp_script_filename_string) { + zend_string_free(tmp_script_filename_string); + } } if (full_post) { diff --git a/sapi/fpm/tests/ghsa-2fjv-p558-g82m-memory-limit.phpt b/sapi/fpm/tests/ghsa-2fjv-p558-g82m-memory-limit.phpt new file mode 100644 index 000000000000..0285f76d5df2 --- /dev/null +++ b/sapi/fpm/tests/ghsa-2fjv-p558-g82m-memory-limit.phpt @@ -0,0 +1,76 @@ +--TEST-- +FPM: late memory limit shutdown error does not recreate the fatal error backtrace +--SKIPIF-- +<?php +include "skipif.inc"; +if (getenv("USE_ZEND_ALLOC") === "0") die("skip Zend MM disabled"); +?> +--FILE-- +<?php +require_once "tester.inc"; + +$cfg = <<<EOT +[global] +error_log = {{FILE:LOG}} +[unconfined] +listen = {{ADDR:UDS}} +pm = static +pm.max_children = 1 +EOT; + +$code = <<<'PHP' +<?php +if ($_SERVER['QUERY_STRING'] === 'producer') { + // The last error message is only freed after the INI entries are restored, + // so this keeps the allocation alive even without fast shutdown (debug builds). + @trigger_error(str_repeat('x', 20 * 1024 * 1024)); +} +echo getmypid(), "\n", date_default_timezone_get(); +PHP; + +$testDir = __DIR__ . '/ghsa-2fjv-p558-g82m-memory-limit-data'; +mkdir($testDir); +file_put_contents($testDir . '/producer.php', $code); +file_put_contents($testDir . '/php.ini', "[PATH=$testDir]\nmax_memory_limit=64M\nmemory_limit=64M\n"); + +$tester = new FPM\Tester($cfg, $code); +$tester->start(extraArgs: ['-c', $testDir . '/php.ini'], iniEntries: [ + 'fatal_error_backtraces' => '1', + 'display_errors' => '0', + 'log_errors' => '1', + 'date.timezone' => 'UTC', + 'max_memory_limit' => '8M', + 'memory_limit' => '8M', +]); +$tester->expectLogStartNotices(); +$body = $tester->request(address: '{{ADDR:UDS}}')->expectError(null)->getBody(); +var_dump(preg_match('/^\d+\nUTC$/D', $body) === 1); + +// Restoring the global maximum fails while the request allocation still exists. +$tester->request(query: 'producer', address: '{{ADDR:UDS}}', scriptFilename: $testDir . '/producer.php') +->expectBody($body)->expectErrorPattern( + '/\APHP message: PHP Fatal error: Failed to set memory limit to 8388608 bytes ' + . '\(Current memory usage is \d+ bytes\) in Unknown on line 0\z/' +); + +$tester->request(address: '{{ADDR:UDS}}', headers: ['PHP_VALUE' => 'date.timezone=invalid']) + ->expectBody($body) + ->expectError("PHP message: PHP Warning: PHP Request Shutdown: " + . "Invalid date.timezone value 'invalid', using 'UTC' instead in Unknown on line 0"); +$tester->terminate(); +$tester->expectLogTerminatingNotices(); +$tester->close(); +?> +Done +--EXPECT-- +bool(true) +Done +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +$testDir = __DIR__ . '/ghsa-2fjv-p558-g82m-memory-limit-data'; +@unlink($testDir . '/producer.php'); +@unlink($testDir . '/php.ini'); +@rmdir($testDir); +?> diff --git a/sapi/fpm/tests/ghsa-2fjv-p558-g82m-zlib.phpt b/sapi/fpm/tests/ghsa-2fjv-p558-g82m-zlib.phpt new file mode 100644 index 000000000000..3a2d44e61eb1 --- /dev/null +++ b/sapi/fpm/tests/ghsa-2fjv-p558-g82m-zlib.phpt @@ -0,0 +1,70 @@ +--TEST-- +FPM: late zlib shutdown error does not recreate the fatal error backtrace +--EXTENSIONS-- +zlib +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php +require_once "tester.inc"; + +$cfg = <<<EOT +[global] +error_log = {{FILE:LOG}} +[unconfined] +listen = {{ADDR:UDS}} +pm = static +pm.max_children = 1 +EOT; + +$code = <<<'PHP' +<?php +echo getmypid(), "\n", date_default_timezone_get(); +PHP; + +$testDir = __DIR__ . '/ghsa-2fjv-p558-g82m-zlib-data'; +mkdir($testDir); +file_put_contents($testDir . '/producer.php', $code); +file_put_contents($testDir . '/php.ini', "[PATH=$testDir]\nzlib.output_compression=0\noutput_handler=ob_gzhandler\n"); + +$tester = new FPM\Tester($cfg, $code); +$tester->start(extraArgs: ['-c', $testDir . '/php.ini'], extensions: ['zlib'], iniEntries: [ + 'fatal_error_backtraces' => '1', + 'display_errors' => '0', + 'log_errors' => '1', + 'date.timezone' => 'UTC', + 'zlib.output_compression' => '1', +]); +$tester->expectLogStartNotices(); +$body = $tester->request(address: '{{ADDR:UDS}}')->expectError(null)->getBody(); +var_dump(preg_match('/^\d+\nUTC$/D', $body) === 1); + +// Restore compression before output_handler to raise a late shutdown error. +$tester->request(address: '{{ADDR:UDS}}', scriptFilename: $testDir . '/producer.php') +->expectBody($body)->expectError( + 'PHP message: PHP Fatal error: PHP Request Shutdown: ' + . 'Cannot use both zlib.output_compression and output_handler together!! in Unknown on line 0' +); + +// This diagnostic occurs before the next request's executor initialization. +$tester->request(address: '{{ADDR:UDS}}', headers: ['PHP_VALUE' => 'date.timezone=invalid']) + ->expectBody($body) + ->expectError("PHP message: PHP Warning: PHP Request Shutdown: " + . "Invalid date.timezone value 'invalid', using 'UTC' instead in Unknown on line 0"); +$tester->terminate(); +$tester->expectLogTerminatingNotices(); +$tester->close(); +?> +Done +--EXPECT-- +bool(true) +Done +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +$testDir = __DIR__ . '/ghsa-2fjv-p558-g82m-zlib-data'; +@unlink($testDir . '/producer.php'); +@unlink($testDir . '/php.ini'); +@rmdir($testDir); +?> diff --git a/sapi/fpm/tests/ghsa-3mg3-cr28-46gc-status-xss.phpt b/sapi/fpm/tests/ghsa-3mg3-cr28-46gc-status-xss.phpt new file mode 100644 index 000000000000..0a40a5ad4b0a --- /dev/null +++ b/sapi/fpm/tests/ghsa-3mg3-cr28-46gc-status-xss.phpt @@ -0,0 +1,70 @@ +--TEST-- +FPM: GHSA-3mg3-cr28-46gc - status xss via request method, auth user and script filename +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php + +require_once "tester.inc"; + +$cfg = <<<EOT +[global] +error_log = {{FILE:LOG}} +[unconfined] +listen = {{ADDR}} +pm = static +pm.max_children = 3 +pm.status_path = /status +catch_workers_output = yes +EOT; + +$code = <<<EOT +<?php +usleep(300000); +EOT; + +$scriptFilename = __DIR__ . '/ghsa-3mg3-cr28-46gc-<svg>.php'; +file_put_contents($scriptFilename, $code); + +$tester = new FPM\Tester($cfg, $code); +$tester->start(); +$tester->expectLogStartNotices(); +$responses = $tester + ->multiRequest([ + [ + 'uri' => '/ghsa-3mg3-cr28-46gc-<svg>.php', + 'headers' => [ + 'REQUEST_METHOD' => '<svg>', + 'HTTP_AUTHORIZATION' => 'Basic ' . base64_encode('"<svg onload=x>:x'), + 'SCRIPT_FILENAME' => $scriptFilename, + ], + ], + ['uri' => '/status', 'query' => 'full&html', 'delay' => 100000], + ['uri' => '/status', 'query' => 'full&json', 'delay' => 100000], + ]); +var_dump(strpos($responses[1]->getBody(), '<svg')); +var_dump(substr_count($responses[1]->getBody(), '&lt;svg')); +$status = json_decode($responses[2]->getBody('application/json'), true); +foreach ($status['processes'] as $proc) { + if ($proc['request method'] === '<svg>') { + var_dump($proc['user'], $proc['script'] === $scriptFilename); + } +} +$tester->terminate(); +$tester->expectLogTerminatingNotices(); +$tester->close(); + +?> +Done +--EXPECT-- +bool(false) +int(4) +string(15) ""<svg onload=x>" +bool(true) +Done +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +@unlink(__DIR__ . '/ghsa-3mg3-cr28-46gc-<svg>.php'); +?> diff --git a/sapi/fpm/tests/ghsa-g3vh-838c-65v7.phpt b/sapi/fpm/tests/ghsa-g3vh-838c-65v7.phpt new file mode 100644 index 000000000000..cca31023418f --- /dev/null +++ b/sapi/fpm/tests/ghsa-g3vh-838c-65v7.phpt @@ -0,0 +1,94 @@ +--TEST-- +FPM: GHSA-g3vh-838c-65v7 terminates a worker after interrupted session shutdown +--EXTENSIONS-- +session +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php +require_once "tester.inc"; + +$sessionDir = __DIR__ . '/ghsa-g3vh-838c-65v7.sessions'; +mkdir($sessionDir, 0700); + +$cfg = <<<EOT +[global] +error_log = {{FILE:LOG}} +log_level = notice +[unconfined] +listen = {{ADDR:UDS}} +pm = static +pm.max_children = 1 +php_admin_value[session.save_path] = $sessionDir +php_admin_flag[opcache.enable] = off +php_admin_flag[display_errors] = off +php_admin_flag[log_errors] = off +EOT; + +$code = <<<'PHP' +<?php +if ($_SERVER['QUERY_STRING'] !== 'producer') { + echo getmypid(); + return; +} + +class ShutdownStream { + public $context; + private $fp; + + public function stream_open($path, $mode, $options, &$openedPath) { + $this->fp = fopen('/dev/null', 'w'); + return true; + } + + public function stream_write($data) { + return strlen($data); + } + + public function stream_close() { + trigger_error('session shutdown bailout', E_USER_ERROR); + } +} + +stream_wrapper_register('shutdown-test', ShutdownStream::class); +session_id('g3vh' . getmypid()); +session_start(); +$_SESSION['stream'] = fopen('shutdown-test://session', 'w'); +unset($_SESSION); + +// Finish the response before the fatal RSHUTDOWN callback runs. +echo 'producer'; +fastcgi_finish_request(); +PHP; + +$tester = new FPM\Tester($cfg, $code); +$tester->start(extensions: ['session']); +$tester->expectLogStartNotices(); +$pid = (int) $tester->request(address: '{{ADDR:UDS}}')->getBody(); +$tester->request(query: 'producer', address: '{{ADDR:UDS}}')->expectBody('producer'); +$tester->expectLogWarning( + 'child ' . $pid . ' exited with code 1 after \\d+\\.\\d+ seconds from start', + 'unconfined', + timeoutSeconds: 5 +); +$tester->expectLogNotice('child \\d+ started', 'unconfined'); +$replacement = (int) $tester->request(address: '{{ADDR:UDS}}')->getBody(); +var_dump($pid > 0 && $replacement > 0 && $replacement !== $pid); +$tester->terminate(); +$tester->expectLogTerminatingNotices(); +$tester->close(); +?> +Done +--EXPECT-- +bool(true) +Done +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +$sessionDir = __DIR__ . '/ghsa-g3vh-838c-65v7.sessions'; +foreach (glob($sessionDir . '/sess_*') as $file) { + unlink($file); +} +@rmdir($sessionDir); +?> diff --git a/sapi/fpm/tests/unread-body-keep-conn.phpt b/sapi/fpm/tests/unread-body-keep-conn.phpt new file mode 100644 index 000000000000..5d818c58c7f5 --- /dev/null +++ b/sapi/fpm/tests/unread-body-keep-conn.phpt @@ -0,0 +1,125 @@ +--TEST-- +FPM: unread request body cannot become a new request on a kept connection +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php + +require_once "tester.inc"; + +function record(int $type, string $content, int $id): string +{ + return pack('CCnnCC', 1, $type, $id, strlen($content), 0, 0) . $content; +} + +function params(array $params): string +{ + $encoded = ''; + $encodeLength = static fn(int $length): string => $length < 128 + ? chr($length) + : pack('N', $length | 0x80000000); + foreach ($params as $name => $value) { + $encoded .= $encodeLength(strlen($name)) . $encodeLength(strlen($value)) . $name . $value; + } + return $encoded; +} + +function request(int $id, bool $keep, array $params, string $stdin): string +{ + return record(1, pack('nCxxxxx', 1, $keep), $id) + . record(4, params($params), $id) + . record(4, '', $id) + . record(5, $stdin, $id) + . record(5, '', $id); +} + +function transact(string $address, string $request): string +{ + [$host, $port] = explode(':', $address); + $socket = fsockopen($host, (int) $port); + stream_set_timeout($socket, 3); + $written = 0; + while ($written < strlen($request)) { + $written += fwrite($socket, substr($request, $written)); + } + stream_socket_shutdown($socket, STREAM_SHUT_WR); + $response = stream_get_contents($socket); + fclose($socket); + return $response; +} + +$config = <<<CFG +[global] +error_log = {{FILE:LOG}} +[unconfined] +listen = {{ADDR}} +pm = static +pm.max_children = 1 +catch_workers_output = yes +CFG; + +$code = <<<'PHP' +<?php +if ($_SERVER['REMOTE_ADDR'] === '203.0.113.1') { + echo "smuggled\n"; +} else { + $input = fopen('php://input', 'r'); + echo "outer\n"; +} +PHP; + +$tester = new FPM\Tester($config, $code); +$script = $tester->makeSourceFile(); +$tester->start(); +$tester->expectLogStartNotices(); + +$hiddenParams = [ + 'GATEWAY_INTERFACE' => 'FastCGI/1.0', + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_FILENAME' => $script, + 'SCRIPT_NAME' => '/smuggled.php', + 'REQUEST_URI' => '/smuggled.php', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'REMOTE_ADDR' => '203.0.113.1', + 'CONTENT_LENGTH' => '0', +]; +$hidden = request(2, false, $hiddenParams, ''); +$body = str_pad("--B\r\nContent-Disposition: form-data\r\n\r\n", 12000, 'A'); +$body = substr_replace($body, $hidden, 5120, strlen($hidden)); + +$outerParams = [ + 'GATEWAY_INTERFACE' => 'FastCGI/1.0', + 'REQUEST_METHOD' => 'POST', + 'SCRIPT_FILENAME' => $script, + 'SCRIPT_NAME' => '/open.php', + 'REQUEST_URI' => '/open.php', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'REMOTE_ADDR' => '127.0.0.1', + 'CONTENT_TYPE' => 'multipart/form-data; boundary=B', + 'CONTENT_LENGTH' => (string) strlen($body), +]; +foreach ([false, true] as $keep) { + $response = transact($tester->getAddr(), request(1, $keep, $outerParams, $body)); + echo 'keep ', $keep ? 'on' : 'off', ': ', + str_contains($response, 'smuggled') ? 'smuggled' : 'safe', "\n"; +} + +$body = 'A' . $hidden; +$outerParams['CONTENT_TYPE'] = 'application/octet-stream'; +$outerParams['CONTENT_LENGTH'] = '1'; +$response = transact($tester->getAddr(), request(1, true, $outerParams, $body)); +echo 'partial frame: ', + str_contains($response, 'smuggled') ? 'smuggled' : 'safe', "\n"; + +$tester->terminate(); +$tester->close(); +?> +--EXPECT-- +keep off: safe +keep on: safe +partial frame: safe +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +?> diff --git a/sapi/fpm/tests/unread-body-partial-record.phpt b/sapi/fpm/tests/unread-body-partial-record.phpt new file mode 100644 index 000000000000..4f3eed4e7177 --- /dev/null +++ b/sapi/fpm/tests/unread-body-partial-record.phpt @@ -0,0 +1,127 @@ +--TEST-- +FPM: partially read STDIN record does not make the worker reject later connections +--SKIPIF-- +<?php include "skipif.inc"; ?> +--FILE-- +<?php + +require_once "tester.inc"; + +function record(int $type, string $content, int $id): string +{ + return pack('CCnnCC', 1, $type, $id, strlen($content), 0, 0) . $content; +} + +function params(array $params): string +{ + $encoded = ''; + $encodeLength = static fn(int $length): string => $length < 128 + ? chr($length) + : pack('N', $length | 0x80000000); + foreach ($params as $name => $value) { + $encoded .= $encodeLength(strlen($name)) . $encodeLength(strlen($value)) . $name . $value; + } + return $encoded; +} + +function request(int $id, bool $keep, array $params, string $stdin): string +{ + return record(1, pack('nCxxxxx', 1, $keep), $id) + . record(4, params($params), $id) + . record(4, '', $id) + . record(5, $stdin, $id) + . record(5, '', $id); +} + +function transact(string $address, string $request): string +{ + [$host, $port] = explode(':', $address); + $socket = fsockopen($host, (int) $port); + stream_set_timeout($socket, 3); + $written = 0; + while ($written < strlen($request)) { + $written += fwrite($socket, substr($request, $written)); + } + stream_socket_shutdown($socket, STREAM_SHUT_WR); + $response = stream_get_contents($socket); + fclose($socket); + return $response; +} + +$config = <<<CFG +[global] +error_log = {{FILE:LOG}} +[unconfined] +listen = {{ADDR}} +pm = static +pm.max_children = 1 +catch_workers_output = yes +CFG; + +$code = <<<'PHP' +<?php +if ($_SERVER['REMOTE_ADDR'] === '203.0.113.1') { + echo "smuggled\n"; +} else { + echo "outer ", strlen(file_get_contents('php://input')), "\n"; +} +PHP; + +$tester = new FPM\Tester($config, $code); +$script = $tester->makeSourceFile(); +$tester->start(); +$tester->expectLogStartNotices(); + +$hiddenParams = [ + 'GATEWAY_INTERFACE' => 'FastCGI/1.0', + 'REQUEST_METHOD' => 'GET', + 'SCRIPT_FILENAME' => $script, + 'SCRIPT_NAME' => '/smuggled.php', + 'REQUEST_URI' => '/smuggled.php', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'REMOTE_ADDR' => '203.0.113.1', + 'CONTENT_LENGTH' => '0', +]; +$hidden = request(2, false, $hiddenParams, ''); +$outerParams = [ + 'GATEWAY_INTERFACE' => 'FastCGI/1.0', + 'REQUEST_METHOD' => 'POST', + 'SCRIPT_FILENAME' => $script, + 'SCRIPT_NAME' => '/open.php', + 'REQUEST_URI' => '/open.php', + 'SERVER_PROTOCOL' => 'HTTP/1.1', + 'REMOTE_ADDR' => '127.0.0.1', + 'CONTENT_TYPE' => 'application/octet-stream', + 'CONTENT_LENGTH' => '1', +]; +$plainParams = ['REQUEST_METHOD' => 'GET', 'CONTENT_LENGTH' => '0'] + $outerParams; +unset($plainParams['CONTENT_TYPE']); + +/* The STDIN record is longer than CONTENT_LENGTH so it is left partially read. */ +foreach ([false, true] as $keep) { + $response = transact($tester->getAddr(), request(1, $keep, $outerParams, 'A' . $hidden)); + echo 'keep ', $keep ? 'on' : 'off', ': ', + str_contains($response, 'smuggled') ? 'smuggled' : 'safe', ', ', + str_contains($response, 'outer 1') ? 'served' : 'not served', "\n"; + /* The only worker must still serve new connections. */ + foreach ([1, 2] as $n) { + $response = transact($tester->getAddr(), request(1, false, $plainParams, '')); + echo " next connection $n: ", str_contains($response, 'outer 0') ? 'served' : 'not served', "\n"; + } +} + +$tester->terminate(); +$tester->close(); +?> +--EXPECT-- +keep off: safe, served + next connection 1: served + next connection 2: served +keep on: safe, served + next connection 1: served + next connection 2: served +--CLEAN-- +<?php +require_once "tester.inc"; +FPM\Tester::clean(); +?> diff --git a/sapi/phpdbg/phpdbg.c b/sapi/phpdbg/phpdbg.c index 539d546e9223..c7bdd1cf1546 100644 --- a/sapi/phpdbg/phpdbg.c +++ b/sapi/phpdbg/phpdbg.c @@ -119,6 +119,7 @@ static inline void php_phpdbg_globals_ctor(zend_phpdbg_globals *pg) /* {{{ */ pg->flags = PHPDBG_DEFAULT_FLAGS; memset(pg->io, 0, sizeof(pg->io)); pg->frame.num = 0; + pg->frame.generator = 0; pg->sapi_name_ptr = NULL; pg->unclean_eval = 0; diff --git a/sapi/phpdbg/phpdbg_frame.c b/sapi/phpdbg/phpdbg_frame.c index b08a877b707a..fdab924638ea 100644 --- a/sapi/phpdbg/phpdbg_frame.c +++ b/sapi/phpdbg/phpdbg_frame.c @@ -50,6 +50,12 @@ zend_string *phpdbg_compile_stackframe(zend_execute_data *ex) { uint32_t i = 0, first_extra_arg = op_array->num_args, num_args = ZEND_CALL_NUM_ARGS(ex); zval *p = ZEND_CALL_ARG(ex, 1); + if (ex->func->op_array.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) { + /* A __call/__callStatic trampoline doesn't move extra args + * behind the CVs and TMPs (see i_init_func_execute_data()). */ + first_extra_arg = num_args; + } + if (op_array->scope) { smart_str_append(&s, op_array->scope->name); smart_str_appends(&s, "::"); @@ -80,6 +86,8 @@ zend_string *phpdbg_compile_stackframe(zend_execute_data *ex) { smart_str_appends(&s, " [internal function]"); } + smart_str_0(&s); + return s.s; } diff --git a/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-001.phpt b/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-001.phpt new file mode 100644 index 000000000000..67c95706cf27 --- /dev/null +++ b/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-001.phpt @@ -0,0 +1,34 @@ +--TEST-- +GHSA-8mjj-2r7p-4hg2: phpdbg frame display for __call trampoline +--INI-- +fatal_error_backtraces=0 +zend.exception_ignore_args=1 +--PHPDBG-- +b ZEND_CALL_TRAMPOLINE +r +f 1 +f 0 +q +--EXPECTF-- +[Successful compilation of %s] +prompt> [Breakpoint #0 added at ZEND_CALL_TRAMPOLINE] +prompt> [Breakpoint #0 in ZEND_CALL_TRAMPOLINE at %s:0, hits: 1] + 00001: <?php + 00002: class C { static function __callStatic($name, $args) {} } +prompt> [Switched to frame #1: caller() at %s:5] +>00005: C::test(1, 2, 3, 4); + 00006: } + 00007:%w +prompt> [Switched to frame #0: C::test(1, 2, 3, 4) at %s:0] + 00001: <?php + 00002: class C { static function __callStatic($name, $args) {} } +prompt> +--FILE-- +<?php +class C { static function __callStatic($name, $args) {} } + +function caller() { + C::test(1, 2, 3, 4); +} + +caller(); diff --git a/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-002.phpt b/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-002.phpt new file mode 100644 index 000000000000..173e58faaa0f --- /dev/null +++ b/sapi/phpdbg/tests/GHSA-8mjj-2r7p-4hg2-002.phpt @@ -0,0 +1,31 @@ +--TEST-- +GHSA-8mjj-2r7p-4hg2: phpdbg backtrace for __call trampoline with attached symbol table +--INI-- +fatal_error_backtraces=0 +zend.exception_ignore_args=0 +--PHPDBG-- +b ZEND_CALL_TRAMPOLINE +r +i v +back +q +--EXPECTF-- +[Successful compilation of %s] +prompt> [Breakpoint #0 added at ZEND_CALL_TRAMPOLINE] +prompt> [Breakpoint #0 in ZEND_CALL_TRAMPOLINE at %s:0, hits: 1] + 00001: <?php + 00002: class C { static function __callStatic($name, $args) {} } +prompt> [Variables in C::test() (0)] +prompt> frame #0: C::test(1, 2, 3, 4) at %s:0 +frame #1: caller() at %s:5 +frame #2: {main} at %s:8 +prompt> +--FILE-- +<?php +class C { static function __callStatic($name, $args) {} } + +function caller() { + C::test(1, 2, 3, 4); +} + +caller();

« previous php.cvs (#143925) next »