PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - ext/openssl - xp_ssl.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 769 982 78.3 %
Date: 2016-09-27 Functions: 44 45 97.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Tue, 27 Sep 2016 10:26:03 +0000 (20 hours ago)

Copyright © 2005-2016 The PHP Group
All rights reserved.