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 #if OPENSSL_VERSION_NUMBER >= 0x10101000 && !defined(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 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(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 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
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 int 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 #if OPENSSL_VERSION_NUMBER < 0x10100000L
680 X509 *cert = x509_store_ctx->cert;
681 #else
682 X509 *cert = X509_STORE_CTX_get0_cert(x509_store_ctx);
683 #endif
684
685 php_stream *stream;
686 php_openssl_netstream_data_t *sslsock;
687 zval *val;
688 bool is_self_signed = 0;
689
690
691 stream = (php_stream*)arg;
692 sslsock = (php_openssl_netstream_data_t*)stream->abstract;
693
694 { /* First convert the x509 struct back to a DER encoded buffer and let Windows decode it into a form it can work with */
695 unsigned char *der_buf = NULL;
696 int der_len;
697
698 der_len = i2d_X509(cert, &der_buf);
699 if (der_len < 0) {
700 unsigned long err_code, e;
701 char err_buf[512];
702
703 while ((e = ERR_get_error()) != 0) {
704 err_code = e;
705 }
706
707 php_error_docref(NULL, E_WARNING, "Error encoding X509 certificate: %d: %s", err_code, ERR_error_string(err_code, err_buf));
708 RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
709 }
710
711 cert_ctx = CertCreateCertificateContext(X509_ASN_ENCODING, der_buf, der_len);
712 OPENSSL_free(der_buf);
713
714 if (cert_ctx == NULL) {
715 char *err = php_win_err();
716 php_error_docref(NULL, E_WARNING, "Error creating certificate context: %s", err);
717 php_win_err_free(err);
718 RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
719 }
720 }
721
722 { /* Next fetch the relevant cert chain from the store */
723 CERT_ENHKEY_USAGE enhkey_usage = {0};
724 CERT_USAGE_MATCH cert_usage = {0};
725 CERT_CHAIN_PARA chain_params = {sizeof(CERT_CHAIN_PARA)};
726 LPSTR usages[] = {szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE};
727 DWORD chain_flags = 0;
728 unsigned long allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;
729 unsigned int i;
730
731 enhkey_usage.cUsageIdentifier = 3;
732 enhkey_usage.rgpszUsageIdentifier = usages;
733 cert_usage.dwType = USAGE_MATCH_TYPE_OR;
734 cert_usage.Usage = enhkey_usage;
735 chain_params.RequestedUsage = cert_usage;
736 chain_flags = CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
737
738 if (!CertGetCertificateChain(NULL, cert_ctx, NULL, NULL, &chain_params, chain_flags, NULL, &cert_chain_ctx)) {
739 char *err = php_win_err();
740 php_error_docref(NULL, E_WARNING, "Error getting certificate chain: %s", err);
741 php_win_err_free(err);
742 CertFreeCertificateContext(cert_ctx);
743 RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
744 }
745
746 /* check if the cert is self-signed */
747 if (cert_chain_ctx->cChain > 0 && cert_chain_ctx->rgpChain[0]->cElement > 0
748 && (cert_chain_ctx->rgpChain[0]->rgpElement[0]->TrustStatus.dwInfoStatus & CERT_TRUST_IS_SELF_SIGNED) != 0) {
749 is_self_signed = 1;
750 }
751
752 /* check the depth */
753 GET_VER_OPT_LONG("verify_depth", allowed_depth);
754
755 for (i = 0; i < cert_chain_ctx->cChain; i++) {
756 if (cert_chain_ctx->rgpChain[i]->cElement > allowed_depth) {
757 CertFreeCertificateChain(cert_chain_ctx);
758 CertFreeCertificateContext(cert_ctx);
759 RETURN_CERT_VERIFY_FAILURE(X509_V_ERR_CERT_CHAIN_TOO_LONG);
760 }
761 }
762 }
763
764 { /* Then verify it against a policy */
765 SSL_EXTRA_CERT_CHAIN_POLICY_PARA ssl_policy_params = {sizeof(SSL_EXTRA_CERT_CHAIN_POLICY_PARA)};
766 CERT_CHAIN_POLICY_PARA chain_policy_params = {sizeof(CERT_CHAIN_POLICY_PARA)};
767 CERT_CHAIN_POLICY_STATUS chain_policy_status = {sizeof(CERT_CHAIN_POLICY_STATUS)};
768 BOOL verify_result;
769
770 ssl_policy_params.dwAuthType = (sslsock->is_client) ? AUTHTYPE_SERVER : AUTHTYPE_CLIENT;
771 /* we validate the name ourselves using the peer_name
772 ctx option, so no need to use a server name here */
773 ssl_policy_params.pwszServerName = NULL;
774 chain_policy_params.pvExtraPolicyPara = &ssl_policy_params;
775
776 verify_result = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, cert_chain_ctx, &chain_policy_params, &chain_policy_status);
777
778 CertFreeCertificateChain(cert_chain_ctx);
779 CertFreeCertificateContext(cert_ctx);
780
781 if (!verify_result) {
782 char *err = php_win_err();
783 php_error_docref(NULL, E_WARNING, "Error verifying certificate chain policy: %s", err);
784 php_win_err_free(err);
785 RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
786 }
787
788 if (chain_policy_status.dwError != 0) {
789 /* The chain does not match the policy */
790 if (is_self_signed && chain_policy_status.dwError == CERT_E_UNTRUSTEDROOT
791 && GET_VER_OPT("allow_self_signed") && zend_is_true(val)) {
792 /* allow self-signed certs */
793 X509_STORE_CTX_set_error(x509_store_ctx, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
794 } else {
795 RETURN_CERT_VERIFY_FAILURE(SSL_R_CERTIFICATE_VERIFY_FAILED);
796 }
797 }
798 }
799
800 return 1;
801 }
802 /* }}} */
803 #endif
804
php_openssl_load_stream_cafile(X509_STORE * cert_store,const char * cafile)805 static long php_openssl_load_stream_cafile(X509_STORE *cert_store, const char *cafile) /* {{{ */
806 {
807 php_stream *stream;
808 X509 *cert;
809 BIO *buffer;
810 int buffer_active = 0;
811 char *line = NULL;
812 size_t line_len;
813 long certs_added = 0;
814
815 stream = php_stream_open_wrapper(cafile, "rb", 0, NULL);
816
817 if (stream == NULL) {
818 php_error(E_WARNING, "failed loading cafile stream: `%s'", cafile);
819 return 0;
820 } else if (stream->wrapper->is_url) {
821 php_stream_close(stream);
822 php_error(E_WARNING, "remote cafile streams are disabled for security purposes");
823 return 0;
824 }
825
826 cert_start: {
827 line = php_stream_get_line(stream, NULL, 0, &line_len);
828 if (line == NULL) {
829 goto stream_complete;
830 } else if (!strcmp(line, "-----BEGIN CERTIFICATE-----\n") ||
831 !strcmp(line, "-----BEGIN CERTIFICATE-----\r\n")
832 ) {
833 buffer = BIO_new(BIO_s_mem());
834 buffer_active = 1;
835 goto cert_line;
836 } else {
837 efree(line);
838 goto cert_start;
839 }
840 }
841
842 cert_line: {
843 BIO_puts(buffer, line);
844 efree(line);
845 line = php_stream_get_line(stream, NULL, 0, &line_len);
846 if (line == NULL) {
847 goto stream_complete;
848 } else if (!strcmp(line, "-----END CERTIFICATE-----") ||
849 !strcmp(line, "-----END CERTIFICATE-----\n") ||
850 !strcmp(line, "-----END CERTIFICATE-----\r\n")
851 ) {
852 goto add_cert;
853 } else {
854 goto cert_line;
855 }
856 }
857
858 add_cert: {
859 BIO_puts(buffer, line);
860 efree(line);
861 cert = PEM_read_bio_X509(buffer, NULL, 0, NULL);
862 BIO_free(buffer);
863 buffer_active = 0;
864 if (cert && X509_STORE_add_cert(cert_store, cert)) {
865 ++certs_added;
866 X509_free(cert);
867 }
868 goto cert_start;
869 }
870
871 stream_complete: {
872 php_stream_close(stream);
873 if (buffer_active == 1) {
874 BIO_free(buffer);
875 }
876 }
877
878 if (certs_added == 0) {
879 php_error(E_WARNING, "no valid certs found cafile stream: `%s'", cafile);
880 }
881
882 return certs_added;
883 }
884 /* }}} */
885
php_openssl_enable_peer_verification(SSL_CTX * ctx,php_stream * stream)886 static int php_openssl_enable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
887 {
888 zval *val = NULL;
889 char *cafile = NULL;
890 char *capath = NULL;
891 php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
892
893 GET_VER_OPT_STRING("cafile", cafile);
894 GET_VER_OPT_STRING("capath", capath);
895
896 if (cafile == NULL) {
897 cafile = zend_ini_string("openssl.cafile", sizeof("openssl.cafile")-1, 0);
898 cafile = strlen(cafile) ? cafile : NULL;
899 } else if (!sslsock->is_client) {
900 /* Servers need to load and assign CA names from the cafile */
901 STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(cafile);
902 if (cert_names != NULL) {
903 SSL_CTX_set_client_CA_list(ctx, cert_names);
904 } else {
905 php_error(E_WARNING, "SSL: failed loading CA names from cafile");
906 return FAILURE;
907 }
908 }
909
910 if (capath == NULL) {
911 capath = zend_ini_string("openssl.capath", sizeof("openssl.capath")-1, 0);
912 capath = strlen(capath) ? capath : NULL;
913 }
914
915 if (cafile || capath) {
916 if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) {
917 ERR_clear_error();
918 if (cafile && !php_openssl_load_stream_cafile(SSL_CTX_get_cert_store(ctx), cafile)) {
919 return FAILURE;
920 }
921 }
922 } else {
923 #ifdef PHP_WIN32
924 SSL_CTX_set_cert_verify_callback(ctx, php_openssl_win_cert_verify_callback, (void *)stream);
925 #else
926 if (sslsock->is_client && !SSL_CTX_set_default_verify_paths(ctx)) {
927 php_error_docref(NULL, E_WARNING,
928 "Unable to set default verify locations and no CA settings specified");
929 return FAILURE;
930 }
931 #endif
932 }
933
934 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
935
936 return SUCCESS;
937 }
938 /* }}} */
939
php_openssl_disable_peer_verification(SSL_CTX * ctx,php_stream * stream)940 static void php_openssl_disable_peer_verification(SSL_CTX *ctx, php_stream *stream) /* {{{ */
941 {
942 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
943 }
944 /* }}} */
945
php_openssl_set_local_cert(SSL_CTX * ctx,php_stream * stream)946 static int php_openssl_set_local_cert(SSL_CTX *ctx, php_stream *stream) /* {{{ */
947 {
948 zval *val = NULL;
949 char *certfile = NULL;
950 size_t certfile_len;
951
952 GET_VER_OPT_STRINGL("local_cert", certfile, certfile_len);
953
954 if (certfile) {
955 char resolved_path_buff[MAXPATHLEN];
956 const char *private_key = NULL;
957 size_t private_key_len;
958
959 if (!php_openssl_check_path_ex(
960 certfile, certfile_len, resolved_path_buff, 0, false, false,
961 "local_cert in ssl stream context")) {
962 php_error_docref(NULL, E_WARNING, "Unable to get real path of certificate file `%s'", certfile);
963 return FAILURE;
964 }
965 /* a certificate to use for authentication */
966 if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
967 php_error_docref(NULL, E_WARNING,
968 "Unable to set local cert chain file `%s'; Check that your cafile/capath "
969 "settings include details of your certificate and its issuer",
970 certfile);
971 return FAILURE;
972 }
973
974 GET_VER_OPT_STRINGL("local_pk", private_key, private_key_len);
975 if (private_key && !php_openssl_check_path_ex(
976 private_key, private_key_len, resolved_path_buff, 0, false, false,
977 "local_pk in ssl stream context")) {
978 php_error_docref(NULL, E_WARNING, "Unable to get real path of private key file `%s'", private_key);
979 return FAILURE;
980 }
981 if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
982 php_error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff);
983 return FAILURE;
984 }
985 if (!SSL_CTX_check_private_key(ctx)) {
986 php_error_docref(NULL, E_WARNING, "Private key does not match certificate!");
987 }
988 }
989
990 return SUCCESS;
991 }
992 /* }}} */
993
994 #if PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_get_crypto_method_ctx_flags(int method_flags)995 static int php_openssl_get_crypto_method_ctx_flags(int method_flags) /* {{{ */
996 {
997 int ssl_ctx_options = SSL_OP_ALL;
998
999 #ifdef SSL_OP_NO_SSLv2
1000 ssl_ctx_options |= SSL_OP_NO_SSLv2;
1001 #endif
1002 #ifdef HAVE_SSL3
1003 if (!(method_flags & STREAM_CRYPTO_METHOD_SSLv3)) {
1004 ssl_ctx_options |= SSL_OP_NO_SSLv3;
1005 }
1006 #endif
1007 #ifdef HAVE_TLS1
1008 if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_0)) {
1009 ssl_ctx_options |= SSL_OP_NO_TLSv1;
1010 }
1011 #endif
1012 #ifdef HAVE_TLS11
1013 if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_1)) {
1014 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
1015 }
1016 #endif
1017 #ifdef HAVE_TLS12
1018 if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_2)) {
1019 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
1020 }
1021 #endif
1022 #ifdef HAVE_TLS13
1023 if (!(method_flags & STREAM_CRYPTO_METHOD_TLSv1_3)) {
1024 ssl_ctx_options |= SSL_OP_NO_TLSv1_3;
1025 }
1026 #endif
1027
1028 return ssl_ctx_options;
1029 }
1030 /* }}} */
1031 #endif
1032
php_openssl_get_min_proto_version_flag(int flags)1033 static inline int php_openssl_get_min_proto_version_flag(int flags) /* {{{ */
1034 {
1035 int ver;
1036 for (ver = PHP_OPENSSL_MIN_PROTO_VERSION; ver <= PHP_OPENSSL_MAX_PROTO_VERSION; ver <<= 1) {
1037 if (flags & ver) {
1038 return ver;
1039 }
1040 }
1041 return PHP_OPENSSL_MAX_PROTO_VERSION;
1042 }
1043 /* }}} */
1044
php_openssl_get_max_proto_version_flag(int flags)1045 static inline int php_openssl_get_max_proto_version_flag(int flags) /* {{{ */
1046 {
1047 int ver;
1048 for (ver = PHP_OPENSSL_MAX_PROTO_VERSION; ver >= PHP_OPENSSL_MIN_PROTO_VERSION; ver >>= 1) {
1049 if (flags & ver) {
1050 return ver;
1051 }
1052 }
1053 return STREAM_CRYPTO_METHOD_TLSv1_3;
1054 }
1055 /* }}} */
1056
1057 #if PHP_OPENSSL_API_VERSION >= 0x10100
php_openssl_map_proto_version(int flag)1058 static inline int php_openssl_map_proto_version(int flag) /* {{{ */
1059 {
1060 switch (flag) {
1061 #ifdef HAVE_TLS13
1062 case STREAM_CRYPTO_METHOD_TLSv1_3:
1063 return TLS1_3_VERSION;
1064 #endif
1065 case STREAM_CRYPTO_METHOD_TLSv1_2:
1066 return TLS1_2_VERSION;
1067 case STREAM_CRYPTO_METHOD_TLSv1_1:
1068 return TLS1_1_VERSION;
1069 case STREAM_CRYPTO_METHOD_TLSv1_0:
1070 return TLS1_VERSION;
1071 #ifdef HAVE_SSL3
1072 case STREAM_CRYPTO_METHOD_SSLv3:
1073 return SSL3_VERSION;
1074 #endif
1075 default:
1076 return TLS1_2_VERSION;
1077 }
1078 }
1079 /* }}} */
1080
php_openssl_get_min_proto_version(int flags)1081 static int php_openssl_get_min_proto_version(int flags) /* {{{ */
1082 {
1083 return php_openssl_map_proto_version(php_openssl_get_min_proto_version_flag(flags));
1084 }
1085 /* }}} */
1086
php_openssl_get_max_proto_version(int flags)1087 static int php_openssl_get_max_proto_version(int flags) /* {{{ */
1088 {
1089 return php_openssl_map_proto_version(php_openssl_get_max_proto_version_flag(flags));
1090 }
1091 /* }}} */
1092 #endif
1093
php_openssl_get_proto_version_flags(int flags,int min,int max)1094 static int php_openssl_get_proto_version_flags(int flags, int min, int max) /* {{{ */
1095 {
1096 int ver;
1097
1098 if (!min) {
1099 min = php_openssl_get_min_proto_version_flag(flags);
1100 }
1101 if (!max) {
1102 max = php_openssl_get_max_proto_version_flag(flags);
1103 }
1104
1105 for (ver = PHP_OPENSSL_MIN_PROTO_VERSION; ver <= PHP_OPENSSL_MAX_PROTO_VERSION; ver <<= 1) {
1106 if (ver >= min && ver <= max) {
1107 if (!(flags & ver)) {
1108 flags |= ver;
1109 }
1110 } else if (flags & ver) {
1111 flags &= ~ver;
1112 }
1113 }
1114
1115 return flags;
1116 }
1117 /* }}} */
1118
php_openssl_limit_handshake_reneg(const SSL * ssl)1119 static void php_openssl_limit_handshake_reneg(const SSL *ssl) /* {{{ */
1120 {
1121 php_stream *stream;
1122 php_openssl_netstream_data_t *sslsock;
1123 struct timeval now;
1124 zend_long elapsed_time;
1125
1126 stream = php_openssl_get_stream_from_ssl_handle(ssl);
1127 sslsock = (php_openssl_netstream_data_t*)stream->abstract;
1128 gettimeofday(&now, NULL);
1129
1130 /* The initial handshake is never rate-limited */
1131 if (sslsock->reneg->prev_handshake == 0) {
1132 sslsock->reneg->prev_handshake = now.tv_sec;
1133 return;
1134 }
1135
1136 elapsed_time = (now.tv_sec - sslsock->reneg->prev_handshake);
1137 sslsock->reneg->prev_handshake = now.tv_sec;
1138 sslsock->reneg->tokens -= (elapsed_time * (sslsock->reneg->limit / sslsock->reneg->window));
1139
1140 if (sslsock->reneg->tokens < 0) {
1141 sslsock->reneg->tokens = 0;
1142 }
1143 ++sslsock->reneg->tokens;
1144
1145 /* The token level exceeds our allowed limit */
1146 if (sslsock->reneg->tokens > sslsock->reneg->limit) {
1147 zval *val;
1148
1149
1150 sslsock->reneg->should_close = 1;
1151
1152 if (PHP_STREAM_CONTEXT(stream) && (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1153 "ssl", "reneg_limit_callback")) != NULL
1154 ) {
1155 zval param, retval;
1156
1157 php_stream_to_zval(stream, ¶m);
1158
1159 /* Closing the stream inside this callback would segfault! */
1160 stream->flags |= PHP_STREAM_FLAG_NO_FCLOSE;
1161 if (FAILURE == call_user_function(NULL, NULL, val, &retval, 1, ¶m)) {
1162 php_error(E_WARNING, "SSL: failed invoking reneg limit notification callback");
1163 }
1164 stream->flags ^= PHP_STREAM_FLAG_NO_FCLOSE;
1165
1166 /* If the reneg_limit_callback returned true don't auto-close */
1167 if (Z_TYPE(retval) == IS_TRUE) {
1168 sslsock->reneg->should_close = 0;
1169 }
1170
1171 zval_ptr_dtor(&retval);
1172 } else {
1173 php_error_docref(NULL, E_WARNING,
1174 "SSL: client-initiated handshake rate limit exceeded by peer");
1175 }
1176 }
1177 }
1178 /* }}} */
1179
php_openssl_info_callback(const SSL * ssl,int where,int ret)1180 static void php_openssl_info_callback(const SSL *ssl, int where, int ret) /* {{{ */
1181 {
1182 /* Rate-limit client-initiated handshake renegotiation to prevent DoS */
1183 if (where & SSL_CB_HANDSHAKE_START) {
1184 php_openssl_limit_handshake_reneg(ssl);
1185 }
1186 }
1187 /* }}} */
1188
php_openssl_init_server_reneg_limit(php_stream * stream,php_openssl_netstream_data_t * sslsock)1189 static void php_openssl_init_server_reneg_limit(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
1190 {
1191 zval *val;
1192 zend_long limit = OPENSSL_DEFAULT_RENEG_LIMIT;
1193 zend_long window = OPENSSL_DEFAULT_RENEG_WINDOW;
1194
1195 if (PHP_STREAM_CONTEXT(stream) &&
1196 NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_limit"))
1197 ) {
1198 limit = zval_get_long(val);
1199 }
1200
1201 /* No renegotiation rate-limiting */
1202 if (limit < 0) {
1203 return;
1204 }
1205
1206 if (PHP_STREAM_CONTEXT(stream) &&
1207 NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "reneg_window"))
1208 ) {
1209 window = zval_get_long(val);
1210 }
1211
1212 sslsock->reneg = (void*)pemalloc(sizeof(php_openssl_handshake_bucket_t),
1213 php_stream_is_persistent(stream)
1214 );
1215
1216 sslsock->reneg->limit = limit;
1217 sslsock->reneg->window = window;
1218 sslsock->reneg->prev_handshake = 0;
1219 sslsock->reneg->tokens = 0;
1220 sslsock->reneg->should_close = 0;
1221
1222 SSL_set_info_callback(sslsock->ssl_handle, php_openssl_info_callback);
1223 }
1224 /* }}} */
1225
1226 #if PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_tmp_rsa_cb(SSL * s,int is_export,int keylength)1227 static RSA *php_openssl_tmp_rsa_cb(SSL *s, int is_export, int keylength)
1228 {
1229 BIGNUM *bn = NULL;
1230 static RSA *rsa_tmp = NULL;
1231
1232 if (!rsa_tmp && ((bn = BN_new()) == NULL)) {
1233 php_error_docref(NULL, E_WARNING, "allocation error generating RSA key");
1234 }
1235 if (!rsa_tmp && bn) {
1236 if (!BN_set_word(bn, RSA_F4) || ((rsa_tmp = RSA_new()) == NULL) ||
1237 !RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) {
1238 if (rsa_tmp) {
1239 RSA_free(rsa_tmp);
1240 }
1241 rsa_tmp = NULL;
1242 }
1243 BN_free(bn);
1244 }
1245
1246 return (rsa_tmp);
1247 }
1248 #endif
1249
php_openssl_set_server_dh_param(php_stream * stream,SSL_CTX * ctx)1250 static int php_openssl_set_server_dh_param(php_stream * stream, SSL_CTX *ctx) /* {{{ */
1251 {
1252 zval *zdhpath = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "dh_param");
1253 if (zdhpath == NULL) {
1254 #if 0
1255 /* Coming in OpenSSL 1.1 ... eventually we'll want to enable this
1256 * in the absence of an explicit dh_param.
1257 */
1258 SSL_CTX_set_dh_auto(ctx, 1);
1259 #endif
1260 return SUCCESS;
1261 }
1262
1263 if (!try_convert_to_string(zdhpath)) {
1264 return FAILURE;
1265 }
1266
1267 BIO *bio = BIO_new_file(Z_STRVAL_P(zdhpath), PHP_OPENSSL_BIO_MODE_R(PKCS7_BINARY));
1268
1269 if (bio == NULL) {
1270 php_error_docref(NULL, E_WARNING, "Invalid dh_param");
1271 return FAILURE;
1272 }
1273
1274 #if PHP_OPENSSL_API_VERSION >= 0x30000
1275 EVP_PKEY *pkey = PEM_read_bio_Parameters(bio, NULL);
1276 BIO_free(bio);
1277
1278 if (pkey == NULL) {
1279 php_error_docref(NULL, E_WARNING, "Failed reading DH params");
1280 return FAILURE;
1281 }
1282
1283 if (SSL_CTX_set0_tmp_dh_pkey(ctx, pkey) == 0) {
1284 php_error_docref(NULL, E_WARNING, "Failed assigning DH params");
1285 EVP_PKEY_free(pkey);
1286 return FAILURE;
1287 }
1288 #else
1289 DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1290 BIO_free(bio);
1291
1292 if (dh == NULL) {
1293 php_error_docref(NULL, E_WARNING, "Failed reading DH params");
1294 return FAILURE;
1295 }
1296
1297 if (SSL_CTX_set_tmp_dh(ctx, dh) == 0) {
1298 php_error_docref(NULL, E_WARNING, "Failed assigning DH params");
1299 DH_free(dh);
1300 return FAILURE;
1301 }
1302
1303 DH_free(dh);
1304 #endif
1305
1306 return SUCCESS;
1307 }
1308 /* }}} */
1309
1310 #if defined(HAVE_ECDH) && PHP_OPENSSL_API_VERSION < 0x10100
php_openssl_set_server_ecdh_curve(php_stream * stream,SSL_CTX * ctx)1311 static int php_openssl_set_server_ecdh_curve(php_stream *stream, SSL_CTX *ctx) /* {{{ */
1312 {
1313 zval *zvcurve;
1314 int curve_nid;
1315 EC_KEY *ecdh;
1316
1317 zvcurve = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "ecdh_curve");
1318 if (zvcurve == NULL) {
1319 SSL_CTX_set_ecdh_auto(ctx, 1);
1320 return SUCCESS;
1321 } else {
1322 if (!try_convert_to_string(zvcurve)) {
1323 return FAILURE;
1324 }
1325
1326 curve_nid = OBJ_sn2nid(Z_STRVAL_P(zvcurve));
1327 if (curve_nid == NID_undef) {
1328 php_error_docref(NULL, E_WARNING, "Invalid ecdh_curve specified");
1329 return FAILURE;
1330 }
1331 }
1332
1333 ecdh = EC_KEY_new_by_curve_name(curve_nid);
1334 if (ecdh == NULL) {
1335 php_error_docref(NULL, E_WARNING, "Failed generating ECDH curve");
1336 return FAILURE;
1337 }
1338
1339 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
1340 EC_KEY_free(ecdh);
1341
1342 return SUCCESS;
1343 }
1344 /* }}} */
1345 #endif
1346
php_openssl_set_server_specific_opts(php_stream * stream,SSL_CTX * ctx)1347 static int php_openssl_set_server_specific_opts(php_stream *stream, SSL_CTX *ctx) /* {{{ */
1348 {
1349 zval *zv;
1350 long ssl_ctx_options = SSL_CTX_get_options(ctx);
1351
1352 #if defined(HAVE_ECDH) && PHP_OPENSSL_API_VERSION < 0x10100
1353 if (php_openssl_set_server_ecdh_curve(stream, ctx) == FAILURE) {
1354 return FAILURE;
1355 }
1356 #endif
1357
1358 #if PHP_OPENSSL_API_VERSION < 0x10100
1359 SSL_CTX_set_tmp_rsa_callback(ctx, php_openssl_tmp_rsa_cb);
1360 #endif
1361 /* We now use php_openssl_tmp_rsa_cb to generate a key of appropriate size whenever necessary */
1362 if (php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "rsa_key_size") != NULL) {
1363 php_error_docref(NULL, E_WARNING, "rsa_key_size context option has been removed");
1364 }
1365
1366 if (php_openssl_set_server_dh_param(stream, ctx) == FAILURE) {
1367 return FAILURE;
1368 }
1369
1370 zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "single_dh_use");
1371 if (zv == NULL || zend_is_true(zv)) {
1372 ssl_ctx_options |= SSL_OP_SINGLE_DH_USE;
1373 }
1374
1375 zv = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "ssl", "honor_cipher_order");
1376 if (zv == NULL || zend_is_true(zv)) {
1377 ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
1378 }
1379
1380 SSL_CTX_set_options(ctx, ssl_ctx_options);
1381
1382 return SUCCESS;
1383 }
1384 /* }}} */
1385
1386 #ifdef HAVE_TLS_SNI
php_openssl_server_sni_callback(SSL * ssl_handle,int * al,void * arg)1387 static int php_openssl_server_sni_callback(SSL *ssl_handle, int *al, void *arg) /* {{{ */
1388 {
1389 php_stream *stream;
1390 php_openssl_netstream_data_t *sslsock;
1391 unsigned i;
1392 const char *server_name;
1393
1394 server_name = SSL_get_servername(ssl_handle, TLSEXT_NAMETYPE_host_name);
1395
1396 if (!server_name) {
1397 return SSL_TLSEXT_ERR_NOACK;
1398 }
1399
1400 stream = (php_stream*)SSL_get_ex_data(ssl_handle, php_openssl_get_ssl_stream_data_index());
1401 sslsock = (php_openssl_netstream_data_t*)stream->abstract;
1402
1403 if (!(sslsock->sni_cert_count && sslsock->sni_certs)) {
1404 return SSL_TLSEXT_ERR_NOACK;
1405 }
1406
1407 for (i=0; i < sslsock->sni_cert_count; i++) {
1408 if (php_openssl_matches_wildcard_name(server_name, sslsock->sni_certs[i].name)) {
1409 SSL_set_SSL_CTX(ssl_handle, sslsock->sni_certs[i].ctx);
1410 return SSL_TLSEXT_ERR_OK;
1411 }
1412 }
1413
1414 return SSL_TLSEXT_ERR_NOACK;
1415 }
1416 /* }}} */
1417
php_openssl_create_sni_server_ctx(char * cert_path,char * key_path)1418 static SSL_CTX *php_openssl_create_sni_server_ctx(char *cert_path, char *key_path) /* {{{ */
1419 {
1420 /* The hello method is not inherited by SSL structs when assigning a new context
1421 * inside the SNI callback, so the just use SSLv23 */
1422 SSL_CTX *ctx = SSL_CTX_new(SSLv23_server_method());
1423
1424 if (SSL_CTX_use_certificate_chain_file(ctx, cert_path) != 1) {
1425 php_error_docref(NULL, E_WARNING,
1426 "Failed setting local cert chain file `%s'; " \
1427 "check that your cafile/capath settings include " \
1428 "details of your certificate and its issuer",
1429 cert_path
1430 );
1431 SSL_CTX_free(ctx);
1432 return NULL;
1433 } else if (SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) != 1) {
1434 php_error_docref(NULL, E_WARNING,
1435 "Failed setting private key from file `%s'",
1436 key_path
1437 );
1438 SSL_CTX_free(ctx);
1439 return NULL;
1440 }
1441
1442 return ctx;
1443 }
1444 /* }}} */
1445
php_openssl_enable_server_sni(php_stream * stream,php_openssl_netstream_data_t * sslsock)1446 static int php_openssl_enable_server_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
1447 {
1448 zval *val;
1449 zval *current;
1450 zend_string *key;
1451 zend_ulong key_index;
1452 int i = 0;
1453 char resolved_path_buff[MAXPATHLEN];
1454 SSL_CTX *ctx;
1455
1456 /* If the stream ctx disables SNI we're finished here */
1457 if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
1458 return SUCCESS;
1459 }
1460
1461 /* If no SNI cert array is specified we're finished here */
1462 if (!GET_VER_OPT("SNI_server_certs")) {
1463 return SUCCESS;
1464 }
1465
1466 if (Z_TYPE_P(val) != IS_ARRAY) {
1467 php_error_docref(NULL, E_WARNING,
1468 "SNI_server_certs requires an array mapping host names to cert paths"
1469 );
1470 return FAILURE;
1471 }
1472
1473 sslsock->sni_cert_count = zend_hash_num_elements(Z_ARRVAL_P(val));
1474 if (sslsock->sni_cert_count == 0) {
1475 php_error_docref(NULL, E_WARNING,
1476 "SNI_server_certs host cert array must not be empty"
1477 );
1478 return FAILURE;
1479 }
1480
1481 sslsock->sni_certs = (php_openssl_sni_cert_t*)safe_pemalloc(sslsock->sni_cert_count,
1482 sizeof(php_openssl_sni_cert_t), 0, php_stream_is_persistent(stream)
1483 );
1484 memset(sslsock->sni_certs, 0, sslsock->sni_cert_count * sizeof(php_openssl_sni_cert_t));
1485
1486 ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(val), key_index, key, current) {
1487 (void) key_index;
1488
1489 if (!key) {
1490 php_error_docref(NULL, E_WARNING,
1491 "SNI_server_certs array requires string host name keys"
1492 );
1493 return FAILURE;
1494 }
1495
1496 if (Z_TYPE_P(current) == IS_ARRAY) {
1497 zval *local_pk, *local_cert;
1498 zend_string *local_pk_str, *local_cert_str;
1499 char resolved_cert_path_buff[MAXPATHLEN], resolved_pk_path_buff[MAXPATHLEN];
1500
1501 local_cert = zend_hash_str_find(Z_ARRVAL_P(current), "local_cert", sizeof("local_cert")-1);
1502 if (local_cert == NULL) {
1503 php_error_docref(NULL, E_WARNING,
1504 "local_cert not present in the array"
1505 );
1506 return FAILURE;
1507 }
1508
1509 local_cert_str = zval_try_get_string(local_cert);
1510 if (UNEXPECTED(!local_cert_str)) {
1511 return FAILURE;
1512 }
1513 if (!php_openssl_check_path_str_ex(
1514 local_cert_str, resolved_cert_path_buff, 0, false, false,
1515 "SNI_server_certs local_cert in ssl stream context")) {
1516 php_error_docref(NULL, E_WARNING,
1517 "Failed setting local cert chain file `%s'; could not open file",
1518 ZSTR_VAL(local_cert_str)
1519 );
1520 zend_string_release(local_cert_str);
1521 return FAILURE;
1522 }
1523 zend_string_release(local_cert_str);
1524
1525 local_pk = zend_hash_str_find(Z_ARRVAL_P(current), "local_pk", sizeof("local_pk")-1);
1526 if (local_pk == NULL) {
1527 php_error_docref(NULL, E_WARNING,
1528 "local_pk not present in the array"
1529 );
1530 return FAILURE;
1531 }
1532
1533 local_pk_str = zval_try_get_string(local_pk);
1534 if (UNEXPECTED(!local_pk_str)) {
1535 return FAILURE;
1536 }
1537 if (!php_openssl_check_path_str_ex(
1538 local_pk_str, resolved_pk_path_buff, 0, false, false,
1539 "SNI_server_certs local_pk in ssl stream context")) {
1540 php_error_docref(NULL, E_WARNING,
1541 "Failed setting local private key file `%s'; could not open file",
1542 ZSTR_VAL(local_pk_str)
1543 );
1544 zend_string_release(local_pk_str);
1545 return FAILURE;
1546 }
1547 zend_string_release(local_pk_str);
1548
1549 ctx = php_openssl_create_sni_server_ctx(resolved_cert_path_buff, resolved_pk_path_buff);
1550
1551 } else if (php_openssl_check_path_str_ex(
1552 Z_STR_P(current), resolved_path_buff, 0, false, false,
1553 "SNI_server_certs in ssl stream context")) {
1554 ctx = php_openssl_create_sni_server_ctx(resolved_path_buff, resolved_path_buff);
1555 } else {
1556 php_error_docref(NULL, E_WARNING,
1557 "Failed setting local cert chain file `%s'; file not found",
1558 Z_STRVAL_P(current)
1559 );
1560 return FAILURE;
1561 }
1562
1563 if (ctx == NULL) {
1564 return FAILURE;
1565 }
1566
1567 sslsock->sni_certs[i].name = pestrdup(ZSTR_VAL(key), php_stream_is_persistent(stream));
1568 sslsock->sni_certs[i].ctx = ctx;
1569 ++i;
1570
1571 } ZEND_HASH_FOREACH_END();
1572
1573 SSL_CTX_set_tlsext_servername_callback(sslsock->ctx, php_openssl_server_sni_callback);
1574
1575 return SUCCESS;
1576 }
1577 /* }}} */
1578
php_openssl_enable_client_sni(php_stream * stream,php_openssl_netstream_data_t * sslsock)1579 static void php_openssl_enable_client_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock) /* {{{ */
1580 {
1581 zval *val;
1582 char *sni_server_name;
1583
1584 /* If SNI is explicitly disabled we're finished here */
1585 if (GET_VER_OPT("SNI_enabled") && !zend_is_true(val)) {
1586 return;
1587 }
1588
1589 sni_server_name = sslsock->url_name;
1590
1591 GET_VER_OPT_STRING("peer_name", sni_server_name);
1592
1593 if (sni_server_name) {
1594 SSL_set_tlsext_host_name(sslsock->ssl_handle, sni_server_name);
1595 }
1596 }
1597 /* }}} */
1598 #endif
1599
1600 #ifdef HAVE_TLS_ALPN
1601 /**
1602 * Parses a comma-separated list of strings into a string suitable for SSL_CTX_set_next_protos_advertised
1603 * outlen: (output) set to the length of the resulting buffer on success.
1604 * err: (maybe NULL) on failure, an error message line is written to this BIO.
1605 * in: a NULL terminated string like "abc,def,ghi"
1606 *
1607 * returns: an emalloced buffer or NULL on failure.
1608 */
php_openssl_alpn_protos_parse(unsigned short * outlen,const char * in)1609 static unsigned char *php_openssl_alpn_protos_parse(unsigned short *outlen, const char *in) /* {{{ */
1610 {
1611 size_t len;
1612 unsigned char *out;
1613 size_t i, start = 0;
1614
1615 len = strlen(in);
1616 if (len >= 65535) {
1617 return NULL;
1618 }
1619
1620 out = emalloc(strlen(in) + 1);
1621
1622 for (i = 0; i <= len; ++i) {
1623 if (i == len || in[i] == ',') {
1624 if (i - start > 255) {
1625 efree(out);
1626 return NULL;
1627 }
1628 out[start] = i - start;
1629 start = i + 1;
1630 } else {
1631 out[i + 1] = in[i];
1632 }
1633 }
1634
1635 *outlen = len + 1;
1636
1637 return out;
1638 }
1639 /* }}} */
1640
php_openssl_server_alpn_callback(SSL * ssl_handle,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)1641 static int php_openssl_server_alpn_callback(SSL *ssl_handle,
1642 const unsigned char **out, unsigned char *outlen,
1643 const unsigned char *in, unsigned int inlen, void *arg) /* {{{ */
1644 {
1645 php_openssl_netstream_data_t *sslsock = arg;
1646
1647 if (SSL_select_next_proto((unsigned char **)out, outlen, sslsock->alpn_ctx.data, sslsock->alpn_ctx.len, in, inlen) != OPENSSL_NPN_NEGOTIATED) {
1648 return SSL_TLSEXT_ERR_NOACK;
1649 }
1650
1651 return SSL_TLSEXT_ERR_OK;
1652 }
1653 /* }}} */
1654
1655 #endif
1656
php_openssl_setup_crypto(php_stream * stream,php_openssl_netstream_data_t * sslsock,php_stream_xport_crypto_param * cparam)1657 int php_openssl_setup_crypto(php_stream *stream,
1658 php_openssl_netstream_data_t *sslsock,
1659 php_stream_xport_crypto_param *cparam) /* {{{ */
1660 {
1661 const SSL_METHOD *method;
1662 int ssl_ctx_options;
1663 int method_flags;
1664 zend_long min_version = 0;
1665 zend_long max_version = 0;
1666 char *cipherlist = NULL;
1667 char *alpn_protocols = NULL;
1668 zval *val;
1669
1670 if (sslsock->ssl_handle) {
1671 if (sslsock->s.is_blocked) {
1672 php_error_docref(NULL, E_WARNING, "SSL/TLS already set-up for this stream");
1673 return FAILURE;
1674 } else {
1675 return SUCCESS;
1676 }
1677 }
1678
1679 ERR_clear_error();
1680
1681 /* We need to do slightly different things based on client/server method
1682 * so lets remember which method was selected */
1683 sslsock->is_client = cparam->inputs.method & STREAM_CRYPTO_IS_CLIENT;
1684 method_flags = cparam->inputs.method & ~STREAM_CRYPTO_IS_CLIENT;
1685
1686 method = sslsock->is_client ? SSLv23_client_method() : SSLv23_server_method();
1687 sslsock->ctx = SSL_CTX_new(method);
1688
1689 if (sslsock->ctx == NULL) {
1690 php_error_docref(NULL, E_WARNING, "SSL context creation failure");
1691 return FAILURE;
1692 }
1693
1694 GET_VER_OPT_LONG("min_proto_version", min_version);
1695 GET_VER_OPT_LONG("max_proto_version", max_version);
1696 method_flags = php_openssl_get_proto_version_flags(method_flags, min_version, max_version);
1697 #if PHP_OPENSSL_API_VERSION < 0x10100
1698 ssl_ctx_options = php_openssl_get_crypto_method_ctx_flags(method_flags);
1699 #else
1700 ssl_ctx_options = SSL_OP_ALL;
1701 #endif
1702
1703 if (GET_VER_OPT("no_ticket") && zend_is_true(val)) {
1704 ssl_ctx_options |= SSL_OP_NO_TICKET;
1705 }
1706
1707 ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1708
1709 #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
1710 /* Only for OpenSSL 3+ to keep OpenSSL 1.1.1 behavior */
1711 ssl_ctx_options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
1712 #endif
1713
1714 if (!GET_VER_OPT("disable_compression") || zend_is_true(val)) {
1715 ssl_ctx_options |= SSL_OP_NO_COMPRESSION;
1716 }
1717
1718 if (GET_VER_OPT("verify_peer") && !zend_is_true(val)) {
1719 php_openssl_disable_peer_verification(sslsock->ctx, stream);
1720 } else if (FAILURE == php_openssl_enable_peer_verification(sslsock->ctx, stream)) {
1721 return FAILURE;
1722 }
1723
1724 /* callback for the passphrase (for localcert) */
1725 if (GET_VER_OPT("passphrase")) {
1726 SSL_CTX_set_default_passwd_cb_userdata(sslsock->ctx, stream);
1727 SSL_CTX_set_default_passwd_cb(sslsock->ctx, php_openssl_passwd_callback);
1728 }
1729
1730 GET_VER_OPT_STRING("ciphers", cipherlist);
1731 #ifndef USE_OPENSSL_SYSTEM_CIPHERS
1732 if (!cipherlist) {
1733 cipherlist = OPENSSL_DEFAULT_STREAM_CIPHERS;
1734 }
1735 #endif
1736 if (cipherlist) {
1737 if (SSL_CTX_set_cipher_list(sslsock->ctx, cipherlist) != 1) {
1738 return FAILURE;
1739 }
1740 }
1741
1742 if (GET_VER_OPT("security_level")) {
1743 zend_long lval = zval_get_long(val);
1744 if (lval < 0 || lval > 5) {
1745 php_error_docref(NULL, E_WARNING, "Security level must be between 0 and 5");
1746 }
1747 #ifdef HAVE_SEC_LEVEL
1748 SSL_CTX_set_security_level(sslsock->ctx, lval);
1749 #endif
1750 }
1751
1752 GET_VER_OPT_STRING("alpn_protocols", alpn_protocols);
1753 if (alpn_protocols) {
1754 #ifdef HAVE_TLS_ALPN
1755 {
1756 unsigned short alpn_len;
1757 unsigned char *alpn = php_openssl_alpn_protos_parse(&alpn_len, alpn_protocols);
1758
1759 if (alpn == NULL) {
1760 php_error_docref(NULL, E_WARNING, "Failed parsing comma-separated TLS ALPN protocol string");
1761 SSL_CTX_free(sslsock->ctx);
1762 sslsock->ctx = NULL;
1763 return FAILURE;
1764 }
1765 if (sslsock->is_client) {
1766 SSL_CTX_set_alpn_protos(sslsock->ctx, alpn, alpn_len);
1767 } else {
1768 sslsock->alpn_ctx.data = (unsigned char *) pestrndup((const char*)alpn, alpn_len, php_stream_is_persistent(stream));
1769 sslsock->alpn_ctx.len = alpn_len;
1770 SSL_CTX_set_alpn_select_cb(sslsock->ctx, php_openssl_server_alpn_callback, sslsock);
1771 }
1772
1773 efree(alpn);
1774 }
1775 #else
1776 php_error_docref(NULL, E_WARNING,
1777 "alpn_protocols support is not compiled into the OpenSSL library against which PHP is linked");
1778 #endif
1779 }
1780
1781 if (FAILURE == php_openssl_set_local_cert(sslsock->ctx, stream)) {
1782 return FAILURE;
1783 }
1784
1785 SSL_CTX_set_options(sslsock->ctx, ssl_ctx_options);
1786
1787 #if PHP_OPENSSL_API_VERSION >= 0x10100
1788 SSL_CTX_set_min_proto_version(sslsock->ctx, php_openssl_get_min_proto_version(method_flags));
1789 SSL_CTX_set_max_proto_version(sslsock->ctx, php_openssl_get_max_proto_version(method_flags));
1790 #endif
1791
1792 if (sslsock->is_client == 0 &&
1793 PHP_STREAM_CONTEXT(stream) &&
1794 FAILURE == php_openssl_set_server_specific_opts(stream, sslsock->ctx)
1795 ) {
1796 return FAILURE;
1797 }
1798
1799 sslsock->ssl_handle = SSL_new(sslsock->ctx);
1800
1801 if (sslsock->ssl_handle == NULL) {
1802 php_error_docref(NULL, E_WARNING, "SSL handle creation failure");
1803 SSL_CTX_free(sslsock->ctx);
1804 sslsock->ctx = NULL;
1805 #ifdef HAVE_TLS_ALPN
1806 if (sslsock->alpn_ctx.data) {
1807 pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
1808 sslsock->alpn_ctx.data = NULL;
1809 }
1810 #endif
1811 return FAILURE;
1812 } else {
1813 SSL_set_ex_data(sslsock->ssl_handle, php_openssl_get_ssl_stream_data_index(), stream);
1814 }
1815
1816 if (!SSL_set_fd(sslsock->ssl_handle, sslsock->s.socket)) {
1817 php_openssl_handle_ssl_error(stream, 0, 1);
1818 }
1819
1820 #ifdef HAVE_TLS_SNI
1821 /* Enable server-side SNI */
1822 if (!sslsock->is_client && php_openssl_enable_server_sni(stream, sslsock) == FAILURE) {
1823 return FAILURE;
1824 }
1825 #endif
1826
1827 /* Enable server-side handshake renegotiation rate-limiting */
1828 if (!sslsock->is_client) {
1829 php_openssl_init_server_reneg_limit(stream, sslsock);
1830 }
1831
1832 #ifdef SSL_MODE_RELEASE_BUFFERS
1833 SSL_set_mode(sslsock->ssl_handle, SSL_MODE_RELEASE_BUFFERS);
1834 #endif
1835
1836 if (cparam->inputs.session) {
1837 if (cparam->inputs.session->ops != &php_openssl_socket_ops) {
1838 php_error_docref(NULL, E_WARNING, "Supplied session stream must be an SSL enabled stream");
1839 } else if (((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle == NULL) {
1840 php_error_docref(NULL, E_WARNING, "Supplied SSL session stream is not initialized");
1841 } else {
1842 SSL_copy_session_id(sslsock->ssl_handle, ((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle);
1843 }
1844 }
1845
1846 return SUCCESS;
1847 }
1848 /* }}} */
1849
php_openssl_capture_peer_certs(php_stream * stream,php_openssl_netstream_data_t * sslsock,X509 * peer_cert)1850 static int php_openssl_capture_peer_certs(php_stream *stream,
1851 php_openssl_netstream_data_t *sslsock, X509 *peer_cert) /* {{{ */
1852 {
1853 zval *val, zcert;
1854 php_openssl_certificate_object *cert_object;
1855 int cert_captured = 0;
1856
1857 if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1858 "ssl", "capture_peer_cert")) &&
1859 zend_is_true(val)
1860 ) {
1861 object_init_ex(&zcert, php_openssl_certificate_ce);
1862 cert_object = Z_OPENSSL_CERTIFICATE_P(&zcert);
1863 cert_object->x509 = peer_cert;
1864
1865 php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate", &zcert);
1866 zval_ptr_dtor(&zcert);
1867 cert_captured = 1;
1868 }
1869
1870 if (NULL != (val = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream),
1871 "ssl", "capture_peer_cert_chain")) &&
1872 zend_is_true(val)
1873 ) {
1874 zval arr;
1875 STACK_OF(X509) *chain;
1876
1877 chain = SSL_get_peer_cert_chain(sslsock->ssl_handle);
1878
1879 if (chain && sk_X509_num(chain) > 0) {
1880 int i;
1881 array_init(&arr);
1882
1883 for (i = 0; i < sk_X509_num(chain); i++) {
1884 X509 *mycert = X509_dup(sk_X509_value(chain, i));
1885
1886 object_init_ex(&zcert, php_openssl_certificate_ce);
1887 cert_object = Z_OPENSSL_CERTIFICATE_P(&zcert);
1888 cert_object->x509 = mycert;
1889 add_next_index_zval(&arr, &zcert);
1890 }
1891
1892 } else {
1893 ZVAL_NULL(&arr);
1894 }
1895
1896 php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_certificate_chain", &arr);
1897 zval_ptr_dtor(&arr);
1898 }
1899
1900 return cert_captured;
1901 }
1902 /* }}} */
1903
php_openssl_enable_crypto(php_stream * stream,php_openssl_netstream_data_t * sslsock,php_stream_xport_crypto_param * cparam)1904 static int php_openssl_enable_crypto(php_stream *stream,
1905 php_openssl_netstream_data_t *sslsock,
1906 php_stream_xport_crypto_param *cparam) /* {{{ */
1907 {
1908 int n;
1909 int retry = 1;
1910 int cert_captured = 0;
1911 X509 *peer_cert;
1912
1913 if (cparam->inputs.activate && !sslsock->ssl_active) {
1914 struct timeval start_time, *timeout;
1915 int blocked = sslsock->s.is_blocked, has_timeout = 0;
1916
1917 #ifdef HAVE_TLS_SNI
1918 if (sslsock->is_client) {
1919 php_openssl_enable_client_sni(stream, sslsock);
1920 }
1921 #endif
1922
1923 if (!sslsock->state_set) {
1924 if (sslsock->is_client) {
1925 SSL_set_connect_state(sslsock->ssl_handle);
1926 } else {
1927 SSL_set_accept_state(sslsock->ssl_handle);
1928 }
1929 sslsock->state_set = 1;
1930 }
1931
1932 if (SUCCESS == php_set_sock_blocking(sslsock->s.socket, 0)) {
1933 sslsock->s.is_blocked = 0;
1934 /* The following mode are added only if we are able to change socket
1935 * to non blocking mode which is also used for read and write */
1936 SSL_set_mode(sslsock->ssl_handle, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1937 }
1938
1939 timeout = sslsock->is_client ? &sslsock->connect_timeout : &sslsock->s.timeout;
1940 has_timeout = !sslsock->s.is_blocked && (timeout->tv_sec > 0 || (timeout->tv_sec == 0 && timeout->tv_usec));
1941 /* gettimeofday is not monotonic; using it here is not strictly correct */
1942 if (has_timeout) {
1943 gettimeofday(&start_time, NULL);
1944 }
1945
1946 do {
1947 struct timeval cur_time, elapsed_time;
1948
1949 ERR_clear_error();
1950 if (sslsock->is_client) {
1951 n = SSL_connect(sslsock->ssl_handle);
1952 } else {
1953 n = SSL_accept(sslsock->ssl_handle);
1954 }
1955
1956 if (has_timeout) {
1957 gettimeofday(&cur_time, NULL);
1958 elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
1959
1960 if (php_openssl_compare_timeval( elapsed_time, *timeout) > 0) {
1961 php_error_docref(NULL, E_WARNING, "SSL: Handshake timed out");
1962 return -1;
1963 }
1964 }
1965
1966 if (n <= 0) {
1967 /* in case of SSL_ERROR_WANT_READ/WRITE, do not retry in non-blocking mode */
1968 retry = php_openssl_handle_ssl_error(stream, n, blocked);
1969 if (retry) {
1970 /* wait until something interesting happens in the socket. It may be a
1971 * timeout. Also consider the unlikely of possibility of a write block */
1972 int err = SSL_get_error(sslsock->ssl_handle, n);
1973 struct timeval left_time;
1974
1975 if (has_timeout) {
1976 left_time = php_openssl_subtract_timeval(*timeout, elapsed_time);
1977 }
1978 php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
1979 (POLLIN|POLLPRI) : POLLOUT, has_timeout ? &left_time : NULL);
1980 }
1981 } else {
1982 retry = 0;
1983 }
1984 } while (retry);
1985
1986 if (sslsock->s.is_blocked != blocked && SUCCESS == php_set_sock_blocking(sslsock->s.socket, blocked)) {
1987 sslsock->s.is_blocked = blocked;
1988 }
1989
1990 if (n == 1) {
1991 peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
1992 if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
1993 cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
1994 }
1995
1996 if (FAILURE == php_openssl_apply_peer_verification_policy(sslsock->ssl_handle, peer_cert, stream)) {
1997 SSL_shutdown(sslsock->ssl_handle);
1998 n = -1;
1999 } else {
2000 sslsock->ssl_active = 1;
2001 }
2002 } else if (errno == EAGAIN) {
2003 n = 0;
2004 } else {
2005 n = -1;
2006 /* We want to capture the peer cert even if verification fails*/
2007 peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
2008 if (peer_cert && PHP_STREAM_CONTEXT(stream)) {
2009 cert_captured = php_openssl_capture_peer_certs(stream, sslsock, peer_cert);
2010 }
2011 }
2012
2013 if (n && peer_cert && cert_captured == 0) {
2014 X509_free(peer_cert);
2015 }
2016
2017 return n;
2018
2019 } else if (!cparam->inputs.activate && sslsock->ssl_active) {
2020 /* deactivate - common for server/client */
2021 SSL_shutdown(sslsock->ssl_handle);
2022 sslsock->ssl_active = 0;
2023 }
2024
2025 return -1;
2026 }
2027 /* }}} */
2028
php_openssl_sockop_read(php_stream * stream,char * buf,size_t count)2029 static ssize_t php_openssl_sockop_read(php_stream *stream, char *buf, size_t count) /* {{{ */
2030 {
2031 return php_openssl_sockop_io( 1, stream, buf, count );
2032 }
2033 /* }}} */
2034
php_openssl_sockop_write(php_stream * stream,const char * buf,size_t count)2035 static ssize_t php_openssl_sockop_write(php_stream *stream, const char *buf, size_t count) /* {{{ */
2036 {
2037 return php_openssl_sockop_io( 0, stream, (char*)buf, count );
2038 }
2039 /* }}} */
2040
2041 /**
2042 * Factored out common functionality (blocking, timeout, loop management) for read and write.
2043 * Perform IO (read or write) to an SSL socket. If we have a timeout, we switch to non-blocking mode
2044 * for the duration of the operation, using select to do our waits. If we time out, or we have an error
2045 * report that back to PHP
2046 */
php_openssl_sockop_io(int read,php_stream * stream,char * buf,size_t count)2047 static ssize_t php_openssl_sockop_io(int read, php_stream *stream, char *buf, size_t count) /* {{{ */
2048 {
2049 php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2050
2051 /* Only do this if SSL is active. */
2052 if (sslsock->ssl_active) {
2053 int retry = 1;
2054 struct timeval start_time;
2055 struct timeval *timeout = NULL;
2056 int began_blocked = sslsock->s.is_blocked;
2057 int has_timeout = 0;
2058 int nr_bytes = 0;
2059
2060 /* prevent overflow in openssl */
2061 if (count > INT_MAX) {
2062 count = INT_MAX;
2063 }
2064
2065 /* never use a timeout with non-blocking sockets */
2066 if (began_blocked) {
2067 timeout = &sslsock->s.timeout;
2068 }
2069
2070 if (timeout && php_set_sock_blocking(sslsock->s.socket, 0) == SUCCESS) {
2071 sslsock->s.is_blocked = 0;
2072 }
2073
2074 if (!sslsock->s.is_blocked && timeout && (timeout->tv_sec > 0 || (timeout->tv_sec == 0 && timeout->tv_usec))) {
2075 has_timeout = 1;
2076 /* gettimeofday is not monotonic; using it here is not strictly correct */
2077 gettimeofday(&start_time, NULL);
2078 }
2079
2080 /* Main IO loop. */
2081 do {
2082 struct timeval cur_time, elapsed_time, left_time;
2083
2084 /* If we have a timeout to check, figure out how much time has elapsed since we started. */
2085 if (has_timeout) {
2086 gettimeofday(&cur_time, NULL);
2087
2088 /* Determine how much time we've taken so far. */
2089 elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
2090
2091 /* and return an error if we've taken too long. */
2092 if (php_openssl_compare_timeval(elapsed_time, *timeout) > 0 ) {
2093 /* If the socket was originally blocking, set it back. */
2094 if (began_blocked) {
2095 php_set_sock_blocking(sslsock->s.socket, 1);
2096 sslsock->s.is_blocked = 1;
2097 }
2098 sslsock->s.timeout_event = 1;
2099 return -1;
2100 }
2101 }
2102
2103 /* Now, do the IO operation. Don't block if we can't complete... */
2104 ERR_clear_error();
2105 if (read) {
2106 nr_bytes = SSL_read(sslsock->ssl_handle, buf, (int)count);
2107
2108 if (sslsock->reneg && sslsock->reneg->should_close) {
2109 /* renegotiation rate limiting triggered */
2110 php_stream_xport_shutdown(stream, (stream_shutdown_t)SHUT_RDWR);
2111 nr_bytes = 0;
2112 stream->eof = 1;
2113 break;
2114 }
2115 } else {
2116 nr_bytes = SSL_write(sslsock->ssl_handle, buf, (int)count);
2117 }
2118
2119 /* Now, how much time until we time out? */
2120 if (has_timeout) {
2121 left_time = php_openssl_subtract_timeval( *timeout, elapsed_time );
2122 }
2123
2124 /* If we didn't do anything on the last loop (or an error) check to see if we should retry or exit. */
2125 if (nr_bytes <= 0) {
2126
2127 /* Get the error code from SSL, and check to see if it's an error or not. */
2128 int err = SSL_get_error(sslsock->ssl_handle, nr_bytes );
2129 retry = php_openssl_handle_ssl_error(stream, nr_bytes, 0);
2130
2131 /* If we get this (the above doesn't check) then we'll retry as well. */
2132 if (errno == EAGAIN && err == SSL_ERROR_WANT_READ && read) {
2133 retry = 1;
2134 }
2135 if (errno == EAGAIN && err == SSL_ERROR_WANT_WRITE && read == 0) {
2136 retry = 1;
2137 }
2138
2139 /* Also, on reads, we may get this condition on an EOF. We should check properly. */
2140 if (read) {
2141 stream->eof = (retry == 0 && errno != EAGAIN && !SSL_pending(sslsock->ssl_handle));
2142 }
2143
2144 /* Don't loop indefinitely in non-blocking mode if no data is available */
2145 if (began_blocked == 0) {
2146 break;
2147 }
2148
2149 /* Now, if we have to wait some time, and we're supposed to be blocking, wait for the socket to become
2150 * available. Now, php_pollfd_for uses select to wait up to our time_left value only...
2151 */
2152 if (retry) {
2153 if (read) {
2154 php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
2155 (POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
2156 } else {
2157 php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
2158 (POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
2159 }
2160 }
2161 } else {
2162 /* Else, if we got bytes back, check for possible errors. */
2163 int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);
2164
2165 /* If we didn't get any error, then let's return it to PHP. */
2166 if (err == SSL_ERROR_NONE) {
2167 break;
2168 }
2169
2170 /* Otherwise, we need to wait again (up to time_left or we get an error) */
2171 if (began_blocked) {
2172 if (read) {
2173 php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_WRITE) ?
2174 (POLLOUT|POLLPRI) : (POLLIN|POLLPRI), has_timeout ? &left_time : NULL);
2175 } else {
2176 php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
2177 (POLLIN|POLLPRI) : (POLLOUT|POLLPRI), has_timeout ? &left_time : NULL);
2178 }
2179 }
2180 }
2181
2182 /* Finally, we keep going until we got data, and an SSL_ERROR_NONE, unless we had an error. */
2183 } while (retry);
2184
2185 /* Tell PHP if we read / wrote bytes. */
2186 if (nr_bytes > 0) {
2187 php_stream_notify_progress_increment(PHP_STREAM_CONTEXT(stream), nr_bytes, 0);
2188 }
2189
2190 /* And if we were originally supposed to be blocking, let's reset the socket to that. */
2191 if (began_blocked && php_set_sock_blocking(sslsock->s.socket, 1) == SUCCESS) {
2192 sslsock->s.is_blocked = 1;
2193 }
2194
2195 return 0 > nr_bytes ? 0 : nr_bytes;
2196 } else {
2197 size_t nr_bytes = 0;
2198
2199 /* This block is if we had no timeout... We will just sit and wait forever on the IO operation. */
2200 if (read) {
2201 nr_bytes = php_stream_socket_ops.read(stream, buf, count);
2202 } else {
2203 nr_bytes = php_stream_socket_ops.write(stream, buf, count);
2204 }
2205
2206 return nr_bytes;
2207 }
2208 }
2209 /* }}} */
2210
php_openssl_subtract_timeval(struct timeval a,struct timeval b)2211 static struct timeval php_openssl_subtract_timeval(struct timeval a, struct timeval b) /* {{{ */
2212 {
2213 struct timeval difference;
2214
2215 difference.tv_sec = a.tv_sec - b.tv_sec;
2216 difference.tv_usec = a.tv_usec - b.tv_usec;
2217
2218 if (a.tv_usec < b.tv_usec) {
2219 difference.tv_sec -= 1L;
2220 difference.tv_usec += 1000000L;
2221 }
2222
2223 return difference;
2224 }
2225 /* }}} */
2226
php_openssl_compare_timeval(struct timeval a,struct timeval b)2227 static int php_openssl_compare_timeval( struct timeval a, struct timeval b )
2228 {
2229 if (a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec) ) {
2230 return 1;
2231 } else if( a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec ) {
2232 return 0;
2233 } else {
2234 return -1;
2235 }
2236 }
2237
php_openssl_sockop_close(php_stream * stream,int close_handle)2238 static int php_openssl_sockop_close(php_stream *stream, int close_handle) /* {{{ */
2239 {
2240 php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2241 #ifdef PHP_WIN32
2242 int n;
2243 #endif
2244 unsigned i;
2245
2246 if (close_handle) {
2247 if (sslsock->ssl_active) {
2248 SSL_shutdown(sslsock->ssl_handle);
2249 sslsock->ssl_active = 0;
2250 }
2251 if (sslsock->ssl_handle) {
2252 SSL_free(sslsock->ssl_handle);
2253 sslsock->ssl_handle = NULL;
2254 }
2255 if (sslsock->ctx) {
2256 SSL_CTX_free(sslsock->ctx);
2257 sslsock->ctx = NULL;
2258 }
2259 #ifdef HAVE_TLS_ALPN
2260 if (sslsock->alpn_ctx.data) {
2261 pefree(sslsock->alpn_ctx.data, php_stream_is_persistent(stream));
2262 }
2263 #endif
2264 #ifdef PHP_WIN32
2265 if (sslsock->s.socket == -1)
2266 sslsock->s.socket = SOCK_ERR;
2267 #endif
2268 if (sslsock->s.socket != SOCK_ERR) {
2269 #ifdef PHP_WIN32
2270 /* prevent more data from coming in */
2271 shutdown(sslsock->s.socket, SHUT_RD);
2272
2273 /* try to make sure that the OS sends all data before we close the connection.
2274 * Essentially, we are waiting for the socket to become writeable, which means
2275 * that all pending data has been sent.
2276 * We use a small timeout which should encourage the OS to send the data,
2277 * but at the same time avoid hanging indefinitely.
2278 * */
2279 do {
2280 n = php_pollfd_for_ms(sslsock->s.socket, POLLOUT, 500);
2281 } while (n == -1 && php_socket_errno() == EINTR);
2282 #endif
2283 closesocket(sslsock->s.socket);
2284 sslsock->s.socket = SOCK_ERR;
2285 }
2286 }
2287
2288 if (sslsock->sni_certs) {
2289 for (i = 0; i < sslsock->sni_cert_count; i++) {
2290 if (sslsock->sni_certs[i].ctx) {
2291 SSL_CTX_free(sslsock->sni_certs[i].ctx);
2292 pefree(sslsock->sni_certs[i].name, php_stream_is_persistent(stream));
2293 }
2294 }
2295 pefree(sslsock->sni_certs, php_stream_is_persistent(stream));
2296 sslsock->sni_certs = NULL;
2297 }
2298
2299 if (sslsock->url_name) {
2300 pefree(sslsock->url_name, php_stream_is_persistent(stream));
2301 }
2302
2303 if (sslsock->reneg) {
2304 pefree(sslsock->reneg, php_stream_is_persistent(stream));
2305 }
2306
2307 pefree(sslsock, php_stream_is_persistent(stream));
2308
2309 return 0;
2310 }
2311 /* }}} */
2312
php_openssl_sockop_flush(php_stream * stream)2313 static int php_openssl_sockop_flush(php_stream *stream) /* {{{ */
2314 {
2315 return php_stream_socket_ops.flush(stream);
2316 }
2317 /* }}} */
2318
php_openssl_sockop_stat(php_stream * stream,php_stream_statbuf * ssb)2319 static int php_openssl_sockop_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
2320 {
2321 return php_stream_socket_ops.stat(stream, ssb);
2322 }
2323 /* }}} */
2324
php_openssl_tcp_sockop_accept(php_stream * stream,php_openssl_netstream_data_t * sock,php_stream_xport_param * xparam STREAMS_DC)2325 static inline int php_openssl_tcp_sockop_accept(php_stream *stream, php_openssl_netstream_data_t *sock,
2326 php_stream_xport_param *xparam STREAMS_DC) /* {{{ */
2327 {
2328 int clisock;
2329 bool nodelay = 0;
2330 zval *tmpzval = NULL;
2331
2332 xparam->outputs.client = NULL;
2333
2334 if (PHP_STREAM_CONTEXT(stream) &&
2335 (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "tcp_nodelay")) != NULL &&
2336 zend_is_true(tmpzval)) {
2337 nodelay = 1;
2338 }
2339
2340 clisock = php_network_accept_incoming(sock->s.socket,
2341 xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
2342 xparam->want_addr ? &xparam->outputs.addr : NULL,
2343 xparam->want_addr ? &xparam->outputs.addrlen : NULL,
2344 xparam->inputs.timeout,
2345 xparam->want_errortext ? &xparam->outputs.error_text : NULL,
2346 &xparam->outputs.error_code,
2347 nodelay);
2348
2349 if (clisock >= 0) {
2350 php_openssl_netstream_data_t *clisockdata = (php_openssl_netstream_data_t*) emalloc(sizeof(*clisockdata));
2351
2352 /* copy underlying tcp fields */
2353 memset(clisockdata, 0, sizeof(*clisockdata));
2354 memcpy(clisockdata, sock, sizeof(clisockdata->s));
2355
2356 clisockdata->s.socket = clisock;
2357 #ifdef __linux__
2358 /* O_NONBLOCK is not inherited on Linux */
2359 clisockdata->s.is_blocked = 1;
2360 #endif
2361
2362 xparam->outputs.client = php_stream_alloc_rel(stream->ops, clisockdata, NULL, "r+");
2363 if (xparam->outputs.client) {
2364 xparam->outputs.client->ctx = stream->ctx;
2365 if (stream->ctx) {
2366 GC_ADDREF(stream->ctx);
2367 }
2368 }
2369
2370 if (xparam->outputs.client && sock->enable_on_connect) {
2371 /* remove the client bit */
2372 sock->method &= ~STREAM_CRYPTO_IS_CLIENT;
2373
2374 clisockdata->method = sock->method;
2375
2376 if (php_stream_xport_crypto_setup(xparam->outputs.client, clisockdata->method,
2377 NULL) < 0 || php_stream_xport_crypto_enable(
2378 xparam->outputs.client, 1) < 0) {
2379 php_error_docref(NULL, E_WARNING, "Failed to enable crypto");
2380
2381 php_stream_close(xparam->outputs.client);
2382 xparam->outputs.client = NULL;
2383 xparam->outputs.returncode = -1;
2384 }
2385 }
2386 }
2387
2388 return xparam->outputs.client == NULL ? -1 : 0;
2389 }
2390 /* }}} */
2391
php_openssl_sockop_set_option(php_stream * stream,int option,int value,void * ptrparam)2392 static int php_openssl_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam) /* {{{ */
2393 {
2394 php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
2395 php_stream_xport_crypto_param *cparam = (php_stream_xport_crypto_param *)ptrparam;
2396 php_stream_xport_param *xparam = (php_stream_xport_param *)ptrparam;
2397
2398 switch (option) {
2399 case PHP_STREAM_OPTION_META_DATA_API:
2400 if (sslsock->ssl_active) {
2401 zval tmp;
2402 char *proto_str;
2403 const SSL_CIPHER *cipher;
2404
2405 array_init(&tmp);
2406
2407 switch (SSL_version(sslsock->ssl_handle)) {
2408 #ifdef HAVE_TLS13
2409 case TLS1_3_VERSION: proto_str = "TLSv1.3"; break;
2410 #endif
2411 #ifdef HAVE_TLS12
2412 case TLS1_2_VERSION: proto_str = "TLSv1.2"; break;
2413 #endif
2414 #ifdef HAVE_TLS11
2415 case TLS1_1_VERSION: proto_str = "TLSv1.1"; break;
2416 #endif
2417 case TLS1_VERSION: proto_str = "TLSv1"; break;
2418 #ifdef HAVE_SSL3
2419 case SSL3_VERSION: proto_str = "SSLv3"; break;
2420 #endif
2421 default: proto_str = "UNKNOWN";
2422 }
2423
2424 cipher = SSL_get_current_cipher(sslsock->ssl_handle);
2425
2426 add_assoc_string(&tmp, "protocol", proto_str);
2427 add_assoc_string(&tmp, "cipher_name", (char *) SSL_CIPHER_get_name(cipher));
2428 add_assoc_long(&tmp, "cipher_bits", SSL_CIPHER_get_bits(cipher, NULL));
2429 add_assoc_string(&tmp, "cipher_version", SSL_CIPHER_get_version(cipher));
2430
2431 #ifdef HAVE_TLS_ALPN
2432 {
2433 const unsigned char *alpn_proto = NULL;
2434 unsigned int alpn_proto_len = 0;
2435
2436 SSL_get0_alpn_selected(sslsock->ssl_handle, &alpn_proto, &alpn_proto_len);
2437 if (alpn_proto) {
2438 add_assoc_stringl(&tmp, "alpn_protocol", (char *)alpn_proto, alpn_proto_len);
2439 }
2440 }
2441 #endif
2442 add_assoc_zval((zval *)ptrparam, "crypto", &tmp);
2443 }
2444
2445 add_assoc_bool((zval *)ptrparam, "timed_out", sslsock->s.timeout_event);
2446 add_assoc_bool((zval *)ptrparam, "blocked", sslsock->s.is_blocked);
2447 add_assoc_bool((zval *)ptrparam, "eof", stream->eof);
2448
2449 return PHP_STREAM_OPTION_RETURN_OK;
2450
2451 case PHP_STREAM_OPTION_CHECK_LIVENESS:
2452 {
2453 struct timeval tv;
2454 char buf;
2455 int alive = 1;
2456
2457 if (value == -1) {
2458 if (sslsock->s.timeout.tv_sec == -1) {
2459 #ifdef _WIN32
2460 tv.tv_sec = (long)FG(default_socket_timeout);
2461 #else
2462 tv.tv_sec = (time_t)FG(default_socket_timeout);
2463 #endif
2464 tv.tv_usec = 0;
2465 } else {
2466 tv = sslsock->connect_timeout;
2467 }
2468 } else {
2469 tv.tv_sec = value;
2470 tv.tv_usec = 0;
2471 }
2472
2473 if (sslsock->s.socket == -1) {
2474 alive = 0;
2475 } else if (
2476 (
2477 !sslsock->ssl_active &&
2478 value == 0 &&
2479 !(stream->flags & PHP_STREAM_FLAG_NO_IO) &&
2480 ((MSG_DONTWAIT != 0) || !sslsock->s.is_blocked)
2481 ) ||
2482 php_pollfd_for(sslsock->s.socket, PHP_POLLREADABLE|POLLPRI, &tv) > 0
2483 ) {
2484 /* the poll() call was skipped if the socket is non-blocking (or MSG_DONTWAIT is available) and if the timeout is zero */
2485 /* additionally, we don't use this optimization if SSL is active because in that case, we're not using MSG_DONTWAIT */
2486 if (sslsock->ssl_active) {
2487 int retry = 1;
2488 struct timeval start_time;
2489 struct timeval *timeout = NULL;
2490 int began_blocked = sslsock->s.is_blocked;
2491 int has_timeout = 0;
2492
2493 /* never use a timeout with non-blocking sockets */
2494 if (began_blocked) {
2495 timeout = &tv;
2496 }
2497
2498 if (timeout && php_set_sock_blocking(sslsock->s.socket, 0) == SUCCESS) {
2499 sslsock->s.is_blocked = 0;
2500 }
2501
2502 if (!sslsock->s.is_blocked && timeout && (timeout->tv_sec > 0 || (timeout->tv_sec == 0 && timeout->tv_usec))) {
2503 has_timeout = 1;
2504 /* gettimeofday is not monotonic; using it here is not strictly correct */
2505 gettimeofday(&start_time, NULL);
2506 }
2507
2508 /* Main IO loop. */
2509 do {
2510 struct timeval cur_time, elapsed_time, left_time;
2511
2512 /* If we have a timeout to check, figure out how much time has elapsed since we started. */
2513 if (has_timeout) {
2514 gettimeofday(&cur_time, NULL);
2515
2516 /* Determine how much time we've taken so far. */
2517 elapsed_time = php_openssl_subtract_timeval(cur_time, start_time);
2518
2519 /* and return an error if we've taken too long. */
2520 if (php_openssl_compare_timeval(elapsed_time, *timeout) > 0 ) {
2521 /* If the socket was originally blocking, set it back. */
2522 if (began_blocked) {
2523 php_set_sock_blocking(sslsock->s.socket, 1);
2524 sslsock->s.is_blocked = 1;
2525 }
2526 sslsock->s.timeout_event = 1;
2527 return PHP_STREAM_OPTION_RETURN_ERR;
2528 }
2529 }
2530
2531 int n = SSL_peek(sslsock->ssl_handle, &buf, sizeof(buf));
2532 /* If we didn't do anything on the last loop (or an error) check to see if we should retry or exit. */
2533 if (n <= 0) {
2534 /* Now, do the IO operation. Don't block if we can't complete... */
2535 int err = SSL_get_error(sslsock->ssl_handle, n);
2536 switch (err) {
2537 case SSL_ERROR_SYSCALL:
2538 retry = php_socket_errno() == EAGAIN;
2539 break;
2540 case SSL_ERROR_WANT_READ:
2541 case SSL_ERROR_WANT_WRITE:
2542 retry = 1;
2543 break;
2544 default:
2545 /* any other problem is a fatal error */
2546 retry = 0;
2547 }
2548
2549 /* Don't loop indefinitely in non-blocking mode if no data is available */
2550 if (began_blocked == 0 || !has_timeout) {
2551 alive = retry;
2552 break;
2553 }
2554
2555 /* Now, if we have to wait some time, and we're supposed to be blocking, wait for the socket to become
2556 * available. Now, php_pollfd_for uses select to wait up to our time_left value only...
2557 */
2558 if (retry) {
2559 /* Now, how much time until we time out? */
2560 left_time = php_openssl_subtract_timeval(*timeout, elapsed_time);
2561 if (php_pollfd_for(sslsock->s.socket, PHP_POLLREADABLE|POLLPRI|POLLOUT, has_timeout ? &left_time : NULL) <= 0) {
2562 retry = 0;
2563 alive = 0;
2564 };
2565 }
2566 } else {
2567 retry = 0;
2568 alive = 1;
2569 }
2570 /* Finally, we keep going until there are any data or there is no time to wait. */
2571 } while (retry);
2572
2573 if (began_blocked && !sslsock->s.is_blocked) {
2574 // Set it back to blocking
2575 php_set_sock_blocking(sslsock->s.socket, 1);
2576 sslsock->s.is_blocked = 1;
2577 }
2578 } else {
2579 #ifdef PHP_WIN32
2580 int ret;
2581 #else
2582 ssize_t ret;
2583 #endif
2584 int err;
2585
2586 ret = recv(sslsock->s.socket, &buf, sizeof(buf), MSG_PEEK|MSG_DONTWAIT);
2587 err = php_socket_errno();
2588 if (0 == ret || /* the counterpart did properly shutdown */
2589 (0 > ret && err != EWOULDBLOCK && err != EAGAIN && err != EMSGSIZE)) { /* there was an unrecoverable error */
2590 alive = 0;
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