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: 654 891 73.4 %
Date: 2014-07-21 Functions: 37 39 94.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Tue, 22 Jul 2014 01:33:14 +0000 (9 days ago)

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