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