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: 660 919 71.8 %
Date: 2015-01-26 Functions: 40 44 90.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Mon, 26 Jan 2015 14:46:49 +0000 (3 days ago)

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