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