xref: /PHP-8.1/ext/openssl/xp_ssl.c (revision 3fc013b2)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Authors: Wez Furlong <wez@thebrainroom.com>                          |
14   |          Daniel Lowrey <rdlowrey@php.net>                            |
15   |          Chris Wright <daverandom@php.net>                           |
16   |          Jakub Zelenka <bukka@php.net>                               |
17   +----------------------------------------------------------------------+
18 */
19 
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 
24 #include "php.h"
25 #include "ext/standard/file.h"
26 #include "ext/standard/url.h"
27 #include "streams/php_streams_int.h"
28 #include "zend_smart_str.h"
29 #include "php_openssl.h"
30 #include "php_network.h"
31 #include <openssl/ssl.h>
32 #include <openssl/rsa.h>
33 #include <openssl/x509.h>
34 #include <openssl/x509v3.h>
35 #include <openssl/err.h>
36 #include <openssl/bn.h>
37 #include <openssl/dh.h>
38 
39 #ifdef PHP_WIN32
40 #include "win32/winutil.h"
41 #include "win32/time.h"
42 #include <Ws2tcpip.h>
43 #include <Wincrypt.h>
44 /* These are from Wincrypt.h, they conflict with OpenSSL */
45 #undef X509_NAME
46 #undef X509_CERT_PAIR
47 #undef X509_EXTENSIONS
48 #endif
49 
50 #ifdef HAVE_ARPA_INET_H
51 #include <arpa/inet.h>
52 #endif
53 
54 /* Flags for determining allowed stream crypto methods */
55 #define STREAM_CRYPTO_IS_CLIENT            (1<<0)
56 #define STREAM_CRYPTO_METHOD_SSLv2         (1<<1)
57 #define STREAM_CRYPTO_METHOD_SSLv3         (1<<2)
58 #define STREAM_CRYPTO_METHOD_TLSv1_0       (1<<3)
59 #define STREAM_CRYPTO_METHOD_TLSv1_1       (1<<4)
60 #define STREAM_CRYPTO_METHOD_TLSv1_2       (1<<5)
61 #define STREAM_CRYPTO_METHOD_TLSv1_3       (1<<6)
62 
63 #ifndef OPENSSL_NO_TLS1_METHOD
64 #define HAVE_TLS1 1
65 #endif
66 
67 #ifndef OPENSSL_NO_TLS1_1_METHOD
68 #define HAVE_TLS11 1
69 #endif
70 
71 #ifndef OPENSSL_NO_TLS1_2_METHOD
72 #define HAVE_TLS12 1
73 #endif
74 
75 #if OPENSSL_VERSION_NUMBER >= 0x10101000 && !defined(OPENSSL_NO_TLS1_3)
76 #define HAVE_TLS13 1
77 #endif
78 
79 #ifndef OPENSSL_NO_ECDH
80 #define HAVE_ECDH 1
81 #endif
82 
83 #ifndef OPENSSL_NO_TLSEXT
84 #define HAVE_TLS_SNI 1
85 #define HAVE_TLS_ALPN 1
86 #endif
87 
88 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
89 #define HAVE_SEC_LEVEL 1
90 #endif
91 
92 #ifndef OPENSSL_NO_SSL3
93 #define HAVE_SSL3 1
94 #define PHP_OPENSSL_MIN_PROTO_VERSION STREAM_CRYPTO_METHOD_SSLv3
95 #else
96 #define PHP_OPENSSL_MIN_PROTO_VERSION STREAM_CRYPTO_METHOD_TLSv1_0
97 #endif
98 #ifdef HAVE_TLS13
99 #define PHP_OPENSSL_MAX_PROTO_VERSION STREAM_CRYPTO_METHOD_TLSv1_3
100 #else
101 #define PHP_OPENSSL_MAX_PROTO_VERSION STREAM_CRYPTO_METHOD_TLSv1_2
102 #endif
103 
104 /* Simplify ssl context option retrieval */
105 #define GET_VER_OPT(name) \
106 	(PHP_STREAM_CONTEXT(stream) && (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", name)) != NULL)
107 #define GET_VER_OPT_STRING(name, str) \
108 	if (GET_VER_OPT(name)) { \
109 		if (try_convert_to_string(val)) str = Z_STRVAL_P(val); \
110 	}
111 #define GET_VER_OPT_LONG(name, num) \
112 	if (GET_VER_OPT(name)) { num = zval_get_long(val); }
113 
114 /* Used for peer verification in windows */
115 #define PHP_X509_NAME_ENTRY_TO_UTF8(ne, i, out) \
116 	ASN1_STRING_to_UTF8(&out, X509_NAME_ENTRY_get_data(X509_NAME_get_entry(ne, i)))
117 
118 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
119 /* Used for IPv6 Address peer verification */
120 #define EXPAND_IPV6_ADDRESS(_str, _bytes) \
121 	do { \
122 		snprintf(_str, 40, "%X:%X:%X:%X:%X:%X:%X:%X", \
123 			_bytes[0] << 8 | _bytes[1], \
124 			_bytes[2] << 8 | _bytes[3], \
125 			_bytes[4] << 8 | _bytes[5], \
126 			_bytes[6] << 8 | _bytes[7], \
127 			_bytes[8] << 8 | _bytes[9], \
128 			_bytes[10] << 8 | _bytes[11], \
129 			_bytes[12] << 8 | _bytes[13], \
130 			_bytes[14] << 8 | _bytes[15] \
131 		); \
132 	} while(0)
133 #define HAVE_IPV6_SAN 1
134 #endif
135 
136 #if PHP_OPENSSL_API_VERSION < 0x10100
137 static RSA *php_openssl_tmp_rsa_cb(SSL *s, int is_export, int keylength);
138 #endif
139 
140 extern php_stream* php_openssl_get_stream_from_ssl_handle(const SSL *ssl);
141 extern zend_string* php_openssl_x509_fingerprint(X509 *peer, const char *method, bool raw);
142 extern int php_openssl_get_ssl_stream_data_index(void);
143 static struct timeval php_openssl_subtract_timeval(struct timeval a, struct timeval b);
144 static int php_openssl_compare_timeval(struct timeval a, struct timeval b);
145 static ssize_t php_openssl_sockop_io(int read, php_stream *stream, char *buf, size_t count);
146 
147 const php_stream_ops php_openssl_socket_ops;
148 
149 /* Certificate contexts used for server-side SNI selection */
150 typedef struct _php_openssl_sni_cert_t {
151 	char *name;
152 	SSL_CTX *ctx;
153 } php_openssl_sni_cert_t;
154 
155 /* Provides leaky bucket handhsake renegotiation rate-limiting  */
156 typedef struct _php_openssl_handshake_bucket_t {
157 	zend_long prev_handshake;
158 	zend_long limit;
159 	zend_long window;
160 	float tokens;
161 	unsigned should_close;
162 } php_openssl_handshake_bucket_t;
163 
164 #ifdef HAVE_TLS_ALPN
165 /* Holds the available server ALPN protocols for negotiation */
166 typedef struct _php_openssl_alpn_ctx_t {
167 	unsigned char *data;
168 	unsigned short len;
169 } php_openssl_alpn_ctx;
170 #endif
171 
172 /* This implementation is very closely tied to the that of the native
173  * sockets implemented in the core.
174  * Don't try this technique in other extensions!
175  * */
176 typedef struct _php_openssl_netstream_data_t {
177 	php_netstream_data_t s;
178 	SSL *ssl_handle;
179 	SSL_CTX *ctx;
180 	struct timeval connect_timeout;
181 	int enable_on_connect;
182 	int is_client;
183 	int ssl_active;
184 	php_stream_xport_crypt_method_t method;
185 	php_openssl_handshake_bucket_t *reneg;
186 	php_openssl_sni_cert_t *sni_certs;
187 	unsigned sni_cert_count;
188 #ifdef HAVE_TLS_ALPN
189 	php_openssl_alpn_ctx alpn_ctx;
190 #endif
191 	char *url_name;
192 	unsigned state_set:1;
193 	unsigned _spare:31;
194 } php_openssl_netstream_data_t;
195 
196 /* it doesn't matter that we do some hash traversal here, since it is done only
197  * in an error condition arising from a network connection problem */
php_openssl_is_http_stream_talking_to_iis(php_stream * stream)198 static int php_openssl_is_http_stream_talking_to_iis(php_stream *stream) /* {{{ */
199 {
200 	if (Z_TYPE(stream->wrapperdata) == IS_ARRAY &&
201 		stream->wrapper &&
202 		strcasecmp(stream->wrapper->wops->label, "HTTP") == 0
203 	) {
204 		/* the wrapperdata is an array zval containing the headers */
205 		zval *tmp;
206 
207 #define SERVER_MICROSOFT_IIS	"Server: Microsoft-IIS"
208 #define SERVER_GOOGLE "Server: GFE/"
209 
210 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL(stream->wrapperdata), tmp) {
211 			if (zend_string_equals_literal_ci(Z_STR_P(tmp), SERVER_MICROSOFT_IIS)) {
212 				return 1;
213 			} else if (zend_string_equals_literal_ci(Z_STR_P(tmp), SERVER_GOOGLE)) {
214 				return 1;
215 			}
216 		} ZEND_HASH_FOREACH_END();
217 	}
218 	return 0;
219 }
220 /* }}} */
221 
php_openssl_handle_ssl_error(php_stream * stream,int nr_bytes,bool is_init)222 static int php_openssl_handle_ssl_error(php_stream *stream, int nr_bytes, bool is_init) /* {{{ */
223 {
224 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
225 	int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);
226 	char esbuf[512];
227 	smart_str ebuf = {0};
228 	unsigned long ecode;
229 	int retry = 1;
230 
231 	switch(err) {
232 		case SSL_ERROR_ZERO_RETURN:
233 			/* SSL terminated (but socket may still be active) */
234 			retry = 0;
235 			break;
236 		case SSL_ERROR_WANT_READ:
237 		case SSL_ERROR_WANT_WRITE:
238 			/* re-negotiation, or perhaps the SSL layer needs more
239 			 * packets: retry in next iteration */
240 			errno = EAGAIN;
241 			retry = is_init ? 1 : sslsock->s.is_blocked;
242 			break;
243 		case SSL_ERROR_SYSCALL:
244 			if (ERR_peek_error() == 0) {
245 				if (nr_bytes == 0) {
246 					if (!php_openssl_is_http_stream_talking_to_iis(stream) && ERR_get_error() != 0) {
247 						php_error_docref(NULL, E_WARNING, "SSL: fatal protocol error");
248 					}
249 					SSL_set_shutdown(sslsock->ssl_handle, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
250 					stream->eof = 1;
251 					retry = 0;
252 				} else {
253 					char *estr = php_socket_strerror(php_socket_errno(), NULL, 0);
254 
255 					php_error_docref(NULL, E_WARNING,
256 							"SSL: %s", estr);
257 
258 					efree(estr);
259 					retry = 0;
260 				}
261 				break;
262 			}
263 
264 			ZEND_FALLTHROUGH;
265 		default:
266 			/* some other error */
267 			ecode = ERR_get_error();
268 
269 			switch (ERR_GET_REASON(ecode)) {
270 				case SSL_R_NO_SHARED_CIPHER:
271 					php_error_docref(NULL, E_WARNING,
272 							"SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used.  "
273 							"This could be because the server is missing an SSL certificate "
274 							"(local_cert context option)");
275 					retry = 0;
276 					break;
277 
278 				default:
279 					do {
280 						/* NULL is automatically added */
281 						ERR_error_string_n(ecode, esbuf, sizeof(esbuf));
282 						if (ebuf.s) {
283 							smart_str_appendc(&ebuf, '\n');
284 						}
285 						smart_str_appends(&ebuf, esbuf);
286 					} while ((ecode = ERR_get_error()) != 0);
287 
288 					smart_str_0(&ebuf);
289 
290 					php_error_docref(NULL, E_WARNING,
291 							"SSL operation failed with code %d. %s%s",
292 							err,
293 							ebuf.s ? "OpenSSL Error messages:\n" : "",
294 							ebuf.s ? ZSTR_VAL(ebuf.s) : "");
295 					if (ebuf.s) {
296 						smart_str_free(&ebuf);
297 					}
298 			}
299 
300 			retry = 0;
301 			errno = 0;
302 	}
303 	return retry;
304 }
305 /* }}} */
306 
verify_callback(int preverify_ok,X509_STORE_CTX * ctx)307 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) /* {{{ */
308 {
309 	php_stream *stream;
310 	SSL *ssl;
311 	int err, depth, ret;
312 	zval *val;
313 	zend_ulong allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;
314 
315 
316 	ret = preverify_ok;
317 
318 	/* determine the status for the current cert */
319 	err = X509_STORE_CTX_get_error(ctx);
320 	depth = X509_STORE_CTX_get_error_depth(ctx);
321 
322 	/* conjure the stream & context to use */
323 	ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
324 	stream = (php_stream*)SSL_get_ex_data(ssl, php_openssl_get_ssl_stream_data_index());
325 
326 	/* if allow_self_signed is set, make sure that verification succeeds */
327 	if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
328 		GET_VER_OPT("allow_self_signed") &&
329 		zend_is_true(val)
330 	) {
331 		ret = 1;
332 	}
333 
334 	/* check the depth */
335 	GET_VER_OPT_LONG("verify_depth", allowed_depth);
336 	if ((zend_ulong)depth > allowed_depth) {
337 		ret = 0;
338 		X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
339 	}
340 
341 	return ret;
342 }
343 /* }}} */
344 
php_openssl_x509_fingerprint_cmp(X509 * peer,const char * method,const char * expected)345 static int php_openssl_x509_fingerprint_cmp(X509 *peer, const char *method, const char *expected)
346 {
347 	zend_string *fingerprint;
348 	int result = -1;
349 
350 	fingerprint = php_openssl_x509_fingerprint(peer, method, 0);
351 	if (fingerprint) {
352 		result = strcasecmp(expected, ZSTR_VAL(fingerprint));
353 		zend_string_release_ex(fingerprint, 0);
354 	}
355 
356 	return result;
357 }
358 
php_openssl_x509_fingerprint_match(X509 * peer,zval * val)359 static bool php_openssl_x509_fingerprint_match(X509 *peer, zval *val)
360 {
361 	if (Z_TYPE_P(val) == IS_STRING) {
362 		const char *method = NULL;
363 
364 		switch (Z_STRLEN_P(val)) {
365 			case 32:
366 				method = "md5";
367 				break;
368 
369 			case 40:
370 				method = "sha1";
371 				break;
372 		}
373 
374 		return method && php_openssl_x509_fingerprint_cmp(peer, method, Z_STRVAL_P(val)) == 0;
375 	} else if (Z_TYPE_P(val) == IS_ARRAY) {
376 		zval *current;
377 		zend_string *key;
378 
379 		if (!zend_hash_num_elements(Z_ARRVAL_P(val))) {
380 			php_error_docref(NULL, E_WARNING, "Invalid peer_fingerprint array; [algo => fingerprint] form required");
381 			return 0;
382 		}
383 
384 		ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(val), key, current) {
385 			if (key == NULL || Z_TYPE_P(current) != IS_STRING) {
386 				php_error_docref(NULL, E_WARNING, "Invalid peer_fingerprint array; [algo => fingerprint] form required");
387 				return 0;
388 			}
389 			if (php_openssl_x509_fingerprint_cmp(peer, ZSTR_VAL(key), Z_STRVAL_P(current)) != 0) {
390 				return 0;
391 			}
392 		} ZEND_HASH_FOREACH_END();
393 
394 		return 1;
395 	} else {
396 		php_error_docref(NULL, E_WARNING,
397 			"Invalid peer_fingerprint value; fingerprint string or array of the form [algo => fingerprint] required");
398 	}
399 
400 	return 0;
401 }
402 
php_openssl_matches_wildcard_name(const char * subjectname,const char * certname)403 static bool php_openssl_matches_wildcard_name(const char *subjectname, const char *certname) /* {{{ */
404 {
405 	char *wildcard = NULL;
406 	ptrdiff_t prefix_len;
407 	size_t suffix_len, subject_len;
408 
409 	if (strcasecmp(subjectname, certname) == 0) {
410 		return 1;
411 	}
412 
413 	/* wildcard, if present, must only be present in the left-most component */
414 	if (!(wildcard = strchr(certname, '*')) || memchr(certname, '.', wildcard - certname)) {
415 		return 0;
416 	}
417 
418 	/* 1) prefix, if not empty, must match subject */
419 	prefix_len = wildcard - certname;
420 	if (prefix_len && strncasecmp(subjectname, certname, prefix_len) != 0) {
421 		return 0;
422 	}
423 
424 	suffix_len = strlen(wildcard + 1);
425 	subject_len = strlen(subjectname);
426 	if (suffix_len <= subject_len) {
427 		/* 2) suffix must match
428 		 * 3) no . between prefix and suffix
429 		 **/
430 		return strcasecmp(wildcard + 1, subjectname + subject_len - suffix_len) == 0 &&
431 			memchr(subjectname + prefix_len, '.', subject_len - suffix_len - prefix_len) == NULL;
432 	}
433 
434 	return 0;
435 }
436 /* }}} */
437 
php_openssl_matches_san_list(X509 * peer,const char * subject_name)438 static bool php_openssl_matches_san_list(X509 *peer, const char *subject_name) /* {{{ */
439 {
440 	int i, len;
441 	unsigned char *cert_name = NULL;
442 	char ipbuffer[64];
443 
444 	GENERAL_NAMES *alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, 0, 0);
445 	int alt_name_count = sk_GENERAL_NAME_num(alt_names);
446 
447 #ifdef HAVE_IPV6_SAN
448 	/* detect if subject name is an IPv6 address and expand once if required */
449 	char subject_name_ipv6_expanded[40];
450 	unsigned char ipv6[16];
451 	bool subject_name_is_ipv6 = false;
452 	subject_name_ipv6_expanded[0] = 0;
453 
454 	if (inet_pton(AF_INET6, subject_name, &ipv6)) {
455 		EXPAND_IPV6_ADDRESS(subject_name_ipv6_expanded, ipv6);
456 		subject_name_is_ipv6 = true;
457 	}
458 #endif
459 
460 	for (i = 0; i < alt_name_count; i++) {
461 		GENERAL_NAME *san = sk_GENERAL_NAME_value(alt_names, i);
462 
463 		if (san->type == GEN_DNS) {
464 			ASN1_STRING_to_UTF8(&cert_name, san->d.dNSName);
465 			if ((size_t)ASN1_STRING_length(san->d.dNSName) != strlen((const char*)cert_name)) {
466 				OPENSSL_free(cert_name);
467 				/* prevent null-byte poisoning*/
468 				continue;
469 			}
470 
471 			/* accommodate valid FQDN entries ending in "." */
472 			len = strlen((const char*)cert_name);
473 			if (len && strcmp((const char *)&cert_name[len-1], ".") == 0) {
474 				cert_name[len-1] = '\0';
475 			}
476 
477 			if (php_openssl_matches_wildcard_name(subject_name, (const char *)cert_name)) {
478 				OPENSSL_free(cert_name);
479 				sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
480 
481 				return 1;
482 			}
483 			OPENSSL_free(cert_name);
484 		} else if (san->type == GEN_IPADD) {
485 			if (san->d.iPAddress->length == 4) {
486 				sprintf(ipbuffer, "%d.%d.%d.%d",
487 					san->d.iPAddress->data[0],
488 					san->d.iPAddress->data[1],
489 					san->d.iPAddress->data[2],
490 					san->d.iPAddress->data[3]
491 				);
492 				if (strcasecmp(subject_name, (const char*)ipbuffer) == 0) {
493 					sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
494 
495 					return 1;
496 				}
497 			}
498 #ifdef HAVE_IPV6_SAN
499 			else if (san->d.ip->length == 16 && subject_name_is_ipv6) {
500 				ipbuffer[0] = 0;
501 				EXPAND_IPV6_ADDRESS(ipbuffer, san->d.iPAddress->data);
502 				if (strcasecmp((const char*)subject_name_ipv6_expanded, (const char*)ipbuffer) == 0) {
503 					sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
504 
505 					return 1;
506 				}
507 			}
508 #endif
509 		}
510 	}
511 
512 	sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
513 
514 	return 0;
515 }
516 /* }}} */
517 
php_openssl_matches_common_name(X509 * peer,const char * subject_name)518 static bool php_openssl_matches_common_name(X509 *peer, const char *subject_name) /* {{{ */
519 {
520 	char buf[1024];
521 	X509_NAME *cert_name;
522 	bool is_match = 0;
523 	int cert_name_len;
524 
525 	cert_name = X509_get_subject_name(peer);
526 	cert_name_len = X509_NAME_get_text_by_NID(cert_name, NID_commonName, buf, sizeof(buf));
527 
528 	if (cert_name_len == -1) {
529 		php_error_docref(NULL, E_WARNING, "Unable to locate peer certificate CN");
530 	} else if ((size_t)cert_name_len != strlen(buf)) {
531 		php_error_docref(NULL, E_WARNING, "Peer certificate CN=`%.*s' is malformed", cert_name_len, buf);
532 	} else if (php_openssl_matches_wildcard_name(subject_name, buf)) {
533 		is_match = 1;
534 	} else {
535 		php_error_docref(NULL, E_WARNING,
536 			"Peer certificate CN=`%.*s' did not match expected CN=`%s'",
537 			cert_name_len, buf, subject_name);
538 	}
539 
540 	return is_match;
541 }
542 /* }}} */
543 
php_openssl_apply_peer_verification_policy(SSL * ssl,X509 * peer,php_stream * stream)544 static int php_openssl_apply_peer_verification_policy(SSL *ssl, X509 *peer, php_stream *stream) /* {{{ */
545 {
546 	zval *val = NULL;
547 	zval *peer_fingerprint;
548 	char *peer_name = NULL;
549 	int err,
550 		must_verify_peer,
551 		must_verify_peer_name,
552 		must_verify_fingerprint;
553 
554 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
555 
556 	must_verify_peer = GET_VER_OPT("verify_peer")
557 		? zend_is_true(val)
558 		: sslsock->is_client;
559 
560 	must_verify_peer_name = GET_VER_OPT("verify_peer_name")
561 		? zend_is_true(val)
562 		: sslsock->is_client;
563 
564 	must_verify_fingerprint = GET_VER_OPT("peer_fingerprint");
565 	peer_fingerprint = val;
566 
567 	if ((must_verify_peer || must_verify_peer_name || must_verify_fingerprint) && peer == NULL) {
568 		php_error_docref(NULL, E_WARNING, "Could not get peer certificate");
569 		return FAILURE;
570 	}
571 
572 	/* Verify the peer against using CA file/path settings */
573 	if (must_verify_peer) {
574 		err = SSL_get_verify_result(ssl);
575 		switch (err) {
576 			case X509_V_OK:
577 				/* fine */
578 				break;
579 			case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
580 				if (GET_VER_OPT("allow_self_signed") && zend_is_true(val)) {
581 					/* allowed */
582 					break;
583 				}
584 				/* not allowed, so fall through */
585 				ZEND_FALLTHROUGH;
586 			default:
587 				php_error_docref(NULL, E_WARNING,
588 						"Could not verify peer: code:%d %s",
589 						err,
590 						X509_verify_cert_error_string(err)
591 				);
592 				return FAILURE;
593 		}
594 	}
595 
596 	/* If a peer_fingerprint match is required this trumps peer and peer_name verification */
597 	if (must_verify_fingerprint) {
598 		if (Z_TYPE_P(peer_fingerprint) == IS_STRING || Z_TYPE_P(peer_fingerprint) == IS_ARRAY) {
599 			if (!php_openssl_x509_fingerprint_match(peer, peer_fingerprint)) {
600 				php_error_docref(NULL, E_WARNING,
601 					"peer_fingerprint match failure"
602 				);
603 				return FAILURE;
604 			}
605 		} else {
606 			php_error_docref(NULL, E_WARNING,
607 				"Expected peer fingerprint must be a string or an array"
608 			);
609 			return FAILURE;
610 		}
611 	}
612 
613 	/* verify the host name presented in the peer certificate */
614 	if (must_verify_peer_name) {
615 		GET_VER_OPT_STRING("peer_name", peer_name);
616 
617 		/* If no peer name was specified we use the autodetected url name in client environments */
618 		if (peer_name == NULL && sslsock->is_client) {
619 			peer_name = sslsock->url_name;
620 		}
621 
622 		if (peer_name) {
623 			if (php_openssl_matches_san_list(peer, peer_name)) {
624 				return SUCCESS;
625 			} else if (php_openssl_matches_common_name(peer, peer_name)) {
626 				return SUCCESS;
627 			} else {
628 				return FAILURE;
629 			}
630 		} else {
631 			return FAILURE;
632 		}
633 	}
634 
635 	return SUCCESS;
636 }
637 /* }}} */
638 
php_openssl_passwd_callback(char * buf,int num,int verify,void * data)639 static int php_openssl_passwd_callback(char *buf, int num, int verify, void *data) /* {{{ */
640 {
641 	php_stream *stream = (php_stream *)data;
642 	zval *val = NULL;
643 	char *passphrase = NULL;
644 	/* TODO: could expand this to make a callback into PHP user-space */
645 
646 	GET_VER_OPT_STRING("passphrase", passphrase);
647 
648 	if (passphrase) {
649 		if (Z_STRLEN_P(val) < (size_t)num - 1) {
650 			memcpy(buf, Z_STRVAL_P(val), Z_STRLEN_P(val)+1);
651 			return (int)Z_STRLEN_P(val);
652 		}
653 	}
654 	return 0;
655 }
656 /* }}} */
657 
658 #ifdef PHP_WIN32
659 #define RETURN_CERT_VERIFY_FAILURE(code) X509_STORE_CTX_set_error(x509_store_ctx, code); return 0;
php_openssl_win_cert_verify_callback(X509_STORE_CTX * x509_store_ctx,void * arg)660 static int php_openssl_win_cert_verify_callback(X509_STORE_CTX *x509_store_ctx, void *arg) /* {{{ */
661 {
662 	PCCERT_CONTEXT cert_ctx = NULL;
663 	PCCERT_CHAIN_CONTEXT cert_chain_ctx = NULL;
664 #if OPENSSL_VERSION_NUMBER < 0x10100000L
665 	X509 *cert = x509_store_ctx->cert;
666 #else
667 	X509 *cert = X509_STORE_CTX_get0_cert(x509_store_ctx);
668 #endif
669 
670 	php_stream *stream;
671 	php_openssl_netstream_data_t *sslsock;
672 	zval *val;
673 	bool is_self_signed = 0;
674 
675 
676 	stream = (php_stream*)arg;
677 	sslsock = (php_openssl_netstream_data_t*)stream->abstract;
678 
679 	{ /* First convert the x509 struct back to a DER encoded buffer and let Windows decode it into a form it can work with */
680 		unsigned char *der_buf = NULL;
681 		int der_len;
682 
683 		der_len = i2d_X509(cert, &der_buf);
684 		if (der_len < 0) {
685 			unsigned long err_code, e;
686 			char err_buf[512];
687 
688 			while ((e = ERR_get_error()) != 0) {
689 				err_code = e;
690 			}
691 
692 			php_error_docref(NULL, E_WARNING, "Error encoding X509 certificate: %d: %s", err_code, ERR_error_string(err_code, err_buf));
693 			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
694 		}
695 
696 		cert_ctx = CertCreateCertificateContext(X509_ASN_ENCODING, der_buf, der_len);
697 		OPENSSL_free(der_buf);
698 
699 		if (cert_ctx == NULL) {
700 			char *err = php_win_err();
701 			php_error_docref(NULL, E_WARNING, "Error creating certificate context: %s", err);
702 			php_win_err_free(err);
703 			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
704 		}
705 	}
706 
707 	{ /* Next fetch the relevant cert chain from the store */
708 		CERT_ENHKEY_USAGE enhkey_usage = {0};
709 		CERT_USAGE_MATCH cert_usage = {0};
710 		CERT_CHAIN_PARA chain_params = {sizeof(CERT_CHAIN_PARA)};
711 		LPSTR usages[] = {szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE};
712 		DWORD chain_flags = 0;
713 		unsigned long allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;
714 		unsigned int i;
715 
716 		enhkey_usage.cUsageIdentifier = 3;
717 		enhkey_usage.rgpszUsageIdentifier = usages;
718 		cert_usage.dwType = USAGE_MATCH_TYPE_OR;
719 		cert_usage.Usage = enhkey_usage;
720 		chain_params.RequestedUsage = cert_usage;
721 		chain_flags = CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
722 
723 		if (!CertGetCertificateChain(NULL, cert_ctx, NULL, NULL, &chain_params, chain_flags, NULL, &cert_chain_ctx)) {
724 			char *err = php_win_err();
725 			php_error_docref(NULL, E_WARNING, "Error getting certificate chain: %s", err);
726 			php_win_err_free(err);
727 			CertFreeCertificateContext(cert_ctx);
728 			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
729 		}
730 
731 		/* check if the cert is self-signed */
732 		if (cert_chain_ctx->cChain > 0 && cert_chain_ctx->rgpChain[0]->cElement > 0
733 			&& (cert_chain_ctx->rgpChain[0]->rgpElement[0]->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED) != 0) {
734 			is_self_signed = 1;
735 		}
736 
737 		/* check the depth */
738 		GET_VER_OPT_LONG("verify_depth", allowed_depth);
739 
740 		for (i = 0; i < cert_chain_ctx->cChain; i++) {
741 			if (cert_chain_ctx->rgpChain[i]->cElement > allowed_depth) {
742 				CertFreeCertificateChain(cert_chain_ctx);
743 				CertFreeCertificateContext(cert_ctx);
744 				RETURN_CERT_VERIFY_FAILURE(X509_V_ERR_CERT_CHAIN_TOO_LONG);
745 			}
746 		}
747 	}
748 
749 	{ /* Then verify it against a policy */
750 		SSL_EXTRA_CERT_CHAIN_POLICY_PARA ssl_policy_params = {sizeof(SSL_EXTRA_CERT_CHAIN_POLICY_PARA)};
751 		CERT_CHAIN_POLICY_PARA chain_policy_params = {sizeof(CERT_CHAIN_POLICY_PARA)};
752 		CERT_CHAIN_POLICY_STATUS chain_policy_status = {sizeof(CERT_CHAIN_POLICY_STATUS)};
753 		LPWSTR server_name = NULL;
754 		BOOL verify_result;
755 
756 		ssl_policy_params.dwAuthType = (sslsock->is_client) ? AUTHTYPE_SERVER : AUTHTYPE_CLIENT;
757 		/* we validate the name ourselves using the peer_name
758 		   ctx option, so no need to use a server name here */
759 		ssl_policy_params.pwszServerName = NULL;
760 		chain_policy_params.pvExtraPolicyPara = &ssl_policy_params;
761 
762 		verify_result = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, cert_chain_ctx, &chain_policy_params, &chain_policy_status);
763 
764 		CertFreeCertificateChain(cert_chain_ctx);
765 		CertFreeCertificateContext(cert_ctx);
766 
767 		if (!verify_result) {
768 			char *err = php_win_err();
769 			php_error_docref(NULL, E_WARNING, "Error verifying certificate chain policy: %s", err);
770 			php_win_err_free(err);
771 			RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
772 		}
773 
774 		if (chain_policy_status.dwError != 0) {
775 			/* The chain does not match the policy */
776 			if (is_self_signed && chain_policy_status.dwError == CERT_E_UNTRUSTEDROOT
777 				&& GET_VER_OPT("allow_self_signed") && zend_is_true(val)) {
778 				/* allow self-signed certs */
779 				X509_STORE_CTX_set_error(x509_store_ctx, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
780 			} else {
781 				RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
782 			}
783 		}
784 	}
785 
786 	return 1;
787 }
788 /* }}} */
789 #endif
790 
php_openssl_load_stream_cafile(X509_STORE * cert_store,const char * cafile)791 static long php_openssl_load_stream_cafile(X509_STORE *cert_store, const char *cafile) /* {{{ */
792 {
793 	php_stream *stream;
794 	X509 *cert;
795 	BIO *buffer;
796 	int buffer_active = 0;
797 	char *line = NULL;
798 	size_t line_len;
799 	long certs_added = 0;
800 
801 	stream = php_stream_open_wrapper(cafile, "rb", 0, NULL);
802 
803 	if (stream == NULL) {
804 		php_error(E_WARNING, "failed loading cafile stream: `%s'", cafile);
805 		return 0;
806 	} else if (stream->wrapper->is_url) {
807 		php_stream_close(stream);
808 		php_error(E_WARNING, "remote cafile streams are disabled for security purposes");
809 		return 0;
810 	}
811 
812 	cert_start: {
813 		line = php_stream_get_line(stream, NULL, 0, &line_len);
814 		if (line == NULL) {
815 			goto stream_complete;
816 		} else if (!strcmp(line, "-----BEGIN CERTIFICATE-----\n") ||
817 			!strcmp(line, "-----BEGIN CERTIFICATE-----\r\n")
818 		) {
819 			buffer = BIO_new(BIO_s_mem());
820 			buffer_active = 1;
821 			goto cert_line;
822 		} else {
823 			efree(line);
824 			goto cert_start;
825 		}
826 	}
827 
828 	cert_line: {
829 		BIO_puts(buffer, line);
830 		efree(line);
831 		line = php_stream_get_line(stream, NULL, 0, &line_len);
832 		if (line == NULL) {
833 			goto stream_complete;
834 		} else if (!strcmp(line, "-----END CERTIFICATE-----") ||
835 			!strcmp(line, "-----END CERTIFICATE-----\n") ||
836 			!strcmp(line, "-----END CERTIFICATE-----\r\n")
837 		) {
838 			goto add_cert;
839 		} else {
840 			goto cert_line;
841 		}
842 	}
843 
844 	add_cert: {
845 		BIO_puts(buffer, line);
846 		efree(line);
847 		cert = PEM_read_bio_X509(buffer, NULL, 0, NULL);
848 		BIO_free(buffer);
849 		buffer_active = 0;
850 		if (cert && X509_STORE_add_cert(cert_store, cert)) {
851 			++certs_added;
852 			X509_free(cert);
853 		}
854 		goto cert_start;
855 	}
856 
857 	stream_complete: {
858 		php_stream_close(stream);
859 		if (buffer_active == 1) {
860 			BIO_free(buffer);
861 		}
862 	}
863 
864 	if (certs_added == 0) {
865 		php_error(E_WARNING, "no valid certs found cafile stream: `%s'", cafile);
866 	}
867 
868 	return certs_added;
869 }
870 /* }}} */
871 
php_openssl_enable_peer_verification(SSL_CTX * ctx,php_stream * stream)872 static int php_openssl_enable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
873 {
874 	zval *val = NULL;
875 	char *cafile = NULL;
876 	char *capath = NULL;
877 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
878 
879 	GET_VER_OPT_STRING("cafile", cafile);
880 	GET_VER_OPT_STRING("capath", capath);
881 
882 	if (cafile == NULL) {
883 		cafile = zend_ini_string("openssl.cafile", sizeof("openssl.cafile")-1, 0);
884 		cafile = strlen(cafile) ? cafile : NULL;
885 	} else if (!sslsock->is_client) {
886 		/* Servers need to load and assign CA names from the cafile */
887 		STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(cafile);
888 		if (cert_names != NULL) {
889 			SSL_CTX_set_client_CA_list(ctx, cert_names);
890 		} else {
891 			php_error(E_WARNING, "SSL: failed loading CA names from cafile");
892 			return FAILURE;
893 		}
894 	}
895 
896 	if (capath == NULL) {
897 		capath = zend_ini_string("openssl.capath", sizeof("openssl.capath")-1, 0);
898 		capath = strlen(capath) ? capath : NULL;
899 	}
900 
901 	if (cafile || capath) {
902 		if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) {
903 			ERR_clear_error();
904 			if (cafile && !php_openssl_load_stream_cafile(SSL_CTX_get_cert_store(ctx), cafile)) {
905 				return FAILURE;
906 			}
907 		}
908 	} else {
909 #ifdef PHP_WIN32
910 		SSL_CTX_set_cert_verify_callback(ctx, php_openssl_win_cert_verify_callback, (void *)stream);
911 #else
912 		if (sslsock->is_client && !SSL_CTX_set_default_verify_paths(ctx)) {
913 			php_error_docref(NULL, E_WARNING,
914 				"Unable to set default verify locations and no CA settings specified");
915 			return FAILURE;
916 		}
917 #endif
918 	}
919 
920 	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
921 
922 	return SUCCESS;
923 }
924 /* }}} */
925 
php_openssl_disable_peer_verification(SSL_CTX * ctx,php_stream * stream)926 static void php_openssl_disable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
927 {
928 	SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
929 }
930 /* }}} */
931 
php_openssl_set_local_cert(SSL_CTX * ctx,php_stream * stream)932 static int php_openssl_set_local_cert(SSL_CTX *ctx, php_stream *stream) /* {{{ */
933 {
934 	zval *val = NULL;
935 	char *certfile = NULL;
936 
937 	GET_VER_OPT_STRING("local_cert", certfile);
938 
939 	if (certfile) {
940 		char resolved_path_buff[MAXPATHLEN];
941 		const char *private_key = NULL;
942 
943 		if (VCWD_REALPATH(certfile, resolved_path_buff)) {
944 			/* a certificate to use for authentication */
945 			if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
946 				php_error_docref(NULL, E_WARNING,
947 					"Unable to set local cert chain file `%s'; Check that your cafile/capath "
948 					"settings include details of your certificate and its issuer",
949 					certfile);
950 				return FAILURE;
951 			}
952 			GET_VER_OPT_STRING("local_pk", private_key);
953 
954 			if (private_key) {
955 				char resolved_path_buff_pk[MAXPATHLEN];
956 				if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) {
957 					if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) {
958 						php_error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff_pk);
959 						return FAILURE;
960 					}
961 				}
962 			} else {
963 				if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
964 					php_error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff);
965 					return FAILURE;
966 				}
967 			}
968 
969 			if (!SSL_CTX_check_private_key(ctx)) {
970 				php_error_docref(NULL, E_WARNING, "Private key does not match certificate!");
971 			}
972 		}
973 	}
974 
975 	return SUCCESS;
976 }
977 /* }}} */
978 
979 #if PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_get_crypto_method_ctx_flags(int method_flags)980 static int php_openssl_get_crypto_method_ctx_flags(int method_flags) /* {{{ */
981 {
982 	int ssl_ctx_options = SSL_OP_ALL;
983 
984 #ifdef SSL_OP_NO_SSLv2
985 	ssl_ctx_options |= SSL_OP_NO_SSLv2;
986 #endif
987 #ifdef HAVE_SSL3
988 	if (!(method_flags & STREAM_CRYPTO_METHOD_SSLv3)) {
989 		ssl_ctx_options |= SSL_OP_NO_SSLv3;
990 	}
991 #endif
992 #ifdef HAVE_TLS1
993 	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_0)) {
994 		ssl_ctx_options |= SSL_OP_NO_TLSv1;
995 	}
996 #endif
997 #ifdef HAVE_TLS11
998 	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_1)) {
999 		ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
1000 	}
1001 #endif
1002 #ifdef HAVE_TLS12
1003 	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_2)) {
1004 		ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
1005 	}
1006 #endif
1007 #ifdef HAVE_TLS13
1008 	if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_3)) {
1009 		ssl_ctx_options |= SSL_OP_NO_TLSv1_3;
1010 	}
1011 #endif
1012 
1013 	return ssl_ctx_options;
1014 }
1015 /* }}} */
1016 #endif
1017 
php_openssl_get_min_proto_version_flag(int flags)1018 static inline int php_openssl_get_min_proto_version_flag(int flags) /* {{{ */
1019 {
1020 	int ver;
1021 	for (ver = PHP_OPENSSL_MIN_PROTO_VERSION; ver <= PHP_OPENSSL_MAX_PROTO_VERSION; ver <<= 1) {
1022 		if (flags & ver) {
1023 			return ver;
1024 		}
1025 	}
1026 	return PHP_OPENSSL_MAX_PROTO_VERSION;
1027 }
1028 /* }}} */
1029 
php_openssl_get_max_proto_version_flag(int flags)1030 static inline int php_openssl_get_max_proto_version_flag(int flags) /* {{{ */
1031 {
1032 	int ver;
1033 	for (ver = PHP_OPENSSL_MAX_PROTO_VERSION; ver >= PHP_OPENSSL_MIN_PROTO_VERSION; ver >>= 1) {
1034 		if (flags & ver) {
1035 			return ver;
1036 		}
1037 	}
1038 	return STREAM_CRYPTO_METHOD_TLSv1_3;
1039 }
1040 /* }}} */
1041 
1042 #if PHP_OPENSSL_API_VERSION >= 0x10100
php_openssl_map_proto_version(int flag)1043 static inline int php_openssl_map_proto_version(int flag) /* {{{ */
1044 {
1045 	switch (flag) {
1046 #ifdef HAVE_TLS13
1047 		case STREAM_CRYPTO_METHOD_TLSv1_3:
1048 			return TLS1_3_VERSION;
1049 #endif
1050 		case STREAM_CRYPTO_METHOD_TLSv1_2:
1051 			return TLS1_2_VERSION;
1052 		case STREAM_CRYPTO_METHOD_TLSv1_1:
1053 			return TLS1_1_VERSION;
1054 		case STREAM_CRYPTO_METHOD_TLSv1_0:
1055 			return TLS1_VERSION;
1056 #ifdef HAVE_SSL3
1057 		case STREAM_CRYPTO_METHOD_SSLv3:
1058 			return SSL3_VERSION;
1059 #endif
1060 		default:
1061 			return TLS1_2_VERSION;
1062 	}
1063 }
1064 /* }}} */
1065 
php_openssl_get_min_proto_version(int flags)1066 static int php_openssl_get_min_proto_version(int flags) /* {{{ */
1067 {
1068 	return php_openssl_map_proto_version(php_openssl_get_min_proto_version_flag(flags));
1069 }
1070 /* }}} */
1071 
php_openssl_get_max_proto_version(int flags)1072 static int php_openssl_get_max_proto_version(int flags) /* {{{ */
1073 {
1074 	return php_openssl_map_proto_version(php_openssl_get_max_proto_version_flag(flags));
1075 }
1076 /* }}} */
1077 #endif
1078 
php_openssl_get_proto_version_flags(int flags,int min,int max)1079 static int php_openssl_get_proto_version_flags(int flags, int min, int max) /* {{{ */
1080 {
1081 	int ver;
1082 
1083 	if (!min) {
1084 		min = php_openssl_get_min_proto_version_flag(flags);
1085 	}
1086 	if (!max) {
1087 		max = php_openssl_get_max_proto_version_flag(flags);
1088 	}
1089 
1090 	for (ver = PHP_OPENSSL_MIN_PROTO_VERSION; ver <= PHP_OPENSSL_MAX_PROTO_VERSION; ver <<= 1) {
1091 		if (ver >= min && ver <= max) {
1092 			if (!(flags & ver)) {
1093 				flags |= ver;
1094 			}
1095 		} else if (flags & ver) {
1096 			flags &= ~ver;
1097 		}
1098 	}
1099 
1100 	return flags;
1101 }
1102 /* }}} */
1103 
php_openssl_limit_handshake_reneg(const SSL * ssl)1104 static void php_openssl_limit_handshake_reneg(const SSL *ssl) /* {{{ */
1105 {
1106 	php_stream *stream;
1107 	php_openssl_netstream_data_t *sslsock;
1108 	struct timeval now;
1109 	zend_long elapsed_time;
1110 
1111 	stream = php_openssl_get_stream_from_ssl_handle(ssl);
1112 	sslsock = (php_openssl_netstream_data_t*)stream->abstract;
1113 	gettimeofday(&now, NULL);
1114 
1115 	/* The initial handshake is never rate-limited */
1116 	if (sslsock->reneg->prev_handshake == 0) {
1117 		sslsock->reneg->prev_handshake = now.tv_sec;
1118 		return;
1119 	}
1120 
1121 	elapsed_time = (now.tv_sec - sslsock->reneg->prev_handshake);
1122 	sslsock->reneg->prev_handshake = now.tv_sec;
1123 	sslsock->reneg->tokens -= (elapsed_time * (sslsock->reneg->limit / sslsock->reneg->window));
1124 
1125 	if (sslsock->reneg->tokens < 0) {
1126 		sslsock->reneg->tokens = 0;
1127 	}
1128 	++sslsock->reneg->tokens;
1129 
1130 	/* The token level exceeds our allowed limit */
1131 	if (sslsock->reneg->tokens > sslsock->reneg->limit) {
1132 		zval *val;
1133 
1134 
1135 		sslsock->reneg->should_close = 1;
1136 
1137 		if (PHP_STREAM_CONTEXT(stream) && (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1138 				"ssl", "reneg_limit_callback")) != NULL
1139 		) {
1140 			zval param, retval;
1141 
1142 			php_stream_to_zval(stream, &param);
1143 
1144 			/* Closing the stream inside this callback would segfault! */
1145 			stream->flags |= PHP_STREAM_FLAG_NO_FCLOSE;
1146 			if (FAILURE == call_user_function(NULL, NULL, val, &retval, 1, &param)) {
1147 				php_error(E_WARNING, "SSL: failed invoking reneg limit notification callback");
1148 			}
1149 			stream->flags ^= PHP_STREAM_FLAG_NO_FCLOSE;
1150 
1151 			/* If the reneg_limit_callback returned true don't auto-close */
1152 			if (Z_TYPE(retval) == IS_TRUE) {
1153 				sslsock->reneg->should_close = 0;
1154 			}
1155 
1156 			zval_ptr_dtor(&retval);
1157 		} else {
1158 			php_error_docref(NULL, E_WARNING,
1159 				"SSL: client-initiated handshake rate limit exceeded by peer");
1160 		}
1161 	}
1162 }
1163 /* }}} */
1164 
php_openssl_info_callback(const SSL * ssl,int where,int ret)1165 static void php_openssl_info_callback(const SSL *ssl, int where, int ret) /* {{{ */
1166 {
1167 	/* Rate-limit client-initiated handshake renegotiation to prevent DoS */
1168 	if (where & SSL_CB_HANDSHAKE_START) {
1169 		php_openssl_limit_handshake_reneg(ssl);
1170 	}
1171 }
1172 /* }}} */
1173 
php_openssl_init_server_reneg_limit(php_stream * stream,php_openssl_netstream_data_t * sslsock)1174 static void php_openssl_init_server_reneg_limit(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
1175 {
1176 	zval *val;
1177 	zend_long limit = OPENSSL_DEFAULT_RENEG_LIMIT;
1178 	zend_long window = OPENSSL_DEFAULT_RENEG_WINDOW;
1179 
1180 	if (PHP_STREAM_CONTEXT(stream) &&
1181 		NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_limit"))
1182 	) {
1183 		limit = zval_get_long(val);
1184 	}
1185 
1186 	/* No renegotiation rate-limiting */
1187 	if (limit < 0) {
1188 		return;
1189 	}
1190 
1191 	if (PHP_STREAM_CONTEXT(stream) &&
1192 		NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_window"))
1193 	) {
1194 		window = zval_get_long(val);
1195 	}
1196 
1197 	sslsock->reneg = (void*)pemalloc(sizeof(php_openssl_handshake_bucket_t),
1198 		php_stream_is_persistent(stream)
1199 	);
1200 
1201 	sslsock->reneg->limit = limit;
1202 	sslsock->reneg->window = window;
1203 	sslsock->reneg->prev_handshake = 0;
1204 	sslsock->reneg->tokens = 0;
1205 	sslsock->reneg->should_close = 0;
1206 
1207 	SSL_set_info_callback(sslsock->ssl_handle, php_openssl_info_callback);
1208 }
1209 /* }}} */
1210 
1211 #if PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_tmp_rsa_cb(SSL * s,int is_export,int keylength)1212 static RSA *php_openssl_tmp_rsa_cb(SSL *s, int is_export, int keylength)
1213 {
1214 	BIGNUM *bn = NULL;
1215 	static RSA *rsa_tmp = NULL;
1216 
1217 	if (!rsa_tmp && ((bn = BN_new()) == NULL)) {
1218 		php_error_docref(NULL, E_WARNING, "allocation error generating RSA key");
1219 	}
1220 	if (!rsa_tmp && bn) {
1221 		if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
1222 			!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
1223 			if (rsa_tmp) {
1224 				RSA_free(rsa_tmp);
1225 			}
1226 			rsa_tmp = NULL;
1227 		}
1228 		BN_free(bn);
1229 	}
1230 
1231 	return (rsa_tmp);
1232 }
1233 #endif
1234 
php_openssl_set_server_dh_param(php_stream * stream,SSL_CTX * ctx)1235 static int php_openssl_set_server_dh_param(php_stream * stream, SSL_CTX *ctx) /* {{{ */
1236 {
1237 	zval *zdhpath = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "dh_param");
1238 	if (zdhpath == NULL) {
1239 #if 0
1240 	/* Coming in OpenSSL 1.1 ... eventually we'll want to enable this
1241 	 * in the absence of an explicit dh_param.
1242 	 */
1243 	SSL_CTX_set_dh_auto(ctx, 1);
1244 #endif
1245 		return SUCCESS;
1246 	}
1247 
1248 	if (!try_convert_to_string(zdhpath)) {
1249 		return FAILURE;
1250 	}
1251 
1252 	BIO *bio = BIO_new_file(Z_STRVAL_P(zdhpath), PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
1253 
1254 	if (bio == NULL) {
1255 		php_error_docref(NULL, E_WARNING, "Invalid dh_param");
1256 		return FAILURE;
1257 	}
1258 
1259 #if PHP_OPENSSL_API_VERSION >= 0x30000
1260 	EVP_PKEY *pkey = PEM_read_bio_Parameters(bio, NULL);
1261 	BIO_free(bio);
1262 
1263 	if (pkey == NULL) {
1264 		php_error_docref(NULL, E_WARNING, "Failed reading DH params");
1265 		return FAILURE;
1266 	}
1267 
1268 	if (SSL_CTX_set0_tmp_dh_pkey(ctx, pkey) == 0) {
1269 		php_error_docref(NULL, E_WARNING, "Failed assigning DH params");
1270 		EVP_PKEY_free(pkey);
1271 		return FAILURE;
1272 	}
1273 #else
1274 	DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1275 	BIO_free(bio);
1276 
1277 	if (dh == NULL) {
1278 		php_error_docref(NULL, E_WARNING, "Failed reading DH params");
1279 		return FAILURE;
1280 	}
1281 
1282 	if (SSL_CTX_set_tmp_dh(ctx, dh) == 0) {
1283 		php_error_docref(NULL, E_WARNING, "Failed assigning DH params");
1284 		DH_free(dh);
1285 		return FAILURE;
1286 	}
1287 
1288 	DH_free(dh);
1289 #endif
1290 
1291 	return SUCCESS;
1292 }
1293 /* }}} */
1294 
1295 #if defined(HAVE_ECDH) && PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_set_server_ecdh_curve(php_stream * stream,SSL_CTX * ctx)1296 static int php_openssl_set_server_ecdh_curve(php_stream *stream, SSL_CTX *ctx) /* {{{ */
1297 {
1298 	zval *zvcurve;
1299 	int curve_nid;
1300 	EC_KEY *ecdh;
1301 
1302 	zvcurve = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "ecdh_curve");
1303 	if (zvcurve == NULL) {
1304 		SSL_CTX_set_ecdh_auto(ctx, 1);
1305 		return SUCCESS;
1306 	} else {
1307 		if (!try_convert_to_string(zvcurve)) {
1308 			return FAILURE;
1309 		}
1310 
1311 		curve_nid = OBJ_sn2nid(Z_STRVAL_P(zvcurve));
1312 		if (curve_nid == NID_undef) {
1313 			php_error_docref(NULL, E_WARNING, "Invalid ecdh_curve specified");
1314 			return FAILURE;
1315 		}
1316 	}
1317 
1318 	ecdh = EC_KEY_new_by_curve_name(curve_nid);
1319 	if (ecdh == NULL) {
1320 		php_error_docref(NULL, E_WARNING, "Failed generating ECDH curve");
1321 		return FAILURE;
1322 	}
1323 
1324 	SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1325 	EC_KEY_free(ecdh);
1326 
1327 	return SUCCESS;
1328 }
1329 /* }}} */
1330 #endif
1331 
php_openssl_set_server_specific_opts(php_stream * stream,SSL_CTX * ctx)1332 static int php_openssl_set_server_specific_opts(php_stream *stream, SSL_CTX *ctx) /* {{{ */
1333 {
1334 	zval *zv;
1335 	long ssl_ctx_options = SSL_CTX_get_options(ctx);
1336 
1337 #if defined(HAVE_ECDH) && PHP_OPENSSL_API_VERSION < 0x10100
1338 	if (php_openssl_set_server_ecdh_curve(stream, ctx) == FAILURE) {
1339 		return FAILURE;
1340 	}
1341 #endif
1342 
1343 #if PHP_OPENSSL_API_VERSION < 0x10100
1344 	SSL_CTX_set_tmp_rsa_callback(ctx, php_openssl_tmp_rsa_cb);
1345 #endif
1346 	/* We now use php_openssl_tmp_rsa_cb to generate a key of appropriate size whenever necessary */
1347 	if (php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "rsa_key_size") != NULL) {
1348 		php_error_docref(NULL, E_WARNING, "rsa_key_size context option has been removed");
1349 	}
1350 
1351 	if (php_openssl_set_server_dh_param(stream, ctx) == FAILURE) {
1352 		return FAILURE;
1353 	}
1354 
1355 	zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "single_dh_use");
1356 	if (zv == NULL || zend_is_true(zv)) {
1357 		ssl_ctx_options |= SSL_OP_SINGLE_DH_USE;
1358 	}
1359 
1360 	zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "honor_cipher_order");
1361 	if (zv == NULL || zend_is_true(zv)) {
1362 		ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
1363 	}
1364 
1365 	SSL_CTX_set_options(ctx, ssl_ctx_options);
1366 
1367 	return SUCCESS;
1368 }
1369 /* }}} */
1370 
1371 #ifdef HAVE_TLS_SNI
php_openssl_server_sni_callback(SSL * ssl_handle,int * al,void * arg)1372 static int php_openssl_server_sni_callback(SSL *ssl_handle, int *al, void *arg) /* {{{ */
1373 {
1374 	php_stream *stream;
1375 	php_openssl_netstream_data_t *sslsock;
1376 	unsigned i;
1377 	const char *server_name;
1378 
1379 	server_name = SSL_get_servername(ssl_handle, TLSEXT_NAMETYPE_host_name);
1380 
1381 	if (!server_name) {
1382 		return SSL_TLSEXT_ERR_NOACK;
1383 	}
1384 
1385 	stream = (php_stream*)SSL_get_ex_data(ssl_handle, php_openssl_get_ssl_stream_data_index());
1386 	sslsock = (php_openssl_netstream_data_t*)stream->abstract;
1387 
1388 	if (!(sslsock->sni_cert_count && sslsock->sni_certs)) {
1389 		return SSL_TLSEXT_ERR_NOACK;
1390 	}
1391 
1392 	for (i=0; i < sslsock->sni_cert_count; i++) {
1393 		if (php_openssl_matches_wildcard_name(server_name, sslsock->sni_certs[i].name)) {
1394 			SSL_set_SSL_CTX(ssl_handle, sslsock->sni_certs[i].ctx);
1395 			return SSL_TLSEXT_ERR_OK;
1396 		}
1397 	}
1398 
1399 	return SSL_TLSEXT_ERR_NOACK;
1400 }
1401 /* }}} */
1402 
php_openssl_create_sni_server_ctx(char * cert_path,char * key_path)1403 static SSL_CTX *php_openssl_create_sni_server_ctx(char *cert_path, char *key_path)  /* {{{ */
1404 {
1405 	/* The hello method is not inherited by SSL structs when assigning a new context
1406 	 * inside the SNI callback, so the just use SSLv23 */
1407 	SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method());
1408 
1409 	if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) != 1) {
1410 		php_error_docref(NULL, E_WARNING,
1411 			"Failed setting local cert chain file `%s'; " \
1412 			"check that your cafile/capath settings include " \
1413 			"details of your certificate and its issuer",
1414 			cert_path
1415 		);
1416 		SSL_CTX_free(ctx);
1417 		return NULL;
1418 	} else if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) != 1) {
1419 		php_error_docref(NULL, E_WARNING,
1420 			"Failed setting private key from file `%s'",
1421 			key_path
1422 		);
1423 		SSL_CTX_free(ctx);
1424 		return NULL;
1425 	}
1426 
1427 	return ctx;
1428 }
1429 /* }}} */
1430 
php_openssl_enable_server_sni(php_stream * stream,php_openssl_netstream_data_t * sslsock)1431 static int php_openssl_enable_server_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock)  /* {{{ */
1432 {
1433 	zval *val;
1434 	zval *current;
1435 	zend_string *key;
1436 	zend_ulong key_index;
1437 	int i = 0;
1438 	char resolved_path_buff[MAXPATHLEN];
1439 	SSL_CTX *ctx;
1440 
1441 	/* If the stream ctx disables SNI we're finished here */
1442 	if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
1443 		return SUCCESS;
1444 	}
1445 
1446 	/* If no SNI cert array is specified we're finished here */
1447 	if (!GET_VER_OPT("SNI_server_certs")) {
1448 		return SUCCESS;
1449 	}
1450 
1451 	if (Z_TYPE_P(val) != IS_ARRAY) {
1452 		php_error_docref(NULL, E_WARNING,
1453 			"SNI_server_certs requires an array mapping host names to cert paths"
1454 		);
1455 		return FAILURE;
1456 	}
1457 
1458 	sslsock->sni_cert_count = zend_hash_num_elements(Z_ARRVAL_P(val));
1459 	if (sslsock->sni_cert_count == 0) {
1460 		php_error_docref(NULL, E_WARNING,
1461 			"SNI_server_certs host cert array must not be empty"
1462 		);
1463 		return FAILURE;
1464 	}
1465 
1466 	sslsock->sni_certs = (php_openssl_sni_cert_t*)safe_pemalloc(sslsock->sni_cert_count,
1467 		sizeof(php_openssl_sni_cert_t), 0, php_stream_is_persistent(stream)
1468 	);
1469 	memset(sslsock->sni_certs, 0, sslsock->sni_cert_count * sizeof(php_openssl_sni_cert_t));
1470 
1471 	ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(val), key_index, key, current) {
1472 		(void) key_index;
1473 
1474 		if (!key) {
1475 			php_error_docref(NULL, E_WARNING,
1476 				"SNI_server_certs array requires string host name keys"
1477 			);
1478 			return FAILURE;
1479 		}
1480 
1481 		if (Z_TYPE_P(current) == IS_ARRAY) {
1482 			zval *local_pk, *local_cert;
1483 			zend_string *local_pk_str, *local_cert_str;
1484 			char resolved_cert_path_buff[MAXPATHLEN], resolved_pk_path_buff[MAXPATHLEN];
1485 
1486 			local_cert = zend_hash_str_find(Z_ARRVAL_P(current), "local_cert", sizeof("local_cert")-1);
1487 			if (local_cert == NULL) {
1488 				php_error_docref(NULL, E_WARNING,
1489 					"local_cert not present in the array"
1490 				);
1491 				return FAILURE;
1492 			}
1493 
1494 			local_cert_str = zval_try_get_string(local_cert);
1495 			if (UNEXPECTED(!local_cert_str)) {
1496 				return FAILURE;
1497 			}
1498 			if (!VCWD_REALPATH(ZSTR_VAL(local_cert_str), resolved_cert_path_buff)) {
1499 				php_error_docref(NULL, E_WARNING,
1500 					"Failed setting local cert chain file `%s'; file not found",
1501 					ZSTR_VAL(local_cert_str)
1502 				);
1503 				zend_string_release(local_cert_str);
1504 				return FAILURE;
1505 			}
1506 			zend_string_release(local_cert_str);
1507 
1508 			local_pk = zend_hash_str_find(Z_ARRVAL_P(current), "local_pk", sizeof("local_pk")-1);
1509 			if (local_pk == NULL) {
1510 				php_error_docref(NULL, E_WARNING,
1511 					"local_pk not present in the array"
1512 				);
1513 				return FAILURE;
1514 			}
1515 
1516 			local_pk_str = zval_try_get_string(local_pk);
1517 			if (UNEXPECTED(!local_pk_str)) {
1518 				return FAILURE;
1519 			}
1520 			if (!VCWD_REALPATH(ZSTR_VAL(local_pk_str), resolved_pk_path_buff)) {
1521 				php_error_docref(NULL, E_WARNING,
1522 					"Failed setting local private key file `%s'; file not found",
1523 					ZSTR_VAL(local_pk_str)
1524 				);
1525 				zend_string_release(local_pk_str);
1526 				return FAILURE;
1527 			}
1528 			zend_string_release(local_pk_str);
1529 
1530 			ctx = php_openssl_create_sni_server_ctx(resolved_cert_path_buff, resolved_pk_path_buff);
1531 
1532 		} else if (VCWD_REALPATH(Z_STRVAL_P(current), resolved_path_buff)) {
1533 			ctx = php_openssl_create_sni_server_ctx(resolved_path_buff, resolved_path_buff);
1534 		} else {
1535 			php_error_docref(NULL, E_WARNING,
1536 				"Failed setting local cert chain file `%s'; file not found",
1537 				Z_STRVAL_P(current)
1538 			);
1539 			return FAILURE;
1540 		}
1541 
1542 		if (ctx == NULL) {
1543 			return FAILURE;
1544 		}
1545 
1546 		sslsock->sni_certs[i].name = pestrdup(ZSTR_VAL(key), php_stream_is_persistent(stream));
1547 		sslsock->sni_certs[i].ctx = ctx;
1548 		++i;
1549 
1550 	} ZEND_HASH_FOREACH_END();
1551 
1552 	SSL_CTX_set_tlsext_servername_callback(sslsock->ctx, php_openssl_server_sni_callback);
1553 
1554 	return SUCCESS;
1555 }
1556 /* }}} */
1557 
php_openssl_enable_client_sni(php_stream * stream,php_openssl_netstream_data_t * sslsock)1558 static void php_openssl_enable_client_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
1559 {
1560 	zval *val;
1561 	char *sni_server_name;
1562 
1563 	/* If SNI is explicitly disabled we're finished here */
1564 	if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
1565 		return;
1566 	}
1567 
1568 	sni_server_name = sslsock->url_name;
1569 
1570 	GET_VER_OPT_STRING("peer_name", sni_server_name);
1571 
1572 	if (sni_server_name) {
1573 		SSL_set_tlsext_host_name(sslsock->ssl_handle, sni_server_name);
1574 	}
1575 }
1576 /* }}} */
1577 #endif
1578 
1579 #ifdef HAVE_TLS_ALPN
1580 /**
1581  * Parses a comma-separated list of strings into a string suitable for SSL_CTX_set_next_protos_advertised
1582  *   outlen: (output) set to the length of the resulting buffer on success.
1583  *   err: (maybe NULL) on failure, an error message line is written to this BIO.
1584  *   in: a NULL terminated string like "abc,def,ghi"
1585  *
1586  *   returns: an emalloced buffer or NULL on failure.
1587  */
php_openssl_alpn_protos_parse(unsigned short * outlen,const char * in)1588 static unsigned char *php_openssl_alpn_protos_parse(unsigned short *outlen, const char *in) /* {{{ */
1589 {
1590 	size_t len;
1591 	unsigned char *out;
1592 	size_t i, start = 0;
1593 
1594 	len = strlen(in);
1595 	if (len >= 65535) {
1596 		return NULL;
1597 	}
1598 
1599 	out = emalloc(strlen(in) + 1);
1600 
1601 	for (i = 0; i <= len; ++i) {
1602 		if (i == len || in[i] == ',') {
1603 			if (i - start > 255) {
1604 				efree(out);
1605 				return NULL;
1606 			}
1607 			out[start] = i - start;
1608 			start = i + 1;
1609 		} else {
1610 			out[i + 1] = in[i];
1611 		}
1612 	}
1613 
1614 	*outlen = len + 1;
1615 
1616 	return out;
1617 }
1618 /* }}} */
1619 
php_openssl_server_alpn_callback(SSL * ssl_handle,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1620 static int php_openssl_server_alpn_callback(SSL *ssl_handle,
1621 		const unsigned char **out, unsigned char *outlen,
1622 		const unsigned char *in, unsigned int inlen, void *arg) /* {{{ */
1623 {
1624 	php_openssl_netstream_data_t *sslsock = arg;
1625 
1626 	if (SSL_select_next_proto((unsigned char **)out, outlen, sslsock->alpn_ctx.data, sslsock->alpn_ctx.len, in, inlen) != OPENSSL_NPN_NEGOTIATED) {
1627 		return SSL_TLSEXT_ERR_NOACK;
1628 	}
1629 
1630 	return SSL_TLSEXT_ERR_OK;
1631 }
1632 /* }}} */
1633 
1634 #endif
1635 
php_openssl_setup_crypto(php_stream * stream,php_openssl_netstream_data_t * sslsock,php_stream_xport_crypto_param * cparam)1636 int php_openssl_setup_crypto(php_stream *stream,
1637 		php_openssl_netstream_data_t *sslsock,
1638 		php_stream_xport_crypto_param *cparam) /* {{{ */
1639 {
1640 	const SSL_METHOD *method;
1641 	int ssl_ctx_options;
1642 	int method_flags;
1643 	zend_long min_version = 0;
1644 	zend_long max_version = 0;
1645 	char *cipherlist = NULL;
1646 	char *alpn_protocols = NULL;
1647 	zval *val;
1648 
1649 	if (sslsock->ssl_handle) {
1650 		if (sslsock->s.is_blocked) {
1651 			php_error_docref(NULL, E_WARNING, "SSL/TLS already set-up for this stream");
1652 			return FAILURE;
1653 		} else {
1654 			return SUCCESS;
1655 		}
1656 	}
1657 
1658 	ERR_clear_error();
1659 
1660 	/* We need to do slightly different things based on client/server method
1661 	 * so lets remember which method was selected */
1662 	sslsock->is_client = cparam->inputs.method & STREAM_CRYPTO_IS_CLIENT;
1663 	method_flags = ((cparam->inputs.method >> 1) << 1);
1664 
1665 	method = sslsock->is_client ? SSLv23_client_method() : SSLv23_server_method();
1666 	sslsock->ctx = SSL_CTX_new(method);
1667 
1668 	GET_VER_OPT_LONG("min_proto_version", min_version);
1669 	GET_VER_OPT_LONG("max_proto_version", max_version);
1670 	method_flags = php_openssl_get_proto_version_flags(method_flags, min_version, max_version);
1671 #if PHP_OPENSSL_API_VERSION < 0x10100
1672 	ssl_ctx_options = php_openssl_get_crypto_method_ctx_flags(method_flags);
1673 #else
1674 	ssl_ctx_options = SSL_OP_ALL;
1675 #endif
1676 
1677 	if (sslsock->ctx == NULL) {
1678 		php_error_docref(NULL, E_WARNING, "SSL context creation failure");
1679 		return FAILURE;
1680 	}
1681 
1682 	if (GET_VER_OPT("no_ticket") && zend_is_true(val)) {
1683 		ssl_ctx_options |= SSL_OP_NO_TICKET;
1684 	}
1685 
1686 	ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1687 
1688 #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
1689 	/* Only for OpenSSL 3+ to keep OpenSSL 1.1.1 behavior */
1690 	ssl_ctx_options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
1691 #endif
1692 
1693 	if (!GET_VER_OPT("disable_compression") || zend_is_true(val)) {
1694 		ssl_ctx_options |= SSL_OP_NO_COMPRESSION;
1695 	}
1696 
1697 	if (GET_VER_OPT("verify_peer") && !zend_is_true(val)) {
1698 		php_openssl_disable_peer_verification(sslsock->ctx, stream);
1699 	} else if (FAILURE == php_openssl_enable_peer_verification(sslsock->ctx, stream)) {
1700 		return FAILURE;
1701 	}
1702 
1703 	/* callback for the passphrase (for localcert) */
1704 	if (GET_VER_OPT("passphrase")) {
1705 		SSL_CTX_set_default_passwd_cb_userdata(sslsock->ctx, stream);
1706 		SSL_CTX_set_default_passwd_cb(sslsock->ctx, php_openssl_passwd_callback);
1707 	}
1708 
1709 	GET_VER_OPT_STRING("ciphers", cipherlist);
1710 #ifndef USE_OPENSSL_SYSTEM_CIPHERS
1711 	if (!cipherlist) {
1712 		cipherlist = OPENSSL_DEFAULT_STREAM_CIPHERS;
1713 	}
1714 #endif
1715 	if (cipherlist) {
1716 		if (SSL_CTX_set_cipher_list(sslsock->ctx, cipherlist) != 1) {
1717 			return FAILURE;
1718 		}
1719 	}
1720 
1721 	if (GET_VER_OPT("security_level")) {
1722 		zend_long lval = zval_get_long(val);
1723 		if (lval < 0 || lval > 5) {
1724 			php_error_docref(NULL, E_WARNING, "Security level must be between 0 and 5");
1725 		}
1726 #ifdef HAVE_SEC_LEVEL
1727 		SSL_CTX_set_security_level(sslsock->ctx, lval);
1728 #endif
1729 	}
1730 
1731 	GET_VER_OPT_STRING("alpn_protocols", alpn_protocols);
1732 	if (alpn_protocols) {
1733 #ifdef HAVE_TLS_ALPN
1734 		{
1735 			unsigned short alpn_len;
1736 			unsigned char *alpn = php_openssl_alpn_protos_parse(&alpn_len, alpn_protocols);
1737 
1738 			if (alpn == NULL) {
1739 				php_error_docref(NULL, E_WARNING, "Failed parsing comma-separated TLS ALPN protocol string");
1740 				SSL_CTX_free(sslsock->ctx);
1741 				sslsock->ctx = NULL;
1742 				return FAILURE;
1743 			}
1744 			if (sslsock->is_client) {
1745 				SSL_CTX_set_alpn_protos(sslsock->ctx, alpn, alpn_len);
1746 			} else {
1747 				sslsock->alpn_ctx.data = (unsigned char *) pestrndup((const char*)alpn, alpn_len, php_stream_is_persistent(stream));
1748 				sslsock->alpn_ctx.len = alpn_len;
1749 				SSL_CTX_set_alpn_select_cb(sslsock->ctx, php_openssl_server_alpn_callback, sslsock);
1750 			}
1751 
1752 			efree(alpn);
1753 		}
1754 #else
1755 		php_error_docref(NULL, E_WARNING,
1756 			"alpn_protocols support is not compiled into the OpenSSL library against which PHP is linked");
1757 #endif
1758 	}
1759 
1760 	if (FAILURE == php_openssl_set_local_cert(sslsock->ctx, stream)) {
1761 		return FAILURE;
1762 	}
1763 
1764 	SSL_CTX_set_options(sslsock->ctx, ssl_ctx_options);
1765 
1766 #if PHP_OPENSSL_API_VERSION >= 0x10100
1767 	SSL_CTX_set_min_proto_version(sslsock->ctx, php_openssl_get_min_proto_version(method_flags));
1768 	SSL_CTX_set_max_proto_version(sslsock->ctx, php_openssl_get_max_proto_version(method_flags));
1769 #endif
1770 
1771 	if (sslsock->is_client == 0 &&
1772 		PHP_STREAM_CONTEXT(stream) &&
1773 		FAILURE == php_openssl_set_server_specific_opts(stream, sslsock->ctx)
1774 	) {
1775 		return FAILURE;
1776 	}
1777 
1778 	sslsock->ssl_handle = SSL_new(sslsock->ctx);
1779 
1780 	if (sslsock->ssl_handle == NULL) {
1781 		php_error_docref(NULL, E_WARNING, "SSL handle creation failure");
1782 		SSL_CTX_free(sslsock->ctx);
1783 		sslsock->ctx = NULL;
1784 #ifdef HAVE_TLS_ALPN
1785 		if (sslsock->alpn_ctx.data) {
1786 			pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
1787 			sslsock->alpn_ctx.data = NULL;
1788 		}
1789 #endif
1790 		return FAILURE;
1791 	} else {
1792 		SSL_set_ex_data(sslsock->ssl_handle, php_openssl_get_ssl_stream_data_index(), stream);
1793 	}
1794 
1795 	if (!SSL_set_fd(sslsock->ssl_handle, sslsock->s.socket)) {
1796 		php_openssl_handle_ssl_error(stream, 0, 1);
1797 	}
1798 
1799 #ifdef HAVE_TLS_SNI
1800 	/* Enable server-side SNI */
1801 	if (!sslsock->is_client && php_openssl_enable_server_sni(stream, sslsock) == FAILURE) {
1802 		return FAILURE;
1803 	}
1804 #endif
1805 
1806 	/* Enable server-side handshake renegotiation rate-limiting */
1807 	if (!sslsock->is_client) {
1808 		php_openssl_init_server_reneg_limit(stream, sslsock);
1809 	}
1810 
1811 #ifdef SSL_MODE_RELEASE_BUFFERS
1812 	SSL_set_mode(sslsock->ssl_handle, SSL_get_mode(sslsock->ssl_handle) | SSL_MODE_RELEASE_BUFFERS);
1813 #endif
1814 
1815 	if (cparam->inputs.session) {
1816 		if (cparam->inputs.session->ops != &php_openssl_socket_ops) {
1817 			php_error_docref(NULL, E_WARNING, "Supplied session stream must be an SSL enabled stream");
1818 		} else if (((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle == NULL) {
1819 			php_error_docref(NULL, E_WARNING, "Supplied SSL session stream is not initialized");
1820 		} else {
1821 			SSL_copy_session_id(sslsock->ssl_handle, ((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle);
1822 		}
1823 	}
1824 
1825 	return SUCCESS;
1826 }
1827 /* }}} */
1828 
php_openssl_capture_peer_certs(php_stream * stream,php_openssl_netstream_data_t * sslsock,X509 * peer_cert)1829 static int php_openssl_capture_peer_certs(php_stream *stream,
1830 		php_openssl_netstream_data_t *sslsock, X509 *peer_cert) /* {{{ */
1831 {
1832 	zval *val, zcert;
1833 	php_openssl_certificate_object *cert_object;
1834 	int cert_captured = 0;
1835 
1836 	if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1837 			"ssl", "capture_peer_cert")) &&
1838 		zend_is_true(val)
1839 	) {
1840 		object_init_ex(&zcert, php_openssl_certificate_ce);
1841 		cert_object = Z_OPENSSL_CERTIFICATE_P(&zcert);
1842 		cert_object->x509 = peer_cert;
1843 
1844 		php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate", &zcert);
1845 		zval_ptr_dtor(&zcert);
1846 		cert_captured = 1;
1847 	}
1848 
1849 	if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1850 			"ssl", "capture_peer_cert_chain")) &&
1851 		zend_is_true(val)
1852 	) {
1853 		zval arr;
1854 		STACK_OF(X509) *chain;
1855 
1856 		chain = SSL_get_peer_cert_chain(sslsock->ssl_handle);
1857 
1858 		if (chain && sk_X509_num(chain) > 0) {
1859 			int i;
1860 			array_init(&arr);
1861 
1862 			for (i = 0; i < sk_X509_num(chain); i++) {
1863 				X509 *mycert = X509_dup(sk_X509_value(chain, i));
1864 
1865 				object_init_ex(&zcert, php_openssl_certificate_ce);
1866 				cert_object = Z_OPENSSL_CERTIFICATE_P(&zcert);
1867 				cert_object->x509 = mycert;
1868 				add_next_index_zval(&arr, &zcert);
1869 			}
1870 
1871 		} else {
1872 			ZVAL_NULL(&arr);
1873 		}
1874 
1875 		php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate_chain", &arr);
1876 		zval_ptr_dtor(&arr);
1877 	}
1878 
1879 	return cert_captured;
1880 }
1881 /* }}} */
1882 
php_openssl_enable_crypto(php_stream * stream,php_openssl_netstream_data_t * sslsock,php_stream_xport_crypto_param * cparam)1883 static int php_openssl_enable_crypto(php_stream *stream,
1884 		php_openssl_netstream_data_t *sslsock,
1885 		php_stream_xport_crypto_param *cparam) /* {{{ */
1886 {
1887 	int n;
1888 	int retry = 1;
1889 	int cert_captured = 0;
1890 	X509 *peer_cert;
1891 
1892 	if (cparam->inputs.activate && !sslsock->ssl_active) {
1893 		struct timeval start_time, *timeout;
1894 		int	blocked = sslsock->s.is_blocked, has_timeout = 0;
1895 
1896 #ifdef HAVE_TLS_SNI
1897 		if (sslsock->is_client) {
1898 			php_openssl_enable_client_sni(stream, sslsock);
1899 		}
1900 #endif
1901 
1902 		if (!sslsock->state_set) {
1903 			if (sslsock->is_client) {
1904 				SSL_set_connect_state(sslsock->ssl_handle);
1905 			} else {
1906 				SSL_set_accept_state(sslsock->ssl_handle);
1907 			}
1908 			sslsock->state_set = 1;
1909 		}
1910 
1911 		if (SUCCESS == php_set_sock_blocking(sslsock->s.socket, 0)) {
1912 			sslsock->s.is_blocked = 0;
1913 			/* The following mode are added only if we are able to change socket
1914 			 * to non blocking mode which is also used for read and write */
1915 			SSL_set_mode(
1916 				sslsock->ssl_handle,
1917 				(
1918 					SSL_get_mode(sslsock->ssl_handle) |
1919 					SSL_MODE_ENABLE_PARTIAL_WRITE |
1920 					SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
1921 				)
1922 			);
1923 		}
1924 
1925 		timeout = sslsock->is_client ? &sslsock->connect_timeout : &sslsock->s.timeout;
1926 		has_timeout = !sslsock->s.is_blocked && (timeout->tv_sec > 0 || (timeout->tv_sec == 0 && timeout->tv_usec));
1927 		/* gettimeofday is not monotonic; using it here is not strictly correct */
1928 		if (has_timeout) {
1929 			gettimeofday(&start_time, NULL);
1930 		}
1931 
1932 		do {
1933 			struct timeval cur_time, elapsed_time;
1934 
1935 			ERR_clear_error();
1936 			if (sslsock->is_client) {
1937 				n = SSL_connect(sslsock->ssl_handle);
1938 			} else {
1939 				n = SSL_accept(sslsock->ssl_handle);
1940 			}
1941 
1942 			if (has_timeout) {
1943 				gettimeofday(&cur_time, NULL);
1944 				elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
1945 
1946 				if (php_openssl_compare_timeval( elapsed_time, *timeout) > 0) {
1947 					php_error_docref(NULL, E_WARNING, "SSL: Handshake timed out");
1948 					return -1;
1949 				}
1950 			}
1951 
1952 			if (n <= 0) {
1953 				/* in case of SSL_ERROR_WANT_READ/WRITE, do not retry in non-blocking mode */
1954 				retry = php_openssl_handle_ssl_error(stream, n, blocked);
1955 				if (retry) {
1956 					/* wait until something interesting happens in the socket. It may be a
1957 					 * timeout. Also consider the unlikely of possibility of a write block  */
1958 					int err = SSL_get_error(sslsock->ssl_handle, n);
1959 					struct timeval left_time;
1960 
1961 					if (has_timeout) {
1962 						left_time = php_openssl_subtract_timeval(*timeout, elapsed_time);
1963 					}
1964 					php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
1965 						(POLLIN|POLLPRI) : POLLOUT, has_timeout ? &left_time : NULL);
1966 				}
1967 			} else {
1968 				retry = 0;
1969 			}
1970 		} while (retry);
1971 
1972 		if (sslsock->s.is_blocked != blocked && SUCCESS == php_set_sock_blocking(sslsock->s.socket, blocked)) {
1973 			sslsock->s.is_blocked = blocked;
1974 		}
1975 
1976 		if (n == 1) {
1977 			peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
1978 			if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
1979 				cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
1980 			}
1981 
1982 			if (FAILURE == php_openssl_apply_peer_verification_policy(sslsock->ssl_handle, peer_cert, stream)) {
1983 				SSL_shutdown(sslsock->ssl_handle);
1984 				n = -1;
1985 			} else {
1986 				sslsock->ssl_active = 1;
1987 			}
1988 		} else if (errno == EAGAIN) {
1989 			n = 0;
1990 		} else {
1991 			n = -1;
1992 			/* We want to capture the peer cert even if verification fails*/
1993 			peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
1994 			if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
1995 				cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
1996 			}
1997 		}
1998 
1999 		if (n && peer_cert && cert_captured == 0) {
2000 			X509_free(peer_cert);
2001 		}
2002 
2003 		return n;
2004 
2005 	} else if (!cparam->inputs.activate && sslsock->ssl_active) {
2006 		/* deactivate - common for server/client */
2007 		SSL_shutdown(sslsock->ssl_handle);
2008 		sslsock->ssl_active = 0;
2009 	}
2010 
2011 	return -1;
2012 }
2013 /* }}} */
2014 
php_openssl_sockop_read(php_stream * stream,char * buf,size_t count)2015 static ssize_t php_openssl_sockop_read(php_stream *stream, char *buf, size_t count) /* {{{ */
2016 {
2017 	return php_openssl_sockop_io( 1, stream, buf, count );
2018 }
2019 /* }}} */
2020 
php_openssl_sockop_write(php_stream * stream,const char * buf,size_t count)2021 static ssize_t php_openssl_sockop_write(php_stream *stream, const char *buf, size_t count) /* {{{ */
2022 {
2023 	return php_openssl_sockop_io( 0, stream, (char*)buf, count );
2024 }
2025 /* }}} */
2026 
2027 /**
2028  * Factored out common functionality (blocking, timeout, loop management) for read and write.
2029  * Perform IO (read or write) to an SSL socket. If we have a timeout, we switch to non-blocking mode
2030  * for the duration of the operation, using select to do our waits. If we time out, or we have an error
2031  * report that back to PHP
2032  */
php_openssl_sockop_io(int read,php_stream * stream,char * buf,size_t count)2033 static ssize_t php_openssl_sockop_io(int read, php_stream *stream, char *buf, size_t count) /* {{{ */
2034 {
2035 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2036 
2037 	/* Only do this if SSL is active. */
2038 	if (sslsock->ssl_active) {
2039 		int retry = 1;
2040 		struct timeval start_time;
2041 		struct timeval *timeout = NULL;
2042 		int began_blocked = sslsock->s.is_blocked;
2043 		int has_timeout = 0;
2044 		int nr_bytes = 0;
2045 
2046 		/* prevent overflow in openssl */
2047 		if (count > INT_MAX) {
2048 			count = INT_MAX;
2049 		}
2050 
2051 		/* never use a timeout with non-blocking sockets */
2052 		if (began_blocked) {
2053 			timeout = &sslsock->s.timeout;
2054 		}
2055 
2056 		if (timeout && php_set_sock_blocking(sslsock->s.socket, 0) == SUCCESS) {
2057 			sslsock->s.is_blocked = 0;
2058 		}
2059 
2060 		if (!sslsock->s.is_blocked && timeout && (timeout->tv_sec > 0 || (timeout->tv_sec == 0 && timeout->tv_usec))) {
2061 			has_timeout = 1;
2062 			/* gettimeofday is not monotonic; using it here is not strictly correct */
2063 			gettimeofday(&start_time, NULL);
2064 		}
2065 
2066 		/* Main IO loop. */
2067 		do {
2068 			struct timeval cur_time, elapsed_time, left_time;
2069 
2070 			/* If we have a timeout to check, figure out how much time has elapsed since we started. */
2071 			if (has_timeout) {
2072 				gettimeofday(&cur_time, NULL);
2073 
2074 				/* Determine how much time we've taken so far. */
2075 				elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
2076 
2077 				/* and return an error if we've taken too long. */
2078 				if (php_openssl_compare_timeval(elapsed_time, *timeout) > 0 ) {
2079 					/* If the socket was originally blocking, set it back. */
2080 					if (began_blocked) {
2081 						php_set_sock_blocking(sslsock->s.socket, 1);
2082 						sslsock->s.is_blocked = 1;
2083 					}
2084 					sslsock->s.timeout_event = 1;
2085 					return -1;
2086 				}
2087 			}
2088 
2089 			/* Now, do the IO operation. Don't block if we can't complete... */
2090 			ERR_clear_error();
2091 			if (read) {
2092 				nr_bytes = SSL_read(sslsock->ssl_handle, buf, (int)count);
2093 
2094 				if (sslsock->reneg && sslsock->reneg->should_close) {
2095 					/* renegotiation rate limiting triggered */
2096 					php_stream_xport_shutdown(stream, (stream_shutdown_t)SHUT_RDWR);
2097 					nr_bytes = 0;
2098 					stream->eof = 1;
2099 					 break;
2100 				}
2101 			} else {
2102 				nr_bytes = SSL_write(sslsock->ssl_handle, buf, (int)count);
2103 			}
2104 
2105 			/* Now, how much time until we time out? */
2106 			if (has_timeout) {
2107 				left_time = php_openssl_subtract_timeval( *timeout, elapsed_time );
2108 			}
2109 
2110 			/* If we didn't do anything on the last loop (or an error) check to see if we should retry or exit. */
2111 			if (nr_bytes <= 0) {
2112 
2113 				/* Get the error code from SSL, and check to see if it's an error or not. */
2114 				int err = SSL_get_error(sslsock->ssl_handle, nr_bytes );
2115 				retry = php_openssl_handle_ssl_error(stream, nr_bytes, 0);
2116 
2117 				/* If we get this (the above doesn't check) then we'll retry as well. */
2118 				if (errno == EAGAIN && err == SSL_ERROR_WANT_READ && read) {
2119 					retry = 1;
2120 				}
2121 				if (errno == EAGAIN && err == SSL_ERROR_WANT_WRITE && read == 0) {
2122 					retry = 1;
2123 				}
2124 
2125 				/* Also, on reads, we may get this condition on an EOF. We should check properly. */
2126 				if (read) {
2127 					stream->eof = (retry == 0 && errno != EAGAIN && !SSL_pending(sslsock->ssl_handle));
2128 				}
2129 
2130 				/* Don't loop indefinitely in non-blocking mode if no data is available */
2131 				if (began_blocked == 0) {
2132 					break;
2133 				}
2134 
2135 				/* Now, if we have to wait some time, and we're supposed to be blocking, wait for the socket to become
2136 				 * available. Now, php_pollfd_for uses select to wait up to our time_left value only...
2137 				 */
2138 				if (retry) {
2139 					if (read) {
2140 						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
2141 							(POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
2142 					} else {
2143 						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
2144 							(POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
2145 					}
2146 				}
2147 			} else {
2148 				/* Else, if we got bytes back, check for possible errors. */
2149 				int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);
2150 
2151 				/* If we didn't get any error, then let's return it to PHP. */
2152 				if (err == SSL_ERROR_NONE) {
2153 					break;
2154 				}
2155 
2156 				/* Otherwise, we need to wait again (up to time_left or we get an error) */
2157 				if (began_blocked) {
2158 					if (read) {
2159 						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
2160 							(POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
2161 					} else {
2162 						php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
2163 							(POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
2164 					}
2165 				}
2166 			}
2167 
2168 			/* Finally, we keep going until we got data, and an SSL_ERROR_NONE, unless we had an error. */
2169 		} while (retry);
2170 
2171 		/* Tell PHP if we read / wrote bytes. */
2172 		if (nr_bytes > 0) {
2173 			php_stream_notify_progress_increment(PHP_STREAM_CONTEXT(stream), nr_bytes, 0);
2174 		}
2175 
2176 		/* And if we were originally supposed to be blocking, let's reset the socket to that. */
2177 		if (began_blocked && php_set_sock_blocking(sslsock->s.socket, 1) == SUCCESS) {
2178 			sslsock->s.is_blocked = 1;
2179 		}
2180 
2181 		return 0 > nr_bytes ? 0 : nr_bytes;
2182 	} else {
2183 		size_t nr_bytes = 0;
2184 
2185 		/* This block is if we had no timeout... We will just sit and wait forever on the IO operation. */
2186 		if (read) {
2187 			nr_bytes = php_stream_socket_ops.read(stream, buf, count);
2188 		} else {
2189 			nr_bytes = php_stream_socket_ops.write(stream, buf, count);
2190 		}
2191 
2192 		return nr_bytes;
2193 	}
2194 }
2195 /* }}} */
2196 
php_openssl_subtract_timeval(struct timeval a,struct timeval b)2197 static struct timeval php_openssl_subtract_timeval(struct timeval a, struct timeval b) /* {{{ */
2198 {
2199 	struct timeval difference;
2200 
2201 	difference.tv_sec  = a.tv_sec  - b.tv_sec;
2202 	difference.tv_usec = a.tv_usec - b.tv_usec;
2203 
2204 	if (a.tv_usec < b.tv_usec) {
2205 		difference.tv_sec  -= 1L;
2206 		difference.tv_usec += 1000000L;
2207 	}
2208 
2209 	return difference;
2210 }
2211 /* }}} */
2212 
php_openssl_compare_timeval(struct timeval a,struct timeval b)2213 static int php_openssl_compare_timeval( struct timeval a, struct timeval b )
2214 {
2215 	if (a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec) ) {
2216 		return 1;
2217 	} else if( a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec ) {
2218 		return 0;
2219 	} else {
2220 		return -1;
2221 	}
2222 }
2223 
php_openssl_sockop_close(php_stream * stream,int close_handle)2224 static int php_openssl_sockop_close(php_stream *stream, int close_handle) /* {{{ */
2225 {
2226 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2227 #ifdef PHP_WIN32
2228 	int n;
2229 #endif
2230 	unsigned i;
2231 
2232 	if (close_handle) {
2233 		if (sslsock->ssl_active) {
2234 			SSL_shutdown(sslsock->ssl_handle);
2235 			sslsock->ssl_active = 0;
2236 		}
2237 		if (sslsock->ssl_handle) {
2238 			SSL_free(sslsock->ssl_handle);
2239 			sslsock->ssl_handle = NULL;
2240 		}
2241 		if (sslsock->ctx) {
2242 			SSL_CTX_free(sslsock->ctx);
2243 			sslsock->ctx = NULL;
2244 		}
2245 #ifdef HAVE_TLS_ALPN
2246 		if (sslsock->alpn_ctx.data) {
2247 			pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
2248 		}
2249 #endif
2250 #ifdef PHP_WIN32
2251 		if (sslsock->s.socket == -1)
2252 			sslsock->s.socket = SOCK_ERR;
2253 #endif
2254 		if (sslsock->s.socket != SOCK_ERR) {
2255 #ifdef PHP_WIN32
2256 			/* prevent more data from coming in */
2257 			shutdown(sslsock->s.socket, SHUT_RD);
2258 
2259 			/* try to make sure that the OS sends all data before we close the connection.
2260 			 * Essentially, we are waiting for the socket to become writeable, which means
2261 			 * that all pending data has been sent.
2262 			 * We use a small timeout which should encourage the OS to send the data,
2263 			 * but at the same time avoid hanging indefinitely.
2264 			 * */
2265 			do {
2266 				n = php_pollfd_for_ms(sslsock->s.socket, POLLOUT, 500);
2267 			} while (n == -1 && php_socket_errno() == EINTR);
2268 #endif
2269 			closesocket(sslsock->s.socket);
2270 			sslsock->s.socket = SOCK_ERR;
2271 		}
2272 	}
2273 
2274 	if (sslsock->sni_certs) {
2275 		for (i = 0; i < sslsock->sni_cert_count; i++) {
2276 			if (sslsock->sni_certs[i].ctx) {
2277 				SSL_CTX_free(sslsock->sni_certs[i].ctx);
2278 				pefree(sslsock->sni_certs[i].name, php_stream_is_persistent(stream));
2279 			}
2280 		}
2281 		pefree(sslsock->sni_certs, php_stream_is_persistent(stream));
2282 		sslsock->sni_certs = NULL;
2283 	}
2284 
2285 	if (sslsock->url_name) {
2286 		pefree(sslsock->url_name, php_stream_is_persistent(stream));
2287 	}
2288 
2289 	if (sslsock->reneg) {
2290 		pefree(sslsock->reneg, php_stream_is_persistent(stream));
2291 	}
2292 
2293 	pefree(sslsock, php_stream_is_persistent(stream));
2294 
2295 	return 0;
2296 }
2297 /* }}} */
2298 
php_openssl_sockop_flush(php_stream * stream)2299 static int php_openssl_sockop_flush(php_stream *stream) /* {{{ */
2300 {
2301 	return php_stream_socket_ops.flush(stream);
2302 }
2303 /* }}} */
2304 
php_openssl_sockop_stat(php_stream * stream,php_stream_statbuf * ssb)2305 static int php_openssl_sockop_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
2306 {
2307 	return php_stream_socket_ops.stat(stream, ssb);
2308 }
2309 /* }}} */
2310 
php_openssl_tcp_sockop_accept(php_stream * stream,php_openssl_netstream_data_t * sock,php_stream_xport_param * xparam STREAMS_DC)2311 static inline int php_openssl_tcp_sockop_accept(php_stream *stream, php_openssl_netstream_data_t *sock,
2312 		php_stream_xport_param *xparam STREAMS_DC)  /* {{{ */
2313 {
2314 	int clisock;
2315 	bool nodelay = 0;
2316 	zval *tmpzval = NULL;
2317 
2318 	xparam->outputs.client = NULL;
2319 
2320 	if (PHP_STREAM_CONTEXT(stream) &&
2321 		(tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "tcp_nodelay")) != NULL &&
2322 		zend_is_true(tmpzval)) {
2323 		nodelay = 1;
2324 	}
2325 
2326 	clisock = php_network_accept_incoming(sock->s.socket,
2327 		xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
2328 		xparam->want_addr ? &xparam->outputs.addr : NULL,
2329 		xparam->want_addr ? &xparam->outputs.addrlen : NULL,
2330 		xparam->inputs.timeout,
2331 		xparam->want_errortext ? &xparam->outputs.error_text : NULL,
2332 		&xparam->outputs.error_code,
2333 		nodelay);
2334 
2335 	if (clisock >= 0) {
2336 		php_openssl_netstream_data_t *clisockdata = (php_openssl_netstream_data_t*) emalloc(sizeof(*clisockdata));
2337 
2338 		/* copy underlying tcp fields */
2339 		memset(clisockdata, 0, sizeof(*clisockdata));
2340 		memcpy(clisockdata, sock, sizeof(clisockdata->s));
2341 
2342 		clisockdata->s.socket = clisock;
2343 #ifdef __linux__
2344 		/* O_NONBLOCK is not inherited on Linux */
2345 		clisockdata->s.is_blocked = 1;
2346 #endif
2347 
2348 		xparam->outputs.client = php_stream_alloc_rel(stream->ops, clisockdata, NULL, "r+");
2349 		if (xparam->outputs.client) {
2350 			xparam->outputs.client->ctx = stream->ctx;
2351 			if (stream->ctx) {
2352 				GC_ADDREF(stream->ctx);
2353 			}
2354 		}
2355 
2356 		if (xparam->outputs.client && sock->enable_on_connect) {
2357 			/* remove the client bit */
2358 			if (sock->method & STREAM_CRYPTO_IS_CLIENT) {
2359 				sock->method = ((sock->method >> 1) << 1);
2360 			}
2361 
2362 			clisockdata->method = sock->method;
2363 
2364 			if (php_stream_xport_crypto_setup(xparam->outputs.client, clisockdata->method,
2365 					NULL) < 0 || php_stream_xport_crypto_enable(
2366 					xparam->outputs.client, 1) < 0) {
2367 				php_error_docref(NULL, E_WARNING, "Failed to enable crypto");
2368 
2369 				php_stream_close(xparam->outputs.client);
2370 				xparam->outputs.client = NULL;
2371 				xparam->outputs.returncode = -1;
2372 			}
2373 		}
2374 	}
2375 
2376 	return xparam->outputs.client == NULL ? -1 : 0;
2377 }
2378 /* }}} */
2379 
php_openssl_sockop_set_option(php_stream * stream,int option,int value,void * ptrparam)2380 static int php_openssl_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam)  /* {{{ */
2381 {
2382 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2383 	php_stream_xport_crypto_param *cparam = (php_stream_xport_crypto_param *)ptrparam;
2384 	php_stream_xport_param *xparam = (php_stream_xport_param *)ptrparam;
2385 
2386 	switch (option) {
2387 		case PHP_STREAM_OPTION_META_DATA_API:
2388 			if (sslsock->ssl_active) {
2389 				zval tmp;
2390 				char *proto_str;
2391 				const SSL_CIPHER *cipher;
2392 
2393 				array_init(&tmp);
2394 
2395 				switch (SSL_version(sslsock->ssl_handle)) {
2396 #ifdef HAVE_TLS13
2397 					case TLS1_3_VERSION: proto_str = "TLSv1.3"; break;
2398 #endif
2399 #ifdef HAVE_TLS12
2400 					case TLS1_2_VERSION: proto_str = "TLSv1.2"; break;
2401 #endif
2402 #ifdef HAVE_TLS11
2403 					case TLS1_1_VERSION: proto_str = "TLSv1.1"; break;
2404 #endif
2405 					case TLS1_VERSION: proto_str = "TLSv1"; break;
2406 #ifdef HAVE_SSL3
2407 					case SSL3_VERSION: proto_str = "SSLv3"; break;
2408 #endif
2409 					default: proto_str = "UNKNOWN";
2410 				}
2411 
2412 				cipher = SSL_get_current_cipher(sslsock->ssl_handle);
2413 
2414 				add_assoc_string(&tmp, "protocol", proto_str);
2415 				add_assoc_string(&tmp, "cipher_name", (char *) SSL_CIPHER_get_name(cipher));
2416 				add_assoc_long(&tmp, "cipher_bits", SSL_CIPHER_get_bits(cipher, NULL));
2417 				add_assoc_string(&tmp, "cipher_version", SSL_CIPHER_get_version(cipher));
2418 
2419 #ifdef HAVE_TLS_ALPN
2420 				{
2421 					const unsigned char *alpn_proto = NULL;
2422 					unsigned int alpn_proto_len = 0;
2423 
2424 					SSL_get0_alpn_selected(sslsock->ssl_handle, &alpn_proto, &alpn_proto_len);
2425 					if (alpn_proto) {
2426 						add_assoc_stringl(&tmp, "alpn_protocol", (char *)alpn_proto, alpn_proto_len);
2427 					}
2428 				}
2429 #endif
2430 				add_assoc_zval((zval *)ptrparam, "crypto", &tmp);
2431 			}
2432 
2433 			add_assoc_bool((zval *)ptrparam, "timed_out", sslsock->s.timeout_event);
2434 			add_assoc_bool((zval *)ptrparam, "blocked", sslsock->s.is_blocked);
2435 			add_assoc_bool((zval *)ptrparam, "eof", stream->eof);
2436 
2437 			return PHP_STREAM_OPTION_RETURN_OK;
2438 
2439 		case PHP_STREAM_OPTION_CHECK_LIVENESS:
2440 			{
2441 				struct timeval tv;
2442 				char buf;
2443 				int alive = 1;
2444 
2445 				if (value == -1) {
2446 					if (sslsock->s.timeout.tv_sec == -1) {
2447 #ifdef _WIN32
2448 						tv.tv_sec = (long)FG(default_socket_timeout);
2449 #else
2450 						tv.tv_sec = (time_t)FG(default_socket_timeout);
2451 #endif
2452 						tv.tv_usec = 0;
2453 					} else {
2454 						tv = sslsock->connect_timeout;
2455 					}
2456 				} else {
2457 					tv.tv_sec = value;
2458 					tv.tv_usec = 0;
2459 				}
2460 
2461 				if (sslsock->s.socket == -1) {
2462 					alive = 0;
2463 				} else if (php_pollfd_for(sslsock->s.socket, PHP_POLLREADABLE|POLLPRI, &tv) > 0) {
2464 					if (sslsock->ssl_active) {
2465 						int n = SSL_peek(sslsock->ssl_handle, &buf, sizeof(buf));
2466 						if (n <= 0) {
2467 							int err = SSL_get_error(sslsock->ssl_handle, n);
2468 							switch (err) {
2469 								case SSL_ERROR_SYSCALL:
2470 									alive = php_socket_errno() == EAGAIN;
2471 									break;
2472 								case SSL_ERROR_WANT_READ:
2473 								case SSL_ERROR_WANT_WRITE:
2474 									alive = 1;
2475 									break;
2476 								default:
2477 									/* any other problem is a fatal error */
2478 									alive = 0;
2479 							}
2480 						}
2481 					} else if (0 == recv(sslsock->s.socket, &buf, sizeof(buf), MSG_PEEK) && php_socket_errno() != EAGAIN) {
2482 						alive = 0;
2483 					}
2484 				}
2485 				return alive ? PHP_STREAM_OPTION_RETURN_OK : PHP_STREAM_OPTION_RETURN_ERR;
2486 			}
2487 
2488 		case PHP_STREAM_OPTION_CRYPTO_API:
2489 
2490 			switch(cparam->op) {
2491 
2492 				case STREAM_XPORT_CRYPTO_OP_SETUP:
2493 					cparam->outputs.returncode = php_openssl_setup_crypto(stream, sslsock, cparam);
2494 					return PHP_STREAM_OPTION_RETURN_OK;
2495 					break;
2496 				case STREAM_XPORT_CRYPTO_OP_ENABLE:
2497 					cparam->outputs.returncode = php_openssl_enable_crypto(stream, sslsock, cparam);
2498 					return PHP_STREAM_OPTION_RETURN_OK;
2499 					break;
2500 				default:
2501 					/* fall through */
2502 					break;
2503 			}
2504 
2505 			break;
2506 
2507 		case PHP_STREAM_OPTION_XPORT_API:
2508 			switch(xparam->op) {
2509 
2510 				case STREAM_XPORT_OP_CONNECT:
2511 				case STREAM_XPORT_OP_CONNECT_ASYNC:
2512 					/* TODO: Async connects need to check the enable_on_connect option when
2513 					 * we notice that the connect has actually been established */
2514 					php_stream_socket_ops.set_option(stream, option, value, ptrparam);
2515 
2516 					if ((sslsock->enable_on_connect) &&
2517 						((xparam->outputs.returncode == 0) ||
2518 						(xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC &&
2519 						xparam->outputs.returncode == 1 && xparam->outputs.error_code == EINPROGRESS)))
2520 					{
2521 						if (php_stream_xport_crypto_setup(stream, sslsock->method, NULL) < 0 ||
2522 								php_stream_xport_crypto_enable(stream, 1) < 0) {
2523 							php_error_docref(NULL, E_WARNING, "Failed to enable crypto");
2524 							xparam->outputs.returncode = -1;
2525 						}
2526 					}
2527 					return PHP_STREAM_OPTION_RETURN_OK;
2528 
2529 				case STREAM_XPORT_OP_ACCEPT:
2530 					/* we need to copy the additional fields that the underlying tcp transport
2531 					 * doesn't know about */
2532 					xparam->outputs.returncode = php_openssl_tcp_sockop_accept(stream, sslsock, xparam STREAMS_CC);
2533 
2534 
2535 					return PHP_STREAM_OPTION_RETURN_OK;
2536 
2537 				default:
2538 					/* fall through */
2539 					break;
2540 			}
2541 	}
2542 
2543 	return php_stream_socket_ops.set_option(stream, option, value, ptrparam);
2544 }
2545 /* }}} */
2546 
php_openssl_sockop_cast(php_stream * stream,int castas,void ** ret)2547 static int php_openssl_sockop_cast(php_stream *stream, int castas, void **ret)  /* {{{ */
2548 {
2549 	php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2550 
2551 	switch(castas)	{
2552 		case PHP_STREAM_AS_STDIO:
2553 			if (sslsock->ssl_active) {
2554 				return FAILURE;
2555 			}
2556 			if (ret)	{
2557 				*ret = fdopen(sslsock->s.socket, stream->mode);
2558 				if (*ret) {
2559 					return SUCCESS;
2560 				}
2561 				return FAILURE;
2562 			}
2563 			return SUCCESS;
2564 
2565 		case PHP_STREAM_AS_FD_FOR_SELECT:
2566 			if (ret) {
2567 				size_t pending;
2568 				if (stream->writepos == stream->readpos
2569 					&& sslsock->ssl_active
2570 					&& (pending = (size_t)SSL_pending(sslsock->ssl_handle)) > 0) {
2571 						php_stream_fill_read_buffer(stream, pending < stream->chunk_size
2572 							? pending
2573 							: stream->chunk_size);
2574 				}
2575 
2576 				*(php_socket_t *)ret = sslsock->s.socket;
2577 			}
2578 			return SUCCESS;
2579 
2580 		case PHP_STREAM_AS_FD:
2581 		case PHP_STREAM_AS_SOCKETD:
2582 			if (sslsock->ssl_active) {
2583 				return FAILURE;
2584 			}
2585 			if (ret) {
2586 				*(php_socket_t *)ret = sslsock->s.socket;
2587 			}
2588 			return SUCCESS;
2589 		default:
2590 			return FAILURE;
2591 	}
2592 }
2593 /* }}} */
2594 
2595 const php_stream_ops php_openssl_socket_ops = {
2596 	php_openssl_sockop_write, php_openssl_sockop_read,
2597 	php_openssl_sockop_close, php_openssl_sockop_flush,
2598 	"tcp_socket/ssl",
2599 	NULL, /* seek */
2600 	php_openssl_sockop_cast,
2601 	php_openssl_sockop_stat,
2602 	php_openssl_sockop_set_option,
2603 };
2604 
php_openssl_get_crypto_method(php_stream_context * ctx,zend_long crypto_method)2605 static zend_long php_openssl_get_crypto_method(
2606 		php_stream_context *ctx, zend_long crypto_method)  /* {{{ */
2607 {
2608 	zval *val;
2609 
2610 	if (ctx && (val = php_stream_context_get_option(ctx, "ssl", "crypto_method")) != NULL) {
2611 		crypto_method = zval_get_long(val);
2612 		crypto_method |= STREAM_CRYPTO_IS_CLIENT;
2613 	}
2614 
2615 	return crypto_method;
2616 }
2617 /* }}} */
2618 
php_openssl_get_url_name(const char * resourcename,size_t resourcenamelen,int is_persistent)2619 static char *php_openssl_get_url_name(const char *resourcename,
2620 		size_t resourcenamelen, int is_persistent)  /* {{{ */
2621 {
2622 	php_url *url;
2623 
2624 	if (!resourcename) {
2625 		return NULL;
2626 	}
2627 
2628 	url = php_url_parse_ex(resourcename, resourcenamelen);
2629 	if (!url) {
2630 		return NULL;
2631 	}
2632 
2633 	if (url->host) {
2634 		const char * host = ZSTR_VAL(url->host);
2635 		char * url_name = NULL;
2636 		size_t len = ZSTR_LEN(url->host);
2637 
2638 		/* skip trailing dots */
2639 		while (len && host[len-1] == '.') {
2640 			--len;
2641 		}
2642 
2643 		if (len) {
2644 			url_name = pestrndup(host, len, is_persistent);
2645 		}
2646 
2647 		php_url_free(url);
2648 		return url_name;
2649 	}
2650 
2651 	php_url_free(url);
2652 	return NULL;
2653 }
2654 /* }}} */
2655 
php_openssl_ssl_socket_factory(const char * proto,size_t protolen,const char * resourcename,size_t resourcenamelen,const char * persistent_id,int options,int flags,struct timeval * timeout,php_stream_context * context STREAMS_DC)2656 php_stream *php_openssl_ssl_socket_factory(const char *proto, size_t protolen,
2657 		const char *resourcename, size_t resourcenamelen,
2658 		const char *persistent_id, int options, int flags,
2659 		struct timeval *timeout,
2660 		php_stream_context *context STREAMS_DC) /* {{{ */
2661 {
2662 	php_stream *stream = NULL;
2663 	php_openssl_netstream_data_t *sslsock = NULL;
2664 
2665 	sslsock = pemalloc(sizeof(php_openssl_netstream_data_t), persistent_id ? 1 : 0);
2666 	memset(sslsock, 0, sizeof(*sslsock));
2667 
2668 	sslsock->s.is_blocked = 1;
2669 	/* this timeout is used by standard stream funcs, therefore it should use the default value */
2670 #ifdef _WIN32
2671 	sslsock->s.timeout.tv_sec = (long)FG(default_socket_timeout);
2672 #else
2673 	sslsock->s.timeout.tv_sec = (time_t)FG(default_socket_timeout);
2674 #endif
2675 	sslsock->s.timeout.tv_usec = 0;
2676 
2677 	/* use separate timeout for our private funcs */
2678 	sslsock->connect_timeout.tv_sec = timeout->tv_sec;
2679 	sslsock->connect_timeout.tv_usec = timeout->tv_usec;
2680 
2681 	/* we don't know the socket until we have determined if we are binding or
2682 	 * connecting */
2683 	sslsock->s.socket = -1;
2684 
2685 	/* Initialize context as NULL */
2686 	sslsock->ctx = NULL;
2687 
2688 	stream = php_stream_alloc_rel(&php_openssl_socket_ops, sslsock, persistent_id, "r+");
2689 
2690 	if (stream == NULL)	{
2691 		pefree(sslsock, persistent_id ? 1 : 0);
2692 		return NULL;
2693 	}
2694 
2695 	if (strncmp(proto, "ssl", protolen) == 0) {
2696 		sslsock->enable_on_connect = 1;
2697 		sslsock->method = php_openssl_get_crypto_method(context, STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT);
2698 	} else if (strncmp(proto, "sslv2", protolen) == 0) {
2699 		php_error_docref(NULL, E_WARNING, "SSLv2 unavailable in this PHP version");
2700 		php_stream_close(stream);
2701 		return NULL;
2702 	} else if (strncmp(proto, "sslv3", protolen) == 0) {
2703 #ifdef HAVE_SSL3
2704 		sslsock->enable_on_connect = 1;
2705 		sslsock->method = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
2706 #else
2707 		php_error_docref(NULL, E_WARNING,
2708 			"SSLv3 support is not compiled into the OpenSSL library against which PHP is linked");
2709 		php_stream_close(stream);
2710 		return NULL;
2711 #endif
2712 	} else if (strncmp(proto, "tls", protolen) == 0) {
2713 		sslsock->enable_on_connect = 1;
2714 		sslsock->method = php_openssl_get_crypto_method(context, STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT);
2715 	} else if (strncmp(proto, "tlsv1.0", protolen) == 0) {
2716 		sslsock->enable_on_connect = 1;
2717 		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT;
2718 	} else if (strncmp(proto, "tlsv1.1", protolen) == 0) {
2719 #ifdef HAVE_TLS11
2720 		sslsock->enable_on_connect = 1;
2721 		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
2722 #else
2723 		php_error_docref(NULL, E_WARNING,
2724 			"TLSv1.1 support is not compiled into the OpenSSL library against which PHP is linked");
2725 		php_stream_close(stream);
2726 		return NULL;
2727 #endif
2728 	} else if (strncmp(proto, "tlsv1.2", protolen) == 0) {
2729 #ifdef HAVE_TLS12
2730 		sslsock->enable_on_connect = 1;
2731 		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
2732 #else
2733 		php_error_docref(NULL, E_WARNING,
2734 			"TLSv1.2 support is not compiled into the OpenSSL library against which PHP is linked");
2735 		php_stream_close(stream);
2736 		return NULL;
2737 #endif
2738 	} else if (strncmp(proto, "tlsv1.3", protolen) == 0) {
2739 #ifdef HAVE_TLS13
2740 		sslsock->enable_on_connect = 1;
2741 		sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT;
2742 #else
2743 		php_error_docref(NULL, E_WARNING,
2744 			"TLSv1.3 support is not compiled into the OpenSSL library against which PHP is linked");
2745 		php_stream_close(stream);
2746 		return NULL;
2747 #endif
2748 	}
2749 
2750 	sslsock->url_name = php_openssl_get_url_name(resourcename, resourcenamelen, !!persistent_id);
2751 
2752 	return stream;
2753 }
2754 /* }}} */
2755