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