diff --git a/NEWS b/NEWS index 9d420d2..56d073e 100644 --- a/NEWS +++ b/NEWS @@ -1,5 +1,101 @@ 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) + +- MBString: + . Fixed GHSA-wm6j-2649-pv75 (Null pointer dereference in + php_mb_check_encoding() via mb_ereg_search_init()). (CVE-2026-7259) + (vi3tL0u1s) + +- PDO_Firebird: + . Fixed GHSA-w476-322c-wpvm (SQL injection via NUL bytes in quoted strings). + (CVE-2025-14179) (SakiTakamachi) + +- 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) + 18 Dec 2025, PHP 8.1.34 - Curl: diff --git a/Zend/tests/GHSA-wm6j-2649-pv75.phpt b/Zend/tests/GHSA-wm6j-2649-pv75.phpt new file mode 100644 index 0000000..7257af2 --- /dev/null +++ b/Zend/tests/GHSA-wm6j-2649-pv75.phpt @@ -0,0 +1,22 @@ +--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-- +Fatal error: Uncaught ValueError: mb_regex_encoding(): Argument #1 ($encoding) must be a valid encoding, "iso-8859-11" given in %s:%d +Stack trace: +#0 %s(%d): mb_regex_encoding('iso-8859-11') +#1 {main} + thrown in %s on line %d diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c index c0cd3c9..856e81a 100644 --- a/Zend/zend_compile.c +++ b/Zend/zend_compile.c @@ -2006,7 +2006,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 ef5c50c..1c4abc9 100644 --- a/Zend/zend_operators.c +++ b/Zend/zend_operators.c @@ -2883,8 +2883,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; } @@ -2904,8 +2904,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 d8a9046..a0df54b 100644 --- a/Zend/zend_virtual_cwd.c +++ b/Zend/zend_virtual_cwd.c @@ -195,7 +195,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); @@ -273,7 +273,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; @@ -1029,6 +1029,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 */ @@ -1114,7 +1127,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; @@ -1122,13 +1135,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 728e3ba..d15c8e2 100644 --- a/Zend/zend_virtual_cwd.h +++ b/Zend/zend_virtual_cwd.h @@ -82,7 +82,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 55b3c28..380ca07 100644 --- a/ext/com_dotnet/com_extension.c +++ b/ext/com_dotnet/com_extension.c @@ -104,11 +104,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 78feb74..9c5c9d6 100644 --- a/ext/date/lib/parse_date.c +++ b/ext/date/lib/parse_date.c @@ -509,7 +509,7 @@ static timelib_sll timelib_get_nr(const char **ptr, int max_length) static void timelib_skip_day_suffix(const 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)) { @@ -792,7 +792,7 @@ static timelib_long timelib_parse_tz_cor(const char **ptr, int *tz_not_found) *tz_not_found = 1; - while (isdigit(**ptr) || **ptr == ':') { + while (isdigit((unsigned char)**ptr) || **ptr == ':') { ++*ptr; } end = *ptr; @@ -857,7 +857,7 @@ static timelib_long timelib_parse_tz_minutes(const char **ptr, timelib_time *t) } ++*ptr; - while (isdigit(**ptr)) { + while (isdigit((unsigned char)**ptr)) { ++*ptr; } @@ -25936,10 +25936,10 @@ timelib_time *timelib_strtotime(const char *s, size_t len, timelib_error_contain 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 f0db34d..a2d1236 100644 --- a/ext/date/lib/parse_date.re +++ b/ext/date/lib/parse_date.re @@ -507,7 +507,7 @@ static timelib_sll timelib_get_nr(const char **ptr, int max_length) static void timelib_skip_day_suffix(const 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)) { @@ -790,7 +790,7 @@ static timelib_long timelib_parse_tz_cor(const char **ptr, int *tz_not_found) *tz_not_found = 1; - while (isdigit(**ptr) || **ptr == ':') { + while (isdigit((unsigned char)**ptr) || **ptr == ':') { ++*ptr; } end = *ptr; @@ -855,7 +855,7 @@ static timelib_long timelib_parse_tz_minutes(const char **ptr, timelib_time *t) } ++*ptr; - while (isdigit(**ptr)) { + while (isdigit((unsigned char)**ptr)) { ++*ptr; } @@ -1938,10 +1938,10 @@ timelib_time *timelib_strtotime(const char *s, size_t len, timelib_error_contain 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 a467da3..113343f 100644 --- a/ext/date/lib/parse_iso_intervals.c +++ b/ext/date/lib/parse_iso_intervals.c @@ -948,10 +948,10 @@ void timelib_strtointerval(const 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 2a39415..0094200 100644 --- a/ext/date/lib/parse_iso_intervals.re +++ b/ext/date/lib/parse_iso_intervals.re @@ -343,10 +343,10 @@ void timelib_strtointerval(const 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 d42c69b..9949225 100644 --- a/ext/date/lib/timelib.c +++ b/ext/date/lib/timelib.c @@ -126,7 +126,7 @@ void timelib_time_tz_abbr_update(timelib_time* tm, const 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 fe58eba..4370f19 100644 --- a/ext/date/php_date.c +++ b/ext/date/php_date.c @@ -4283,6 +4283,23 @@ static bool date_period_initialize(timelib_time **st, timelib_time **et, timelib return retval; } /* }}} */ +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) { @@ -4304,7 +4321,7 @@ PHP_METHOD(DatePeriod, __construct) } dpobj = Z_PHPPERIOD_P(ZEND_THIS); - dpobj->current = NULL; + date_period_reset(dpobj); if (isostr) { if (!date_period_initialize(&(dpobj->start), &(dpobj->end), &(dpobj->interval), &recurrences, isostr, isostr_len)) { @@ -4343,6 +4360,7 @@ PHP_METHOD(DatePeriod, __construct) if (end) { DATE_CHECK_INITIALIZED(Z_PHPDATE_P(end)->time, DateTimeInterface); } + 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/filter/logical_filters.c b/ext/filter/logical_filters.c index 3db0ef4..472e276 100644 --- a/ext/filter/logical_filters.c +++ b/ext/filter/logical_filters.c @@ -528,21 +528,21 @@ static int _php_filter_validate_domain(char * domain, size_t len, zend_long flag } /* 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; } @@ -569,9 +569,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; diff --git a/ext/filter/sanitizing_filters.c b/ext/filter/sanitizing_filters.c index 7c57171..27706ae 100644 --- a/ext/filter/sanitizing_filters.c +++ b/ext/filter/sanitizing_filters.c @@ -67,7 +67,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/ftp/ftp.c b/ext/ftp/ftp.c index 9253edc..9da59ea 100644 --- a/ext/ftp/ftp.c +++ b/ext/ftp/ftp.c @@ -499,7 +499,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; } } @@ -841,7 +841,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; @@ -1144,7 +1144,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; @@ -1342,13 +1342,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 3c655a2..8efb34f 100644 --- a/ext/gd/libgd/gd_xbm.c +++ b/ext/gd/libgd/gd_xbm.c @@ -191,7 +191,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 159b3ea..adca3ed 100644 --- a/ext/intl/locale/locale_methods.c +++ b/ext/intl/locale/locale_methods.c @@ -1135,7 +1135,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/mbstring/mbstring.c b/ext/mbstring/mbstring.c index 238d74e..265356a 100644 --- a/ext/mbstring/mbstring.c +++ b/ext/mbstring/mbstring.c @@ -626,7 +626,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; } @@ -642,7 +642,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 06f65f5..5342de2 100644 --- a/ext/mbstring/php_mbregex.c +++ b/ext/mbstring/php_mbregex.c @@ -409,8 +409,13 @@ int php_mb_regex_set_mbctype(const char *encname) if (mbctype == ONIG_ENCODING_UNDEF) { return FAILURE; } + const mbfl_encoding *mbfl_enc = mbfl_name2encoding(encname); + if (mbfl_enc == NULL) { + /* Encoding supported by Oniguruma but not by mbfl */ + return FAILURE; + } MBREX(current_mbctype) = mbctype; - MBREX(current_mbctype_mbfl_encoding) = mbfl_name2encoding(encname); + MBREX(current_mbctype_mbfl_encoding) = mbfl_enc; return SUCCESS; } /* }}} */ @@ -779,7 +784,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 index d6afbb0..ff49ae8 100644 --- a/ext/mysqli/tests/fake_server.inc +++ b/ext/mysqli/tests/fake_server.inc @@ -168,11 +168,11 @@ class my_mysqli_fake_packet_generator return new my_mysqli_fake_packet_item(null, $packed_value, $is_hex); } - public function server_ok(): my_mysqli_fake_packet + public function server_ok($number = "02"): my_mysqli_fake_packet { $packet = new my_mysqli_fake_packet(); $packet->packet_length = "070000"; - $packet->packet_number = "02"; + $packet->packet_number = $number; $packet->header = "00"; // OK $packet->affected_rows = "00"; $packet->last_insert_id = "00"; @@ -181,6 +181,17 @@ class my_mysqli_fake_packet_generator return $packet; } + public function server_eof(): my_mysqli_fake_packet + { + $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(): my_mysqli_fake_packet { $packet = new my_mysqli_fake_packet(); @@ -204,6 +215,25 @@ class my_mysqli_fake_packet_generator 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(): array { $qr1 = new my_mysqli_fake_packet(); @@ -246,7 +276,6 @@ class my_mysqli_fake_packet_generator $qr1->packet_number = "01"; $qr1->field_count = "00"; // UPSERT $qr1->affected_rows = "00"; - $qr1->affected_rows = "00"; $qr1->last_insert_id = "00"; $qr1->server_status = "0000"; $qr1->warning_count = "0000"; @@ -257,6 +286,21 @@ class my_mysqli_fake_packet_generator 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): my_mysqli_fake_packet { $pr1 = new my_mysqli_fake_packet(); @@ -712,6 +756,44 @@ function my_mysqli_test_stmt_response_row_over_read_string(my_mysqli_fake_server $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, @@ -805,6 +887,114 @@ function my_mysqli_test_query_response_row_length_overflow(my_mysqli_fake_server $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): void { $conn->send_server_greetings(); @@ -818,7 +1008,401 @@ function my_mysqli_test_query_response_row_read_two_fields(my_mysqli_fake_server } } -function run_fake_server(string $test_function, int|string $port = 0): int +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, int|string $port = 0): void { $host = '127.0.0.1'; @@ -847,9 +1431,12 @@ function run_fake_server(string $test_function, int|string $port = 0): int echo "[*] Server finished\n"; } - function run_fake_server_in_background($test_function, $port = 0): my_mysqli_fake_server_process { + if ($port == 0) { + $port = (int) getenv('MYSQLI_TEST_FAKE_SERVER_PORT'); + } + $command = [PHP_BINARY, '-n', __FILE__, 'mysqli_fake_server', $test_function, $port]; $descriptorspec = array( 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..45d33cd --- /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, "", $process->getPort() ); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..63233ad --- /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, "", $process->getPort() ); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..6a18f36 --- /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, "", $process->getPort() ); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..13856f0 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-affected-rows.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..3a163ef --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id-no-space.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..9d30f04 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-last-insert-id.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..a4f5ca2 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-packet-warning-count.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..8c1415a --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-auth-switch-unterminated.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +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 +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..9a7c961 --- /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, "", $process->getPort()); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..568f1f0 --- /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, "", $process->getPort()); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..77b1983 --- /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, "", $process->getPort()); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..2554a46 --- /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, "", $process->getPort() ); +echo "[*] connect_errno: ", $conn->connect_errno, "\n"; +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..66bde99 --- /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, "", $process->getPort()); + +echo "[*] Changing user on the fake server...\n"; +var_dump($conn->change_user("root2", "", "")); + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..5a2b2c6 --- /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, "", $process->getPort()); + +echo "[*] Changing user on the fake server...\n"; +var_dump($conn->change_user("root2", "", "")); + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..e6403f5 --- /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, "", "", $process->getPort() ); + +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 on 127.0.0.1:%d +[*] 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 +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 +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..2f1f0f0 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-eof-warning-count.phpt @@ -0,0 +1,44 @@ +--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, "", $process->getPort()); + $query = "SELECT 1; SELECT 2;"; + $conn->multi_query($query); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +MySQL server has gone away +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..210ffb8 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet-string.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..7bcbd26 --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-packet.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..c85401d --- /dev/null +++ b/ext/mysqli/tests/ghsa-r6x9-5r99-36j7-greet-scramble-len.phpt @@ -0,0 +1,37 @@ +--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, "", $process->getPort() ); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Unknown error while trying to connect via tcp://127.0.0.1:%d +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..953abde --- /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, "", $process->getPort()); + var_dump($conn->select_db("php_test")); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Malformed packet +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..fe2f0c7 --- /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, "", $process->getPort()); + var_dump($conn->select_db("php_test")); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Malformed packet +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..ed33298 --- /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, "", $process->getPort()); + var_dump($conn->select_db("php_test")); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Malformed packet +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..70ce5b8 --- /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, "", $process->getPort()); + var_dump($conn->select_db("php_test")); +} catch (Exception $e) { + echo $e->getMessage() . PHP_EOL; +} + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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 +Malformed packet +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..685af99 --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..dd7a496 --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..1b1d80c --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..dc6e670 --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..0668441 --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..7e91c0d --- /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, "", $process->getPort()); + +// 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 on 127.0.0.1:%d +[*] 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..13193ab --- /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, "", $process->getPort()); + +// 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 on 127.0.0.1:%d +[*] 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..14357a3 --- /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, "", $process->getPort()); + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..d56e69b --- /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, "", $process->getPort()); + +$conn->close(); + +$process->terminate(true); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..44d61c2 --- /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, "", $process->getPort() ); + +echo "[*] Preparing statement on the fake server...\n"; +$conn->prepare("SELECT item FROM items"); + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..6975627 --- /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, "", $process->getPort() ); + +echo "[*] Preparing statement on the fake server...\n"; +$conn->prepare("SELECT item FROM items"); + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..1c71da1 --- /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, "", $process->getPort() ); + +echo "[*] Preparing statement on the fake server...\n"; +$conn->prepare("SELECT item FROM items"); + +$conn->close(); + +$process->terminate(); + +print "done!"; +?> +--EXPECTF-- +[*] Server started on 127.0.0.1:%d +[*] 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..e01dc3f --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..8e86d40 --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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..0b9335c --- /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, "", $process->getPort()); + +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 on 127.0.0.1:%d +[*] 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/mysqlnd/mysqlnd_ps.c b/ext/mysqlnd/mysqlnd_ps.c index 15ccec4..a5e88c8 100644 --- a/ext/mysqlnd/mysqlnd_ps.c +++ b/ext/mysqlnd/mysqlnd_ps.c @@ -348,6 +348,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 796516b..fbef5f2 100644 --- a/ext/mysqlnd/mysqlnd_ps_codec.c +++ b/ext/mysqlnd/mysqlnd_ps_codec.c @@ -63,7 +63,9 @@ static inline bool ps_fetch_is_packet_over_read_with_variable_length(const unsig return false; } size_t length_len = *row - p; - if (length_len > pack_len || length > pack_len - length_len) { + /* 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 true; } @@ -80,6 +82,18 @@ static inline bool ps_fetch_is_packet_over_read_with_static_length(const unsigne return false; } +/* The declared length has to cover the fixed offsets that the field type reads. */ +static inline 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 true; + } + return false; +} + /* {{{ ps_fetch_from_1_to_8_bytes */ void @@ -259,11 +273,15 @@ ps_fetch_time(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p 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; @@ -273,7 +291,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 */ @@ -309,11 +327,15 @@ ps_fetch_date(zval * zv, const MYSQLND_FIELD * const field, const unsigned int p 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; @@ -325,7 +347,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; @@ -346,11 +368,15 @@ ps_fetch_datetime(zval * zv, const MYSQLND_FIELD * const field, const unsigned i 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; @@ -360,16 +386,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; @@ -393,7 +419,7 @@ static void ps_fetch_string(zval * zv, const MYSQLND_FIELD * const field, const unsigned int pack_len, const zend_uchar ** row) { const zend_uchar *p = *row; - const zend_ulong length = php_mysqlnd_net_field_length(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; } @@ -413,7 +439,7 @@ static void ps_fetch_bit(zval * zv, const MYSQLND_FIELD * const field, const unsigned int pack_len, const zend_uchar ** row) { const zend_uchar *p = *row; - const zend_ulong length = php_mysqlnd_net_field_length(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; } diff --git a/ext/mysqlnd/mysqlnd_wireprotocol.c b/ext/mysqlnd/mysqlnd_wireprotocol.c index b4a92bb..b5a9adc 100644 --- a/ext/mysqlnd/mysqlnd_wireprotocol.c +++ b/ext/mysqlnd/mysqlnd_wireprotocol.c @@ -24,11 +24,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"; @@ -91,10 +98,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) { 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; @@ -105,14 +116,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; } } /* }}} */ @@ -120,29 +140,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) { const zend_uchar *p = (zend_uchar *)*packet; + MYSQLND_OPTIONAL_UINT64_T result; + result.has_value = false; + 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 = true; + return result; } switch (*p) { case 251: (*packet)++; - return (uint64_t) MYSQLND_NULL_LENGTH; + result.value = MYSQLND_NULL_LENGTH; + result.has_value = true; + 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 = true; + } + 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 = true; + } + 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 = true; + } + 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, @@ -374,43 +410,42 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) /* MariaDB always sends 5.5.5 before version string: 5.5.5 was never released, so just ignore it */ - if (!strncmp((char *) p, MARIADB_RPL_VERSION_HACK, sizeof(MARIADB_RPL_VERSION_HACK) - 1)) { + if (packet->header.size - (p - begin) >= sizeof(MARIADB_RPL_VERSION_HACK) - 1 && !strncmp((char *) p, MARIADB_RPL_VERSION_HACK, sizeof(MARIADB_RPL_VERSION_HACK) - 1)) { p += sizeof(MARIADB_RPL_VERSION_HACK) - 1; } - 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 */ @@ -432,6 +467,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); @@ -445,11 +483,14 @@ 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 */ size_t remaining_size = packet->header.size - (size_t)(p - buf); if (remaining_size == 0) { - /* Might be better to fail but this will fail anyway */ + /* 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 */ @@ -483,9 +524,8 @@ php_mysqlnd_greet_read(MYSQLND_CONN_DATA * conn, void * _packet) DBG_RETURN(PASS); premature_end: - DBG_ERR_FMT("GREET packet %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "GREET packet %zu 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); } /* }}} */ @@ -690,7 +730,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 @@ -701,7 +741,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, @@ -713,9 +753,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) { @@ -726,27 +771,37 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) DBG_INF_FMT("Server salt : [%zu][%.*s]", packet->new_auth_protocol_data_len, (int) 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; - 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->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))) { - /* p can get past packet size when getting field length so it needs to be checked first - * and after that it can be checked that the net_len is not greater than the packet size */ - if ((p - buf) > packet->header.size || packet->header.size - (p - buf) < net_len) { + 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); @@ -765,9 +820,8 @@ php_mysqlnd_auth_response_read(MYSQLND_CONN_DATA * conn, void * _packet) DBG_RETURN(PASS); premature_end: - DBG_ERR_FMT("OK packet %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "AUTH_RESPONSE packet %zu 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); } /* }}} */ @@ -860,12 +914,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, @@ -875,22 +929,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 { @@ -902,13 +967,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 %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "OK packet %zu 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); } /* }}} */ @@ -953,12 +1015,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, @@ -974,28 +1036,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 %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "EOF packet %zu 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); } /* }}} */ @@ -1076,13 +1135,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 @@ -1091,7 +1151,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 @@ -1099,8 +1159,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: @@ -1108,7 +1171,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. */ @@ -1120,24 +1183,34 @@ 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))) { - /* p can get past packet size when getting field length so it needs to be checked first - * and after that it can be checked that the len is not greater than the packet size */ - if ((p - buf) > packet->header.size || packet->header.size - (p - buf) < len) { + 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); @@ -1160,13 +1233,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 %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "RSET_HEADER packet %zu 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); } /* }}} */ @@ -1184,8 +1255,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; \ @@ -1229,11 +1300,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 @@ -1297,9 +1368,8 @@ php_mysqlnd_rset_field_read(MYSQLND_CONN_DATA * conn, void * _packet) } /* COM_FIELD_LIST is no longer supported so def should not be present */ - if (packet->header.size > (size_t) (p - buf) && - (len = php_mysqlnd_net_field_length(&p)) && - len != MYSQLND_NULL_LENGTH) + len = php_mysqlnd_net_field_length(&p, packet->header.size - (p - begin)); + if (len < MYSQLND_INVALID_NET_FIELD_LENGTH) { DBG_ERR_FMT("Protocol error. Server sent default for unsupported field list"); php_error_docref(NULL, E_WARNING, @@ -1367,9 +1437,8 @@ faulty_or_fake: " The server is faulty"); DBG_RETURN(FAIL); premature_end: - DBG_ERR_FMT("RSET field packet %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "Result set field packet %zu 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); } /* }}} */ @@ -1591,12 +1660,12 @@ php_mysqlnd_rowp_read_text_protocol(MYSQLND_ROW_BUFFER * row_buffer, zval * fiel 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 > packet_end || len > packet_end - p) { + } 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); @@ -1769,7 +1838,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); @@ -1854,12 +1924,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, @@ -1879,23 +1949,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); } @@ -1903,13 +1973,10 @@ php_mysqlnd_prepare_read(MYSQLND_CONN_DATA * conn, void * _packet) DBG_INF_FMT("Prepare packet read: stmt_id=" ZEND_ULONG_FMT " 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 %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "PREPARE packet %zu 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); } /* }}} */ @@ -1936,7 +2003,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 @@ -1961,11 +2028,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); @@ -1977,9 +2049,8 @@ php_mysqlnd_chg_user_read(MYSQLND_CONN_DATA * conn, void * _packet) DBG_RETURN(PASS); premature_end: - DBG_ERR_FMT("CHANGE_USER packet %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "CHANGE_USER packet %zu 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); } /* }}} */ @@ -2049,10 +2120,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); @@ -2062,9 +2133,8 @@ php_mysqlnd_sha256_pk_request_response_read(MYSQLND_CONN_DATA * conn, void * _pa DBG_RETURN(PASS); premature_end: - DBG_ERR_FMT("OK packet %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet %zu 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); } /* }}} */ @@ -2128,11 +2198,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, @@ -2144,9 +2214,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) { @@ -2163,20 +2238,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 %zu bytes shorter than expected", p - begin - packet->header.size); - php_error_docref(NULL, E_WARNING, "SHA256_PK_REQUEST_RESPONSE packet %zu 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 f24eb70..33c90f3 100644 --- a/ext/mysqlnd/mysqlnd_wireprotocol.h +++ b/ext/mysqlnd/mysqlnd_wireprotocol.h @@ -295,9 +295,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; + 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 a6a05fe..331e94b 100644 --- a/ext/openssl/openssl.c +++ b/ext/openssl/openssl.c @@ -7472,6 +7472,7 @@ static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type, const 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(); @@ -7485,7 +7486,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, false); if (!EVP_CipherUpdate(cipher_ctx, (unsigned char*)ZSTR_VAL(*poutbuf), &i, (const unsigned char *)data, (int)data_len)) { @@ -7497,7 +7510,7 @@ static int php_openssl_cipher_update(const EVP_CIPHER *cipher_type, } */ php_openssl_store_errors(); - zend_string_release_ex(*poutbuf, 0); + zend_string_release_ex(*poutbuf, false); return FAILURE; } 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..daf5b87 --- /dev/null +++ b/ext/openssl/tests/GHSA-xr7j-rvgx-xq5p.phpt @@ -0,0 +1,67 @@ +--TEST-- +GHSA-xr7j-rvgx-xq5p: OOB read in php_openssl_matches_wildcard_name() with overlapping wildcard prefix and suffix +--EXTENSIONS-- +openssl +--SKIPIF-- + +--FILE-- + [ + 'local_cert' => '%s', + ]]); + + $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); + phpt_notify_server_start($server); + + @stream_socket_accept($server, 1); + @stream_socket_accept($server, 1); +CODE; +$serverCode = sprintf($serverCode, $certFile); + +$clientCode = <<<'CODE' + $serverUri = "ssl://{{ ADDR }}"; + $clientFlags = STREAM_CLIENT_CONNECT; + $clientCtx = stream_context_create(['ssl' => [ + 'verify_peer' => false, + ]]); + + 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/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..30f4821 --- /dev/null +++ b/ext/openssl/tests/san_absent_cn_fallback.phpt @@ -0,0 +1,61 @@ +--TEST-- +Peer verification falls back to CN when the certificate has no SAN +--EXTENSIONS-- +openssl +--SKIPIF-- + +--FILE-- + [ + 'local_cert' => '%s', + ]]); + + $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); + phpt_notify_server_start($server); + + @stream_socket_accept($server, 1); + @stream_socket_accept($server, 1); +CODE; +$serverCode = sprintf($serverCode, $certFile); + +$clientCode = <<<'CODE' + $serverUri = "ssl://{{ ADDR }}"; + $clientFlags = STREAM_CLIENT_CONNECT; + $clientCtx = stream_context_create(['ssl' => [ + 'verify_peer' => false, + ]]); + + 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..ae19be4 --- /dev/null +++ b/ext/openssl/tests/san_no_cn_fallback.phpt @@ -0,0 +1,64 @@ +--TEST-- +Peer verification does not fall back to CN when the certificate has a SAN +--EXTENSIONS-- +openssl +--SKIPIF-- + +--FILE-- + [ + 'local_cert' => '%s', + ]]); + + $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); + phpt_notify_server_start($server); + + @stream_socket_accept($server, 1); + @stream_socket_accept($server, 1); +CODE; +$serverCode = sprintf($serverCode, $certFile); + +$clientCode = <<<'CODE' + $serverUri = "ssl://{{ ADDR }}"; + $clientFlags = STREAM_CLIENT_CONNECT; + $clientCtx = stream_context_create(['ssl' => [ + 'verify_peer' => false, + ]]); + + // 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 0df18f4..cca4d36 100644 --- a/ext/openssl/tests/san_peer_matching.phpt +++ b/ext/openssl/tests/san_peer_matching.phpt @@ -54,7 +54,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..9c130e7 --- /dev/null +++ b/ext/openssl/tests/san_srv_no_cn_fallback.phpt @@ -0,0 +1,57 @@ +--TEST-- +Peer verification does not fall back to CN when the certificate has an SRV-ID +--EXTENSIONS-- +openssl +--SKIPIF-- + +--FILE-- + [ + 'local_cert' => '%s', + ]]); + + $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); + phpt_notify_server_start($server); + + @stream_socket_accept($server, 1); +CODE; +$serverCode = sprintf($serverCode, $certFile); + +$clientCode = <<<'CODE' + $serverUri = "ssl://{{ ADDR }}"; + $clientFlags = STREAM_CLIENT_CONNECT; + $clientCtx = stream_context_create(['ssl' => [ + 'verify_peer' => false, + ]]); + + // 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..b621d52 --- /dev/null +++ b/ext/openssl/tests/san_uri_no_cn_fallback.phpt @@ -0,0 +1,57 @@ +--TEST-- +Peer verification does not fall back to CN when the certificate has a URI-ID +--EXTENSIONS-- +openssl +--SKIPIF-- + +--FILE-- + [ + 'local_cert' => '%s', + ]]); + + $server = stream_socket_server($serverUri, $errno, $errstr, $serverFlags, $serverCtx); + phpt_notify_server_start($server); + + @stream_socket_accept($server, 1); +CODE; +$serverCode = sprintf($serverCode, $certFile); + +$clientCode = <<<'CODE' + $serverUri = "ssl://{{ ADDR }}"; + $clientFlags = STREAM_CLIENT_CONNECT; + $clientCtx = stream_context_create(['ssl' => [ + 'verify_peer' => false, + ]]); + + // 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 6890810..253530d 100644 --- a/ext/openssl/xp_ssl.c +++ b/ext/openssl/xp_ssl.c @@ -403,8 +403,7 @@ static bool php_openssl_x509_fingerprint_match(X509 *peer, zval *val) static 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; @@ -423,7 +422,7 @@ static bool php_openssl_matches_wildcard_name(const char *subjectname, const cha 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 **/ @@ -435,7 +434,8 @@ static bool php_openssl_matches_wildcard_name(const char *subjectname, const cha } /* }}} */ -static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) /* {{{ */ +static bool php_openssl_matches_san_list( + X509 *peer, const char *subject_name, bool *has_service_id) { int i, len; unsigned char *cert_name = NULL; @@ -444,6 +444,8 @@ static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) / 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 = false; + #ifdef HAVE_IPV6_SAN /* detect if subject name is an IPv6 address and expand once if required */ char subject_name_ipv6_expanded[40]; @@ -461,6 +463,8 @@ static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) / GENERAL_NAME *san = sk_GENERAL_NAME_value(alt_names, i); if (san->type == GEN_DNS) { + *has_service_id = true; + 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); @@ -506,6 +510,16 @@ static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) / } } #endif + } else if (san->type == GEN_URI) { + *has_service_id = true; + } 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 = true; + } } } @@ -513,7 +527,6 @@ static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) / return 0; } -/* }}} */ static bool php_openssl_matches_common_name(X509 *peer, const char *subject_name) /* {{{ */ { @@ -620,8 +633,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)) { + bool has_service_id = false; + + 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 { diff --git a/ext/pcre/php_pcre.c b/ext/pcre/php_pcre.c index 6249a80..6589109 100644 --- a/ext/pcre/php_pcre.c +++ b/ext/pcre/php_pcre.c @@ -648,7 +648,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); @@ -662,7 +662,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 b18efe4..03925ab 100644 --- a/ext/pdo/pdo.c +++ b/ext/pdo/pdo.c @@ -229,7 +229,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 7f4721d..7d28235 100644 --- a/ext/pdo/pdo_sql_parser.re +++ b/ext/pdo/pdo_sql_parser.re @@ -105,7 +105,7 @@ PDO_API int pdo_parse_params(pdo_stmt_t *stmt, zend_string *inquery, zend_string if (t == PDO_PARSER_BIND) { ptrdiff_t len = s.cur - s.tok; - if ((ZSTR_VAL(inquery) < (s.cur - len)) && isalnum(*(s.cur - len - 1))) { + if ((ZSTR_VAL(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 c3c466f..ea2046a 100644 --- a/ext/pdo/pdo_stmt.c +++ b/ext/pdo/pdo_stmt.c @@ -148,7 +148,7 @@ bool pdo_stmt_describe_columns(pdo_stmt_t *stmt) /* {{{ */ stmt->columns[col].name = zend_string_separate(orig_name, 0); char *s = ZSTR_VAL(stmt->columns[col].name); while (*s != '\0') { - *s = toupper(*s); + *s = toupper((unsigned char)*s); s++; } break; diff --git a/ext/pdo_firebird/firebird_driver.c b/ext/pdo_firebird/firebird_driver.c index a446622..2588291 100644 --- a/ext/pdo_firebird/firebird_driver.c +++ b/ext/pdo_firebird/firebird_driver.c @@ -291,7 +291,7 @@ static FbTokenType getToken(const char** begin, const char* end) return ret; } -int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) +int preprocess(const zend_string* sql, char* sql_out, size_t* sql_out_len, HashTable* named_params) { bool passAsIs = 1, execBlock = 0; zend_long pindex = -1; @@ -322,7 +322,7 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) if (l > 252) { return 0; } - strncpy(ident, i, l); + memcpy(ident, i, l); ident[l] = '\0'; if (!strcasecmp(ident, "EXECUTE")) { @@ -347,7 +347,7 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) if (l > 252) { return 0; } - strncpy(ident2, i2, l); + memcpy(ident2, i2, l); ident2[l] = '\0'; execBlock = !strcasecmp(ident2, "BLOCK"); passAsIs = 0; @@ -363,11 +363,15 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) if (passAsIs) { - strcpy(sql_out, ZSTR_VAL(sql)); + memcpy(sql_out, ZSTR_VAL(sql), ZSTR_LEN(sql)); + sql_out[ZSTR_LEN(sql)] = '\0'; + *sql_out_len = ZSTR_LEN(sql); return 1; } - strncat(sql_out, start, p - start); + char *sql_out_p = sql_out; + memcpy(sql_out_p, start, p - start); + sql_out_p += p - start; while (p < end) { @@ -375,10 +379,12 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) tok = getToken(&p, end); switch (tok) { - case ttParamMark: - tok = getToken(&p, end); + case ttParamMark: { + const char* p_peek = p; + tok = getToken(&p_peek, end); if (tok == ttIdent /*|| tok == ttString*/) { + p = p_peek; ++pindex; l = p - start; /* check the length of the identifier */ @@ -387,7 +393,7 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) if (l > 253) { return 0; } - strncpy(pname, start, l); + memcpy(pname, start, l); pname[l] = '\0'; if (named_params) { @@ -396,7 +402,7 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) zend_hash_str_update(named_params, pname, l, &tmp); } - strcat(sql_out, "?"); + *sql_out_p++ = '?'; } else { @@ -406,10 +412,11 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) return 0; } ++pindex; - strncat(sql_out, start, p - start); + memcpy(sql_out_p, start, p - start); + sql_out_p += p - start; } break; - + } case ttIdent: if (execBlock) { @@ -421,11 +428,14 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) if (l > 252) { return 0; } - strncpy(ident, start, l); + memcpy(ident, start, l); ident[l] = '\0'; if (!strcasecmp(ident, "AS")) { - strncat(sql_out, start, end - start); + memcpy(sql_out_p, start, end - start); + sql_out_p += end - start; + *sql_out_p = '\0'; + *sql_out_len = sql_out_p - sql_out; return 1; } } @@ -436,7 +446,8 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) case ttComment: case ttString: case ttOther: - strncat(sql_out, start, p - start); + memcpy(sql_out_p, start, p - start); + sql_out_p += p - start; break; case ttBrokenComment: @@ -454,6 +465,8 @@ int preprocess(const zend_string* sql, char* sql_out, HashTable* named_params) break; } } + *sql_out_p = '\0'; + *sql_out_len = sql_out_p - sql_out; return 1; } @@ -663,7 +676,7 @@ free_statement: static zend_string* firebird_handle_quoter(pdo_dbh_t *dbh, const zend_string *unquoted, enum pdo_param_type paramtype) { size_t qcount = 0; - char const *co, *l, *r; + char const *co, *l; char *c; size_t quotedlen; zend_string *quoted_str; @@ -672,9 +685,15 @@ static zend_string* firebird_handle_quoter(pdo_dbh_t *dbh, const zend_string *un return zend_string_init("''", 2, 0); } + const char * const end = ZSTR_VAL(unquoted) + ZSTR_LEN(unquoted); + /* Firebird only requires single quotes to be doubled if string lengths are used */ /* count the number of ' characters */ - for (co = ZSTR_VAL(unquoted); (co = strchr(co,'\'')); qcount++, co++); + for (co = ZSTR_VAL(unquoted); co < end; co++) { + if (*co == '\'') { + qcount++; + } + } if (UNEXPECTED(ZSTR_LEN(unquoted) + 2 > ZSTR_MAX_LEN - qcount)) { return NULL; @@ -686,15 +705,14 @@ static zend_string* firebird_handle_quoter(pdo_dbh_t *dbh, const zend_string *un *c++ = '\''; /* foreach (chunk that ends in a quote) */ - for (l = ZSTR_VAL(unquoted); (r = strchr(l,'\'')); l = r+1) { - strncpy(c, l, r-l+1); - c += (r-l+1); - /* add the second quote */ - *c++ = '\''; + for (l = ZSTR_VAL(unquoted); l < end; l++) { + *c++ = *l; + if (*l == '\'') { + /* add the second quote */ + *c++ = '\''; + } } - /* copy the remainder */ - strncpy(c, l, quotedlen-(c-ZSTR_VAL(quoted_str))-1); ZSTR_VAL(quoted_str)[quotedlen-1] = '\''; ZSTR_VAL(quoted_str)[quotedlen] = '\0'; @@ -787,6 +805,7 @@ static int firebird_alloc_prepare_stmt(pdo_dbh_t *dbh, const zend_string *sql, { pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data; char *new_sql; + size_t new_sql_len; /* Firebird allows SQL statements up to 64k, so bail if it doesn't fit */ if (ZSTR_LEN(sql) > 65536) { @@ -814,14 +833,14 @@ static int firebird_alloc_prepare_stmt(pdo_dbh_t *dbh, const zend_string *sql, we need to replace :foo by ?, and store the name we just replaced */ new_sql = emalloc(ZSTR_LEN(sql)+1); new_sql[0] = '\0'; - if (!preprocess(sql, new_sql, named_params)) { + if (!preprocess(sql, new_sql, &new_sql_len, named_params)) { strcpy(dbh->error_code, "07000"); efree(new_sql); return 0; } /* prepare the statement */ - if (isc_dsql_prepare(H->isc_status, &H->tr, s, 0, new_sql, H->sql_dialect, out_sqlda)) { + if (isc_dsql_prepare(H->isc_status, &H->tr, s, new_sql_len, new_sql, H->sql_dialect, out_sqlda)) { RECORD_ERROR(dbh); efree(new_sql); return 0; diff --git a/ext/pdo_firebird/tests/ghsa-w476-322c-wpvm.phpt b/ext/pdo_firebird/tests/ghsa-w476-322c-wpvm.phpt new file mode 100644 index 0000000..41c1125 --- /dev/null +++ b/ext/pdo_firebird/tests/ghsa-w476-322c-wpvm.phpt @@ -0,0 +1,44 @@ +--TEST-- +GHSA-w476-322c-wpvm: SQL injection in pdo_firebird via NUL bytes in quoted strings +--EXTENSIONS-- +pdo_firebird +--SKIPIF-- + +--XLEAK-- +A bug in firebird causes a memory leak when calling `isc_attach_database()`. +See https://github.com/FirebirdSQL/firebird/issues/7849 +--FILE-- +exec('CREATE TABLE ghsa_w476_322c_wpvm (name VARCHAR(255))'); + +$param = $dbh->quote("\0"); +$param2 = $dbh->quote('or 1=1--'); +var_export($param); +echo("\n"); + +echo "prepare: "; +$stmt = $dbh->prepare("SELECT * FROM ghsa_w476_322c_wpvm WHERE name = {$param} AND name = {$param2}"); +$stmt->execute(); +echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)) . "\n"; + +echo "query: "; +$stmt = $dbh->query("SELECT * FROM ghsa_w476_322c_wpvm WHERE name = {$param} AND name = {$param2}"); +echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)) . "\n"; + +echo "exec: "; +$affectedRows = $dbh->exec("UPDATE ghsa_w476_322c_wpvm SET name = 'updated' WHERE name = {$param} AND name = {$param2}"); +echo $affectedRows . "\n"; +?> +--CLEAN-- +exec("DROP TABLE ghsa_w476_322c_wpvm"); +?> +--EXPECT-- +'\'' . "\0" . '\'' +prepare: [] +query: [] +exec: 0 diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c index 01fb9dd..de90b0b 100644 --- a/ext/pgsql/pgsql.c +++ b/ext/pgsql/pgsql.c @@ -4563,7 +4563,7 @@ static int php_pgsql_convert_match(const zend_string *str, const char *regex , s */ static zend_string *php_pgsql_add_quotes(zend_string *src) { - return zend_string_concat3("E'", strlen("E'"), ZSTR_VAL(src), ZSTR_LEN(src), "'", strlen("'")); + return zend_string_concat3("'", strlen("'"), ZSTR_VAL(src), ZSTR_LEN(src), "'", strlen("'")); } /* }}} */ @@ -4841,7 +4841,6 @@ PHP_PGSQL_API zend_result php_pgsql_convert(PGconn *pg_link, const zend_string * 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), &escape_err); if (escape_err) { diff --git a/ext/pgsql/tests/10pg_convert_9.phpt b/ext/pgsql/tests/10pg_convert_9.phpt index f4bfaf5..fb36e58 100644 --- a/ext/pgsql/tests/10pg_convert_9.phpt +++ b/ext/pgsql/tests/10pg_convert_9.phpt @@ -21,6 +21,8 @@ $converted = pg_convert($db, $table_name, $fields); var_dump($converted); +var_dump(pg_convert($db, $table_name, ['str' => "\\' OR 1=1"])); + /* Invalid values */ try { $converted = pg_convert($db, $table_name, [5 => 'AAA']); @@ -48,18 +50,30 @@ try { } catch (\TypeError $e) { echo $e->getMessage(), \PHP_EOL; } + +/* standard_conforming_strings = 1 */ +pg_query($db, "SET standard_conforming_strings = 1"); +var_dump(pg_convert($db, $table_name, ['str' => "\\' OR 1=1"])); ?> --EXPECT-- array(3) { [""num""]=> string(4) "1234" [""str""]=> - string(6) "E'AAA'" + string(5) "'AAA'" [""bin""]=> - string(12) "E'\\x424242'" + string(11) "'\\x424242'" +} +array(1) { + [""str""]=> + string(13) "'\\'' OR 1=1'" } Array of values must be an associative array with string keys Array of values must be an associative array with string keys Values must be of type string|int|float|bool|null, array given Values must be of type string|int|float|bool|null, stdClass given Values must be of type string|int|float|bool|null, PgSql\Connection given +array(1) { + [""str""]=> + string(12) "'\'' OR 1=1'" +} diff --git a/ext/pgsql/tests/10pg_convert_json_array.phpt b/ext/pgsql/tests/10pg_convert_json_array.phpt index 918765d..5353e04 100644 --- a/ext/pgsql/tests/10pg_convert_json_array.phpt +++ b/ext/pgsql/tests/10pg_convert_json_array.phpt @@ -32,8 +32,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 892494f..699426c 100644 --- a/ext/pgsql/tests/12pg_insert_9.phpt +++ b/ext/pgsql/tests/12pg_insert_9.phpt @@ -54,7 +54,7 @@ try { 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'); object(PgSql\Result)#%d (0) { } diff --git a/ext/pgsql/tests/14pg_update_9.phpt b/ext/pgsql/tests/14pg_update_9.phpt index d34f052..6449307 100644 --- a/ext/pgsql/tests/14pg_update_9.phpt +++ b/ext/pgsql/tests/14pg_update_9.phpt @@ -26,6 +26,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..88b37a8 --- /dev/null +++ b/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt @@ -0,0 +1,58 @@ +--TEST-- +GHSA-7qpv-r5mr-78m4: SQL injection via E'...' backslash breakout +--CREDITS-- +expatch.llc +--EXTENSIONS-- +pgsql +--SKIPIF-- + +--FILE-- + "zzz' OR 1=1 --"]; +echo pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_STRING) . "\n"; +printf("returned: %d\n\n", count(pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params))); + +$params = ['name' => "zzz\\' OR 1=1 --"]; +echo pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_STRING) . "\n"; +printf("returned: %d\n\n", count(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']); +echo "\n"; + +$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-- +SELECT * FROM "ghsa_7qpv_r5mr_78m4" WHERE "name"='zzz'' OR 1=1 --'; +returned: 0 + +SELECT * FROM "ghsa_7qpv_r5mr_78m4" WHERE "name"='zzz\'' OR 1=1 --'; +returned: 0 + +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 ebf878d..ba27091 100644 --- a/ext/pgsql/tests/bug64609.phpt +++ b/ext/pgsql/tests/bug64609.phpt @@ -28,5 +28,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 d95fa1e..2a1025c 100644 --- a/ext/pgsql/tests/bug68638.phpt +++ b/ext/pgsql/tests/bug68638.phpt @@ -34,7 +34,7 @@ pg_query($conn, "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/phar/phar_internal.h b/ext/phar/phar_internal.h index 30b408a..81245a3 100644 --- a/ext/phar/phar_internal.h +++ b/ext/phar/phar_internal.h @@ -115,8 +115,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 80a17d6..7830819 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 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 false; + default: + return true; + } +} + +static 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 false; + } + + 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 false; + } + + *result = (uint32_t) num; + return true; +} + /* adapted from format_octal() in libarchive * * Copyright (c) 2003-2009 Tim Kientzle @@ -277,8 +323,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)) { @@ -366,13 +436,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); } @@ -583,7 +653,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/tar/GHSA-j3wh-g957-2m85-longlink.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt new file mode 100644 index 0000000..5d05ac3 --- /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) +--EXTENSIONS-- +phar +--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..731422a --- /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) +--EXTENSIONS-- +phar +--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..227d33a --- /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) +--EXTENSIONS-- +phar +--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..cf0048c --- /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 +--EXTENSIONS-- +phar +--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 753c8d3..62eba21 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/soap/php_encoding.c b/ext/soap/php_encoding.c index 4d389a8..cc8b58e 100644 --- a/ext/soap/php_encoding.c +++ b/ext/soap/php_encoding.c @@ -365,6 +365,7 @@ static 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); } } @@ -551,7 +552,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; } @@ -2710,7 +2716,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"); } @@ -3432,18 +3438,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 5f964ee..63a3b6d 100644 --- a/ext/soap/php_http.c +++ b/ext/soap/php_http.c @@ -1117,7 +1117,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)); @@ -1405,7 +1405,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: "); @@ -1435,14 +1436,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); } @@ -1450,7 +1451,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, false); } else { http_buf = zend_string_alloc(buf_size, 0); } @@ -1509,7 +1510,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); @@ -1524,7 +1525,11 @@ static zend_string* get_http_body(php_stream *stream, int close, char *headers) do { ssize_t len_read; if (http_buf) { - http_buf = zend_string_realloc(http_buf, http_buf_size + 4096, 0); + 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, false); } else { http_buf = zend_string_alloc(4096, 0); } diff --git a/ext/soap/php_soap.h b/ext/soap/php_soap.h index 33a071e..e14916c 100644 --- a/ext/soap/php_soap.h +++ b/ext/soap/php_soap.h @@ -150,6 +150,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 */ @@ -175,6 +177,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 20fd91a..340dbd8 100644 --- a/ext/soap/php_xml.c +++ b/ext/soap/php_xml.c @@ -35,36 +35,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) { @@ -125,6 +161,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; @@ -175,6 +220,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); @@ -297,6 +349,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); @@ -304,11 +358,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 3bc713c..728e85b 100644 --- a/ext/soap/soap.c +++ b/ext/soap/soap.c @@ -320,6 +320,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) @@ -1477,13 +1478,21 @@ PHP_METHOD(SoapServer, handle) php_output_discard(); soap_server_fault_ex(function, &h->retval, h); zend_string_release(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); zend_string_release(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) { 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..a8e9647 --- /dev/null +++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt @@ -0,0 +1,53 @@ +--TEST-- +GHSA-rgrp-mwpx-f6rm: Stack overflow on a chain of href references +--EXTENSIONS-- +soap +--SKIPIF-- + +--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..9d27b4a --- /dev/null +++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt @@ -0,0 +1,49 @@ +--TEST-- +GHSA-rgrp-mwpx-f6rm: Stack overflow on an array element referencing its own array +--EXTENSIONS-- +soap +--SKIPIF-- + +--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..c96b67b --- /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/standard/dl.c b/ext/standard/dl.c index 0df3848..babab64 100644 --- a/ext/standard/dl.c +++ b/ext/standard/dl.c @@ -93,7 +93,7 @@ PHPAPI void *php_load_shlib(const 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/exec.c b/ext/standard/exec.c index 1831b8e..156eaa2 100644 --- a/ext/standard/exec.c +++ b/ext/standard/exec.c @@ -83,7 +83,7 @@ PHP_MINIT_FUNCTION(exec) static size_t strip_trailing_whitespace(char *buf, size_t bufl) { size_t l = bufl; - while (l-- > 0 && isspace(((unsigned char *)buf)[l])); + while (l-- > 0 && isspace((unsigned char)buf[l])); if (l != (bufl - 1)) { bufl = l + 1; buf[bufl] = '\0'; diff --git a/ext/standard/file.c b/ext/standard/file.c index 8bab360..bf20702 100644 --- a/ext/standard/file.c +++ b/ext/standard/file.c @@ -2086,7 +2086,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 && tmp < limit) { diff --git a/ext/standard/filters.c b/ext/standard/filters.c index 9b54b3d..956bd86 100644 --- a/ext/standard/filters.c +++ b/ext/standard/filters.c @@ -235,7 +235,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; @@ -844,7 +844,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; @@ -958,7 +958,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; } @@ -1057,7 +1057,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 b988422..a1927b5 100644 --- a/ext/standard/formatted_print.c +++ b/ext/standard/formatted_print.c @@ -378,7 +378,7 @@ php_sprintf_getnumber(char **buffer, size_t *len) int php_sprintf_get_argnum(char **format, size_t *format_len) { char *temppos = *format; - while (isdigit((int) *temppos)) temppos++; + while (isdigit((unsigned char)*temppos)) temppos++; if (*temppos != '$') { return ARG_NUM_NEXT; } @@ -466,7 +466,7 @@ php_formatted_print(char *format, size_t format_len, zval *args, int argc, int n 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 = ARG_NUM_NEXT; } else { @@ -535,7 +535,7 @@ php_formatted_print(char *format, size_t format_len, zval *args, int argc, int n } width = Z_LVAL_P(tmp); adjusting |= ADJ_WIDTH; - } else if (isdigit((int)*format)) { + } else if (isdigit((unsigned char)*format)) { PRINTF_DEBUG(("sprintf: getting width\n")); if ((width = php_sprintf_getnumber(&format, &format_len)) < 0) { zend_value_error("Width must be greater than zero and less than %d", INT_MAX); @@ -580,7 +580,7 @@ php_formatted_print(char *format, size_t format_len, zval *args, int argc, int n precision = Z_LVAL_P(tmp); adjusting |= ADJ_PRECISION; expprec = 1; - } else if (isdigit((int)*format)) { + } else if (isdigit((unsigned char)*format)) { if ((precision = php_sprintf_getnumber(&format, &format_len)) < 0) { zend_value_error("Precision must be greater than zero and less than %d", INT_MAX); goto fail; diff --git a/ext/standard/ftp_fopen_wrapper.c b/ext/standard/ftp_fopen_wrapper.c index d19113f..c749117 100644 --- a/ext/standard/ftp_fopen_wrapper.c +++ b/ext/standard/ftp_fopen_wrapper.c @@ -78,8 +78,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); } /* }}} */ @@ -228,7 +228,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; \ } \ @@ -339,14 +339,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; } @@ -826,7 +826,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 14ccd71..8d39490 100644 --- a/ext/standard/html.c +++ b/ext/standard/html.c @@ -682,8 +682,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 46169e9..f2b15f7 100644 --- a/ext/standard/http_fopen_wrapper.c +++ b/ext/standard/http_fopen_wrapper.c @@ -81,27 +81,70 @@ #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); } } @@ -667,8 +710,23 @@ finish: 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:")) { @@ -1022,7 +1080,7 @@ finish: char *new_path = NULL; - if (strlen(header_info.location) < 8 || + 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) && @@ -1030,7 +1088,7 @@ finish: { char *loc_path = NULL; if (*header_info.location != '/') { - if (*(header_info.location+1) != '\0' && resource->path) { + if (header_info.location_len > 1 && resource->path) { char *s = strrchr(ZSTR_VAL(resource->path), '/'); if (!s) { s = ZSTR_VAL(resource->path); @@ -1070,14 +1128,22 @@ finish: 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; + 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; \ @@ -1099,7 +1165,10 @@ finish: CHECK_FOR_CNTRL_CHARS(resource->pass); CHECK_FOR_CNTRL_CHARS(resource->path); } - int new_flags = HTTP_WRAPPER_REDIRECTED; + 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. diff --git a/ext/standard/math.c b/ext/standard/math.c index 8643676..af5869c 100644 --- a/ext/standard/math.c +++ b/ext/standard/math.c @@ -727,9 +727,9 @@ PHPAPI void _php_math_basetozval(zend_string *str, int base, zval *ret) e = s + ZSTR_LEN(str); /* 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; @@ -1031,7 +1031,7 @@ PHPAPI zend_string *_php_math_number_format_ex(double d, int dec, const char *de 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 2ba7a83..01ae1f9 100644 --- a/ext/standard/metaphone.c +++ b/ext/standard/metaphone.c @@ -78,7 +78,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 */ @@ -102,25 +102,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... */ @@ -156,12 +156,12 @@ 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 void 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 */ ZEND_ASSERT(word != NULL); @@ -179,7 +179,7 @@ static void metaphone(unsigned char *word, size_t word_len, zend_long max_phonem /*-- 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(); @@ -263,7 +263,7 @@ static void metaphone(unsigned char *word, size_t word_len, zend_long max_phonem */ /* Ignore non-alphas */ - if (!isalpha(Curr_Letter)) + if (!isalpha((unsigned char)Curr_Letter)) continue; /* Drop duplicates, except CC */ diff --git a/ext/standard/quot_print.c b/ext/standard/quot_print.c index e6aa2e4..fba61f9 100644 --- a/ext/standard/quot_print.c +++ b/ext/standard/quot_print.c @@ -216,11 +216,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 78ecc16..61154ec 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 @@ -656,9 +656,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; } @@ -809,7 +809,7 @@ literal: if (!(flags & SCAN_NOSKIP)) { while (*string != '\0') { sch = *string; - if (! isspace((int)sch) ) { + if (! isspace((unsigned char)sch) ) { break; } string++; @@ -835,7 +835,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 7d50be9..4dded61 100644 --- a/ext/standard/soundex.c +++ b/ext/standard/soundex.c @@ -67,7 +67,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 da1a97f..8ca36ed 100644 --- a/ext/standard/string.c +++ b/ext/standard/string.c @@ -3534,9 +3534,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; @@ -4386,7 +4386,7 @@ PHP_FUNCTION(hebrev) 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--; } @@ -4818,7 +4818,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; } @@ -4908,7 +4908,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; } @@ -4955,7 +4955,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 8cbc0db..6d45785 100644 --- a/ext/standard/strnatcmp.c +++ b/ext/standard/strnatcmp.c @@ -40,12 +40,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) @@ -67,12 +67,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; @@ -103,27 +103,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 (ca == '0' && (ap+1 < aend) && isdigit((int)(unsigned char)*(ap+1))) { + while (ca == '0' && (ap+1 < aend) && isdigit((unsigned char)ap[1])) { ca = *++ap; } - while (cb == '0' && (bp+1 < bend) && isdigit((int)(unsigned char)*(bp+1))) { + while (cb == '0' && (bp+1 < bend) && isdigit((unsigned char)bp[1])) { cb = *++bp; } while (1) { /* 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) @@ -147,8 +147,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/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/http/bug61548.phpt b/ext/standard/tests/http/bug61548.phpt index 5f21b37..ba46e65 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.1 Host: %s:%d Connection: close @@ -69,7 +68,6 @@ Connection: close First:1 Second:2 - POST / HTTP/1.1 Host: %s:%d Connection: close 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..5ccc88b --- /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; +['pid' => $pidB, 'uri' => $uriB] = http_server([ + "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; +['pid' => $pidA, 'uri' => $uriA] = http_server([ + "data://text/plain,HTTP/1.1 302 Found\r\nLocation: $uriB/first\r\nContent-Length: 0\r\n\r\n", +], $captureA); + +var_dump(file_get_contents($uriA . '/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; +['pid' => $pidC, 'uri' => $uriC] = http_server([ + "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($uriC . '/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; +['pid' => $pidH, 'uri' => $uriH] = http_server([ + "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", +], $captureH); + +$captureG = null; +['pid' => $pidG, 'uri' => $uriG] = http_server([ + "data://text/plain,HTTP/1.1 307 Temporary Redirect\r\nLocation: $uriH/second\r\nContent-Length: 0\r\n\r\n", +], $captureG); + +var_dump(@file_get_contents($uriG . '/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; + ['pid' => $pidF, 'uri' => $uriF] = http_server([ + "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", + ], $captureF); + + $captureE = null; + ['pid' => $pidE, 'uri' => $uriE] = http_server([ + "data://text/plain,HTTP/1.1 302 Found\r\nLocation: $uriF/second\r\nContent-Length: 0\r\n\r\n", + ], $captureE); + + file_get_contents($uriE . '/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, + str_contains($request, 'SECRET'), str_contains($request, 'X-Custom')); +} +?> +--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.1 +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/http_empty_location_redirect.phpt b/ext/standard/tests/http/http_empty_location_redirect.phpt new file mode 100644 index 0000000..a7f99bf --- /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/../../../openssl/tests/ServerClientTestCase.inc", __DIR__); +ServerClientTestCase::getInstance()->run($clientCode, $serverCode); +?> +--EXPECT-- +uri=/ 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..66af7a4 --- /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/../../../openssl/tests/ServerClientTestCase.inc", __DIR__); +ServerClientTestCase::getInstance()->run($clientCode, $serverCode); +?> +--EXPECT-- +uri=/x diff --git a/ext/standard/type.c b/ext/standard/type.c index 93df434..bf56c70 100644 --- a/ext/standard/type.c +++ b/ext/standard/type.c @@ -161,7 +161,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 e3d9576..def29df 100644 --- a/ext/standard/url.c +++ b/ext/standard/url.c @@ -117,7 +117,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, bool *has_port 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 */ @@ -146,7 +146,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, bool *has_port * correctly parse things like a.com:80 */ p = e + 1; - while (p < ue && isdigit(*p)) { + while (p < ue && isdigit((unsigned char)*p)) { p++; } @@ -186,7 +186,7 @@ PHPAPI php_url *php_url_parse_ex2(char const *str, size_t length, bool *has_port p = e + 1; pp = p; - while (pp < ue && pp - p < 6 && isdigit(*pp)) { + while (pp < ue && pp - p < 6 && isdigit((unsigned char)*pp)) { pp++; } @@ -429,12 +429,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; @@ -601,8 +601,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])) { *dest = (char) php_htoi(data + 1); data += 2; len -= 2; @@ -660,8 +660,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])) { *dest = (char) php_htoi(data + 1); data += 2; len -= 2; @@ -722,7 +722,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 bac4920..30b395b 100644 --- a/ext/standard/url_scanner_ex.re +++ b/ext/standard/url_scanner_ex.re @@ -85,7 +85,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); @@ -134,7 +134,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) { @@ -454,7 +454,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 aa60d97..1785397 100644 --- a/ext/standard/versioning.c +++ b/ext/standard/versioning.c @@ -45,8 +45,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); @@ -59,7 +59,7 @@ php_canonicalize_version(const char *version) *q++ = '.'; } *q++ = *p; - } else if (!isalnum(*p)) { + } else if (!isalnum((unsigned char)*p)) { if (lq != '.') { *q++ = '.'; } @@ -152,17 +152,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#"); @@ -180,13 +180,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/main/SAPI.c b/main/SAPI.c index 656418a..57c30e5 100644 --- a/main/SAPI.c +++ b/main/SAPI.c @@ -193,7 +193,7 @@ static void sapi_read_post_data(void) *p = 0; break; default: - *p = tolower(*p); + *p = tolower((unsigned char)*p); break; } } @@ -715,10 +715,10 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg) } /* 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 9eb504b..49cb8e1 100644 --- a/main/fastcgi.c +++ b/main/fastcgi.c @@ -1340,7 +1340,7 @@ static int fcgi_is_allowed(void) { 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 efb1101..2ba2615 100644 --- a/main/fopen_wrappers.c +++ b/main/fopen_wrappers.c @@ -487,7 +487,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) { @@ -519,7 +519,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) { @@ -588,7 +588,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 1369428..f28c7db 100644 --- a/main/php_ini.c +++ b/main/php_ini.c @@ -40,7 +40,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 aaeb281..3570890 100644 --- a/main/php_variables.c +++ b/main/php_variables.c @@ -185,7 +185,7 @@ PHPAPI void php_register_variable_ex(const char *var_name, zval *val, zval *trac ip++; index_s = ip; - if (isspace(*ip)) { + if (isspace((unsigned char)*ip)) { ip++; } if (*ip==']') { @@ -508,7 +508,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 92e3eae..f98070b 100644 --- a/main/rfc1867.c +++ b/main/rfc1867.c @@ -421,7 +421,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, ':'); } @@ -540,7 +540,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; } @@ -556,7 +556,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); @@ -823,7 +823,7 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ goto fileupload_done; } - while (isspace(*cd)) { + while (isspace((unsigned char)*cd)) { ++cd; } @@ -831,7 +831,7 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) /* {{{ */ { char *key = NULL, *word = pair; - while (isspace(*cd)) { + while (isspace((unsigned char)*cd)) { ++cd; } diff --git a/main/snprintf.c b/main/snprintf.c index f082115..b591169 100644 --- a/main/snprintf.c +++ b/main/snprintf.c @@ -286,7 +286,7 @@ PHPAPI char * php_conv_fp(char format, 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; @@ -433,11 +433,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)++ ) ; \ } /* @@ -531,7 +531,7 @@ static size_t format_converter(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, + */ @@ -553,7 +553,7 @@ static size_t format_converter(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 = true; } else if (*fmt == '*') { @@ -573,7 +573,7 @@ static size_t format_converter(buffy * odp, const char *fmt, va_list ap) /* {{{ if (*fmt == '.') { adjust_precision = true; 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 4c01347..2a31e3a 100644 --- a/main/spprintf.c +++ b/main/spprintf.c @@ -146,12 +146,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; \ } \ } \ @@ -238,7 +238,7 @@ static void xbuf_format_converter(void *xbuf, bool is_char, const char *fmt, va_ /* * 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, + */ @@ -260,7 +260,7 @@ static void xbuf_format_converter(void *xbuf, bool is_char, const char *fmt, va_ /* * Check if a width was specified */ - if (isdigit((int)*fmt)) { + if (isdigit((unsigned char)*fmt)) { STR_TO_DEC(fmt, min_width); adjust_width = true; } else if (*fmt == '*') { @@ -280,7 +280,7 @@ static void xbuf_format_converter(void *xbuf, bool is_char, const char *fmt, va_ if (*fmt == '.') { adjust_precision = true; 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 634c0d5..030c245 100644 --- a/main/streams/streams.c +++ b/main/streams/streams.c @@ -1739,7 +1739,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] != '.') { @@ -1819,7 +1819,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 35ac4ae..306f7ff 100644 --- a/main/streams/transports.c +++ b/main/streams/transports.c @@ -94,7 +94,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/sapi/cli/php_cli_server.c b/sapi/cli/php_cli_server.c index 82cf5c1..ab0ad1d 100644 --- a/sapi/cli/php_cli_server.c +++ b/sapi/cli/php_cli_server.c @@ -633,7 +633,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); diff --git a/sapi/fpm/fpm/fpm_conf.c b/sapi/fpm/fpm/fpm_conf.c index cc7102e..01c4ee2 100644 --- a/sapi/fpm/fpm/fpm_conf.c +++ b/sapi/fpm/fpm/fpm_conf.c @@ -932,7 +932,7 @@ static int fpm_conf_process_all_pools(void) } 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; } @@ -955,7 +955,7 @@ static int fpm_conf_process_all_pools(void) } 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 contain 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 f698753..81292aa 100644 --- a/sapi/fpm/fpm/fpm_status.c +++ b/sapi/fpm/fpm/fpm_status.c @@ -525,8 +525,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; float cpu; @@ -551,13 +551,36 @@ 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_HTML_IGNORE_ERRORS & ENT_COMPAT, + 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, @@ -596,7 +619,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, @@ -607,6 +630,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/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(), '