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: 650 891 73.0 %
Date: 2014-04-16 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          44 : static int is_http_stream_talking_to_iis(php_stream *stream TSRMLS_DC) /* {{{ */
     123             : {
     124          44 :         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          44 :         return 0;
     144             : }
     145             : /* }}} */
     146             : 
     147         146 : static int handle_ssl_error(php_stream *stream, int nr_bytes, zend_bool is_init TSRMLS_DC) /* {{{ */
     148             : {
     149         146 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
     150         146 :         int err = SSL_get_error(sslsock->ssl_handle, nr_bytes);
     151             :         char esbuf[512];
     152         146 :         smart_str ebuf = {0};
     153             :         unsigned long ecode;
     154         146 :         int retry = 1;
     155             : 
     156         146 :         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          92 :                         errno = EAGAIN;
     166          92 :                         retry = is_init ? 1 : sslsock->s.is_blocked;
     167          92 :                         break;
     168             :                 case SSL_ERROR_SYSCALL:
     169          44 :                         if (ERR_peek_error() == 0) {
     170          44 :                                 if (nr_bytes == 0) {
     171          44 :                                         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          44 :                                         SSL_set_shutdown(sslsock->ssl_handle, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
     176          44 :                                         stream->eof = 1;
     177          44 :                                         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          44 :                                 break;
     188             :                         }
     189             : 
     190             :                         
     191             :                         /* fall through */
     192             :                 default:
     193             :                         /* some other error */
     194           4 :                         ecode = ERR_get_error();
     195             : 
     196           4 :                         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           4 :                                                 ERR_error_string_n(ecode, esbuf, sizeof(esbuf));
     206           4 :                                                 if (ebuf.c) {
     207           0 :                                                         smart_str_appendc(&ebuf, '\n');
     208             :                                                 }
     209           4 :                                                 smart_str_appends(&ebuf, esbuf);
     210           4 :                                         } while ((ecode = ERR_get_error()) != 0);
     211             : 
     212           4 :                                         smart_str_0(&ebuf);
     213             : 
     214           8 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING,
     215             :                                                         "SSL operation failed with code %d. %s%s",
     216             :                                                         err,
     217           4 :                                                         ebuf.c ? "OpenSSL Error messages:\n" : "",
     218           4 :                                                         ebuf.c ? ebuf.c : "");
     219           4 :                                         if (ebuf.c) {
     220           4 :                                                 smart_str_free(&ebuf);
     221             :                                         }
     222             :                         }
     223             :                                 
     224           4 :                         retry = 0;
     225           4 :                         errno = 0;
     226             :         }
     227         146 :         return retry;
     228             : }
     229             : /* }}} */
     230             : 
     231           6 : 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           6 :         unsigned long allowed_depth = OPENSSL_DEFAULT_STREAM_VERIFY_DEPTH;
     238             : 
     239             :         TSRMLS_FETCH();
     240             : 
     241           6 :         ret = preverify_ok;
     242             : 
     243             :         /* determine the status for the current cert */
     244           6 :         err = X509_STORE_CTX_get_error(ctx);
     245           6 :         depth = X509_STORE_CTX_get_error_depth(ctx);
     246             : 
     247             :         /* conjure the stream & context to use */
     248           6 :         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
     249           6 :         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           6 :         if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
     253           0 :                 GET_VER_OPT("allow_self_signed") &&
     254             :                 zend_is_true(*val TSRMLS_CC)
     255           0 :         ) {
     256           0 :                 ret = 1;
     257             :         }
     258             : 
     259             :         /* check the depth */
     260           6 :         GET_VER_OPT_LONG("verify_depth", allowed_depth);
     261           6 :         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           6 :         return ret;
     267             : }
     268             : /* }}} */
     269             : 
     270          10 : static zend_bool matches_wildcard_name(const char *subjectname, const char *certname) /* {{{ */
     271             : {
     272          10 :         char *wildcard = NULL;
     273             :         int prefix_len, suffix_len, subject_len;
     274             : 
     275          10 :         if (strcasecmp(subjectname, certname) == 0) {
     276           6 :                 return 1;
     277             :         }
     278             : 
     279           4 :         if (!(wildcard = strchr(certname, '*'))) {
     280           3 :                 return 0;
     281             :         }
     282             : 
     283             :         // 1) prefix, if not empty, must match subject
     284           1 :         prefix_len = wildcard - certname;
     285           1 :         if (prefix_len && strncasecmp(subjectname, certname, prefix_len) != 0) {
     286           0 :                 return 0;
     287             :         }
     288             : 
     289           1 :         suffix_len = strlen(wildcard + 1);
     290           1 :         subject_len = strlen(subjectname);
     291           1 :         if (suffix_len <= subject_len) {
     292             :                 /* 2) suffix must match
     293             :                  * 3) no . between prefix and suffix
     294             :                  **/
     295           2 :                 return strcasecmp(wildcard + 1, subjectname + subject_len - suffix_len) == 0 &&
     296           1 :                         memchr(subjectname + prefix_len, '.', subject_len - suffix_len - prefix_len) == NULL;
     297             :         }
     298             : 
     299           0 :         return 0;
     300             : }
     301             : /* }}} */
     302             : 
     303           9 : static zend_bool matches_san_list(X509 *peer, const char *subject_name TSRMLS_DC) /* {{{ */
     304             : {
     305             :         int i, san_name_len;
     306           9 :         zend_bool is_match = 0;
     307           9 :         unsigned char *cert_name = NULL;
     308             : 
     309           9 :         GENERAL_NAMES *alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, 0, 0);
     310           9 :         int alt_name_count = sk_GENERAL_NAME_num(alt_names);
     311             : 
     312          11 :         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           9 :         return is_match;
     337             : }
     338             : /* }}} */
     339             : 
     340           4 : 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           4 :         zend_bool is_match = 0;
     345             :         int cert_name_len;
     346             : 
     347           4 :         cert_name = X509_get_subject_name(peer);
     348           4 :         cert_name_len = X509_NAME_get_text_by_NID(cert_name, NID_commonName, buf, sizeof(buf));
     349             : 
     350           4 :         if (cert_name_len == -1) {
     351           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate peer certificate CN");
     352           4 :         } 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           4 :         } else if (matches_wildcard_name(subject_name, buf)) {
     355           4 :                 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           4 :         return is_match;
     361             : }
     362             : /* }}} */
     363             : 
     364          25 : static int apply_peer_verification_policy(SSL *ssl, X509 *peer, php_stream *stream TSRMLS_DC) /* {{{ */
     365             : {
     366          25 :         zval **val = NULL;
     367          25 :         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          25 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
     375             : 
     376          40 :         must_verify_peer = GET_VER_OPT("verify_peer")
     377          15 :                 ? zend_is_true(*val TSRMLS_CC)
     378             :                 : sslsock->is_client;
     379             : 
     380          25 :         has_cnmatch_ctx_opt = GET_VER_OPT("CN_match");
     381          34 :         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          25 :         must_verify_fingerprint = (GET_VER_OPT("peer_fingerprint") && zend_is_true(*val TSRMLS_CC));
     386             : 
     387          25 :         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          25 :         if (must_verify_peer) {
     394           3 :                 err = SSL_get_verify_result(ssl);
     395           3 :                 switch (err) {
     396             :                         case X509_V_OK:
     397             :                                 /* fine */
     398           3 :                                 break;
     399             :                         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
     400           0 :                                 if (GET_VER_OPT("allow_self_signed") && zend_is_true(*val TSRMLS_CC)) {
     401             :                                         /* allowed */
     402           0 :                                         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          25 :         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          25 :         if (must_verify_peer_name) {
     433           9 :                 GET_VER_OPT_STRING("peer_name", peer_name);
     434             : 
     435           9 :                 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           9 :                 if (peer_name == NULL && sslsock->is_client) {
     443           0 :                         peer_name = sslsock->url_name;
     444             :                 }
     445             : 
     446           9 :                 if (peer_name) {
     447           9 :                         if (matches_san_list(peer, peer_name TSRMLS_CC)) {
     448           5 :                                 return SUCCESS;
     449           4 :                         } else if (matches_common_name(peer, peer_name TSRMLS_CC)) {
     450           4 :                                 return SUCCESS;
     451             :                         } else {
     452           0 :                                 return FAILURE;
     453             :                         }
     454             :                 } else {
     455           0 :                         return FAILURE;
     456             :                 }
     457             :         }
     458             : 
     459          16 :         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         561 : static void info_callback(const SSL *ssl, int where, int ret) /* {{{ */
     979             : {
     980             :         /* Rate-limit client-initiated handshake renegotiation to prevent DoS */
     981         561 :         if (where & SSL_CB_HANDSHAKE_START) {
     982          56 :                 limit_handshake_reneg(ssl);
     983             :         }
     984         561 : }
     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          55 :         if (SUCCESS == php_stream_context_get_option(
    1170          55 :                                 stream->context, "ssl", "single_ecdh_use", &val) &&
    1171             :                         zend_is_true(*val TSRMLS_CC)
    1172           0 :         ) {
    1173           0 :                 ssl_ctx_options |= SSL_OP_SINGLE_ECDH_USE;
    1174             :         }
    1175             : 
    1176          55 :         SSL_CTX_set_options(ctx, ssl_ctx_options);
    1177             : 
    1178          55 :         return SUCCESS;
    1179             : }
    1180             : /* }}} */
    1181             : 
    1182             : #ifdef HAVE_SNI
    1183           3 : static int server_sni_callback(SSL *ssl_handle, int *al, void *arg) /* {{{ */
    1184             : {
    1185             :         php_stream *stream;
    1186             :         php_openssl_netstream_data_t *sslsock;
    1187             :         unsigned i;
    1188             :         const char *server_name;
    1189             : 
    1190           3 :         server_name = SSL_get_servername(ssl_handle, TLSEXT_NAMETYPE_host_name);
    1191             : 
    1192           3 :         if (!server_name) {
    1193           0 :                 return SSL_TLSEXT_ERR_NOACK;
    1194             :         }
    1195             : 
    1196           3 :         stream = (php_stream*)SSL_get_ex_data(ssl_handle, php_openssl_get_ssl_stream_data_index());
    1197           3 :         sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    1198             : 
    1199           3 :         if (!(sslsock->sni_cert_count && sslsock->sni_certs)) {
    1200           0 :                 return SSL_TLSEXT_ERR_NOACK;
    1201             :         }
    1202             : 
    1203           6 :         for (i=0; i < sslsock->sni_cert_count; i++) {
    1204           6 :                 if (matches_wildcard_name(server_name, sslsock->sni_certs[i].name)) {
    1205           3 :                         SSL_set_SSL_CTX(ssl_handle, sslsock->sni_certs[i].ctx);
    1206           3 :                         return SSL_TLSEXT_ERR_OK;
    1207             :                 }
    1208             :         }
    1209             : 
    1210           0 :         return SSL_TLSEXT_ERR_NOACK;
    1211             : }
    1212             : /* }}} */
    1213             : 
    1214          55 : static int enable_server_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock TSRMLS_DC)
    1215             : {
    1216             :         zval **val;
    1217             :         zval **current;
    1218             :         char *key;
    1219             :         uint key_len;
    1220             :         ulong key_index;
    1221             :         int key_type;
    1222             :         HashPosition pos;
    1223          55 :         int i = 0;
    1224             :         char resolved_path_buff[MAXPATHLEN];
    1225             :         SSL_CTX *ctx;
    1226             : 
    1227             :         /* If the stream ctx disables SNI we're finished here */
    1228          55 :         if (GET_VER_OPT("SNI_enabled") && !zend_is_true(*val TSRMLS_CC)) {
    1229           0 :                 return SUCCESS;
    1230             :         }
    1231             : 
    1232             :         /* If no SNI cert array is specified we're finished here */
    1233          55 :         if (!GET_VER_OPT("SNI_server_certs")) {
    1234          52 :                 return SUCCESS;
    1235             :         }
    1236             : 
    1237           3 :         if (Z_TYPE_PP(val) != IS_ARRAY) {
    1238           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1239             :                         "SNI_server_certs requires an array mapping host names to cert paths"
    1240             :                 );
    1241           0 :                 return FAILURE;
    1242             :         }
    1243             : 
    1244           3 :         sslsock->sni_cert_count = zend_hash_num_elements(Z_ARRVAL_PP(val));
    1245           3 :         if (sslsock->sni_cert_count == 0) {
    1246           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1247             :                         "SNI_server_certs host cert array must not be empty"
    1248             :                 );
    1249           0 :                 return FAILURE;
    1250             :         }
    1251             : 
    1252           3 :         sslsock->sni_certs = (php_openssl_sni_cert_t*)safe_pemalloc(sslsock->sni_cert_count,
    1253             :                 sizeof(php_openssl_sni_cert_t), 0, php_stream_is_persistent(stream)
    1254             :         );
    1255             : 
    1256          15 :         for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(val), &pos);
    1257          12 :                 zend_hash_get_current_data_ex(Z_ARRVAL_PP(val), (void **)&current, &pos) == SUCCESS;
    1258           9 :                 zend_hash_move_forward_ex(Z_ARRVAL_PP(val), &pos)
    1259           9 :         ) {
    1260           9 :                 key_type = zend_hash_get_current_key_ex(Z_ARRVAL_PP(val), &key, &key_len, &key_index, 0, &pos);
    1261           9 :                 if (key_type != HASH_KEY_IS_STRING) {
    1262           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1263             :                                 "SNI_server_certs array requires string host name keys"
    1264             :                         );
    1265           0 :                         return FAILURE;
    1266             :                 }
    1267             : 
    1268           9 :                 if (VCWD_REALPATH(Z_STRVAL_PP(current), resolved_path_buff)) {
    1269             :                         /* The hello method is not inherited by SSL structs when assigning a new context
    1270             :                          * inside the SNI callback, so the just use SSLv23 */
    1271           9 :                         ctx = SSL_CTX_new(SSLv23_server_method());
    1272             : 
    1273           9 :                         if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
    1274           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1275             :                                         "failed setting local cert chain file `%s'; " \
    1276             :                                         "check that your cafile/capath settings include " \
    1277             :                                         "details of your certificate and its issuer",
    1278             :                                         resolved_path_buff
    1279             :                                 );
    1280           0 :                                 SSL_CTX_free(ctx);
    1281           0 :                                 return FAILURE;
    1282           9 :                         } else if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
    1283           0 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1284             :                                         "failed setting private key from file `%s'",
    1285             :                                         resolved_path_buff
    1286             :                                 );
    1287           0 :                                 SSL_CTX_free(ctx);
    1288           0 :                                 return FAILURE;
    1289             :                         } else {
    1290           9 :                                 sslsock->sni_certs[i].name = pestrdup(key, php_stream_is_persistent(stream));
    1291           9 :                                 sslsock->sni_certs[i].ctx = ctx;
    1292           9 :                                 ++i;
    1293             :                         }
    1294             :                 } else {
    1295           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING,
    1296             :                                 "failed setting local cert chain file `%s'; file not found",
    1297           0 :                                 Z_STRVAL_PP(current)
    1298             :                         );
    1299           0 :                         return FAILURE;
    1300             :                 }
    1301             :         }
    1302             : 
    1303           3 :         SSL_CTX_set_tlsext_servername_callback(sslsock->ctx, server_sni_callback);
    1304             : 
    1305           3 :         return SUCCESS;
    1306             : }
    1307             : 
    1308          67 : static void enable_client_sni(php_stream *stream, php_openssl_netstream_data_t *sslsock TSRMLS_DC) /* {{{ */
    1309             : {
    1310             :         zval **val;
    1311             :         char *sni_server_name;
    1312             : 
    1313             :         /* If SNI is explicitly disabled we're finished here */
    1314          67 :         if (GET_VER_OPT("SNI_enabled") && !zend_is_true(*val TSRMLS_CC)) {
    1315           3 :                 return;
    1316             :         }
    1317             : 
    1318          64 :         sni_server_name = sslsock->url_name;
    1319             : 
    1320          64 :         GET_VER_OPT_STRING("peer_name", sni_server_name);
    1321             : 
    1322          64 :         if (GET_VER_OPT("SNI_server_name")) {
    1323           0 :                 GET_VER_OPT_STRING("SNI_server_name", sni_server_name);
    1324           0 :                 php_error(E_DEPRECATED, "SNI_server_name is deprecated in favor of peer_name");
    1325             :         }
    1326             : 
    1327          64 :         if (sni_server_name) {
    1328          64 :                 SSL_set_tlsext_host_name(sslsock->ssl_handle, sni_server_name);
    1329             :         }
    1330             : }
    1331             : /* }}} */
    1332             : #endif
    1333             : 
    1334         123 : int php_openssl_setup_crypto(php_stream *stream,
    1335             :                 php_openssl_netstream_data_t *sslsock,
    1336             :                 php_stream_xport_crypto_param *cparam
    1337             :                 TSRMLS_DC) /* {{{ */
    1338             : {
    1339             :         const SSL_METHOD *method;
    1340             :         long ssl_ctx_options;
    1341             :         long method_flags;
    1342         123 :         char *cipherlist = NULL;
    1343             :         zval **val;
    1344             : 
    1345         123 :         if (sslsock->ssl_handle) {
    1346           0 :                 if (sslsock->s.is_blocked) {
    1347           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL/TLS already set-up for this stream");
    1348           0 :                         return FAILURE;
    1349             :                 } else {
    1350           0 :                         return SUCCESS;
    1351             :                 }
    1352             :         }
    1353             : 
    1354         123 :         ERR_clear_error();
    1355             : 
    1356             :         /* We need to do slightly different things based on client/server method
    1357             :          * so lets remember which method was selected */
    1358         123 :         sslsock->is_client = cparam->inputs.method & STREAM_CRYPTO_IS_CLIENT;
    1359         123 :         method_flags = ((cparam->inputs.method >> 1) << 1);
    1360             : 
    1361             :         /* Should we use a specific crypto method or is generic SSLv23 okay? */
    1362         123 :         if ((method_flags & (method_flags-1)) == 0) {
    1363          39 :                 ssl_ctx_options = SSL_OP_ALL;
    1364          39 :                 method = php_select_crypto_method(method_flags, sslsock->is_client TSRMLS_CC);
    1365          39 :                 if (method == NULL) {
    1366           0 :                         return FAILURE;
    1367             :                 }
    1368             :         } else {
    1369          84 :                 method = sslsock->is_client ? SSLv23_client_method() : SSLv23_server_method();
    1370          84 :                 ssl_ctx_options = php_get_crypto_method_ctx_flags(method_flags TSRMLS_CC);
    1371          84 :                 if (ssl_ctx_options == -1) {
    1372           0 :                         return FAILURE;
    1373             :                 }
    1374             :         }
    1375             : 
    1376             : #if OPENSSL_VERSION_NUMBER >= 0x10001001L
    1377         123 :         sslsock->ctx = SSL_CTX_new(method);
    1378             : #else
    1379             :         /* Avoid const warning with old versions */
    1380             :         sslsock->ctx = SSL_CTX_new((SSL_METHOD*)method);
    1381             : #endif
    1382             : 
    1383         123 :         if (sslsock->ctx == NULL) {
    1384           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL context creation failure");
    1385           0 :                 return FAILURE;
    1386             :         }
    1387             : 
    1388             : #if OPENSSL_VERSION_NUMBER >= 0x0090806fL
    1389         123 :         if (GET_VER_OPT("no_ticket") && zend_is_true(*val TSRMLS_CC)) {
    1390           0 :                 ssl_ctx_options |= SSL_OP_NO_TICKET;
    1391             :         }
    1392             : #endif
    1393             : 
    1394             : #if OPENSSL_VERSION_NUMBER >= 0x0090605fL
    1395         123 :         ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
    1396             : #endif
    1397             : 
    1398             : #if OPENSSL_VERSION_NUMBER >= 0x10000000L
    1399         123 :         if (!GET_VER_OPT("disable_compression") || zend_is_true(*val TSRMLS_CC)) {
    1400         123 :                 ssl_ctx_options |= SSL_OP_NO_COMPRESSION;
    1401             :         }
    1402             : #endif
    1403             : 
    1404         152 :         if (GET_VER_OPT("verify_peer") && !zend_is_true(*val TSRMLS_CC)) {
    1405          29 :                 disable_peer_verification(sslsock->ctx, stream TSRMLS_CC);
    1406          94 :         } else if (FAILURE == enable_peer_verification(sslsock->ctx, stream TSRMLS_CC)) {
    1407           1 :                 return FAILURE;
    1408             :         }
    1409             : 
    1410             :         /* callback for the passphrase (for localcert) */
    1411         122 :         if (GET_VER_OPT("passphrase")) {
    1412           1 :                 SSL_CTX_set_default_passwd_cb_userdata(sslsock->ctx, stream);
    1413           1 :                 SSL_CTX_set_default_passwd_cb(sslsock->ctx, passwd_callback);
    1414             :         }
    1415             : 
    1416         122 :         GET_VER_OPT_STRING("ciphers", cipherlist);
    1417         122 :         if (!cipherlist) {
    1418         122 :                 cipherlist = OPENSSL_DEFAULT_STREAM_CIPHERS;
    1419             :         }
    1420         122 :         if (SSL_CTX_set_cipher_list(sslsock->ctx, cipherlist) != 1) {
    1421           0 :                 return FAILURE;
    1422             :         }
    1423             : 
    1424         122 :         if (FAILURE == set_local_cert(sslsock->ctx, stream TSRMLS_CC)) {
    1425           0 :                 return FAILURE;
    1426             :         }
    1427             : 
    1428         122 :         SSL_CTX_set_options(sslsock->ctx, ssl_ctx_options);
    1429             : 
    1430         232 :         if (sslsock->is_client == 0 &&
    1431          55 :                 stream->context &&
    1432          55 :                 FAILURE == set_server_specific_opts(stream, sslsock->ctx TSRMLS_CC)
    1433             :         ) {
    1434           0 :                 return FAILURE;
    1435             :         }
    1436             : 
    1437         122 :         sslsock->ssl_handle = SSL_new(sslsock->ctx);
    1438         122 :         if (sslsock->ssl_handle == NULL) {
    1439           0 :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL handle creation failure");
    1440           0 :                 SSL_CTX_free(sslsock->ctx);
    1441           0 :                 sslsock->ctx = NULL;
    1442           0 :                 return FAILURE;
    1443             :         } else {
    1444         122 :                 SSL_set_ex_data(sslsock->ssl_handle, php_openssl_get_ssl_stream_data_index(), stream);
    1445             :         }
    1446             : 
    1447         122 :         if (!SSL_set_fd(sslsock->ssl_handle, sslsock->s.socket)) {
    1448           0 :                 handle_ssl_error(stream, 0, 1 TSRMLS_CC);
    1449             :         }
    1450             : 
    1451             : #ifdef HAVE_SNI
    1452             :         /* Enable server-side SNI */
    1453         122 :         if (sslsock->is_client == 0 && enable_server_sni(stream, sslsock TSRMLS_CC) == FAILURE) {
    1454           0 :                 return FAILURE;
    1455             :         }
    1456             : #endif
    1457             : 
    1458             :         /* Enable server-side handshake renegotiation rate-limiting */
    1459         122 :         if (sslsock->is_client == 0) {
    1460          55 :                 init_server_reneg_limit(stream, sslsock);
    1461             :         }
    1462             : 
    1463             : #ifdef SSL_MODE_RELEASE_BUFFERS
    1464             :         do {
    1465         122 :                 long mode = SSL_get_mode(sslsock->ssl_handle);
    1466         122 :                 SSL_set_mode(sslsock->ssl_handle, mode | SSL_MODE_RELEASE_BUFFERS);
    1467             :         } while (0);
    1468             : #endif
    1469             : 
    1470         122 :         if (cparam->inputs.session) {
    1471           0 :                 if (cparam->inputs.session->ops != &php_openssl_socket_ops) {
    1472           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied session stream must be an SSL enabled stream");
    1473           0 :                 } else if (((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle == NULL) {
    1474           0 :                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied SSL session stream is not initialized");
    1475             :                 } else {
    1476           0 :                         SSL_copy_session_id(sslsock->ssl_handle, ((php_openssl_netstream_data_t*)cparam->inputs.session->abstract)->ssl_handle);
    1477             :                 }
    1478             :         }
    1479             : 
    1480         122 :         return SUCCESS;
    1481             : }
    1482             : /* }}} */
    1483             : 
    1484           0 : static zval *capture_session_meta(SSL *ssl_handle) /* {{{ */
    1485             : {
    1486             :         zval *meta_arr;
    1487             :         char *proto_str;
    1488           0 :         long proto = SSL_version(ssl_handle);
    1489           0 :         const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl_handle);
    1490             : 
    1491           0 :         switch (proto) {
    1492             : #if OPENSSL_VERSION_NUMBER >= 0x10001001L
    1493           0 :                 case TLS1_2_VERSION: proto_str = "TLSv1.2"; break;
    1494           0 :                 case TLS1_1_VERSION: proto_str = "TLSv1.1"; break;
    1495             : #endif
    1496           0 :                 case TLS1_VERSION: proto_str = "TLSv1"; break;
    1497           0 :                 case SSL3_VERSION: proto_str = "SSLv3"; break;
    1498           0 :                 case SSL2_VERSION: proto_str = "SSLv2"; break;
    1499           0 :                 default: proto_str = "UNKNOWN";
    1500             :         }
    1501             : 
    1502           0 :         MAKE_STD_ZVAL(meta_arr);
    1503           0 :         array_init(meta_arr);
    1504           0 :         add_assoc_string(meta_arr, "protocol", proto_str, 1);
    1505           0 :         add_assoc_string(meta_arr, "cipher_name", (char *) SSL_CIPHER_get_name(cipher), 1);
    1506           0 :         add_assoc_long(meta_arr, "cipher_bits", SSL_CIPHER_get_bits(cipher, NULL));
    1507           0 :         add_assoc_string(meta_arr, "cipher_version", SSL_CIPHER_get_version(cipher), 1);
    1508             : 
    1509           0 :         return meta_arr;
    1510             : }
    1511             : /* }}} */
    1512             : 
    1513          18 : static int capture_peer_certs(php_stream *stream, php_openssl_netstream_data_t *sslsock, X509 *peer_cert TSRMLS_DC) /* {{{ */
    1514             : {
    1515             :         zval **val, *zcert;
    1516          18 :         int cert_captured = 0;
    1517             : 
    1518          32 :         if (SUCCESS == php_stream_context_get_option(stream->context,
    1519          18 :                         "ssl", "capture_peer_cert", &val) &&
    1520             :                 zend_is_true(*val TSRMLS_CC)
    1521          14 :         ) {
    1522          14 :                 MAKE_STD_ZVAL(zcert);
    1523          14 :                 ZVAL_RESOURCE(zcert, zend_list_insert(peer_cert, php_openssl_get_x509_list_id() TSRMLS_CC));
    1524          14 :                 php_stream_context_set_option(stream->context, "ssl", "peer_certificate", zcert);
    1525          14 :                 cert_captured = 1;
    1526          14 :                 FREE_ZVAL(zcert);
    1527             :         }
    1528             : 
    1529          18 :         if (SUCCESS == php_stream_context_get_option(stream->context,
    1530          18 :                         "ssl", "capture_peer_cert_chain", &val) &&
    1531             :                 zend_is_true(*val TSRMLS_CC)
    1532           0 :         ) {
    1533             :                 zval *arr;
    1534             :                 STACK_OF(X509) *chain;
    1535             : 
    1536           0 :                 MAKE_STD_ZVAL(arr);
    1537           0 :                 chain = SSL_get_peer_cert_chain(sslsock->ssl_handle);
    1538             : 
    1539           0 :                 if (chain && sk_X509_num(chain) > 0) {
    1540             :                         int i;
    1541           0 :                         array_init(arr);
    1542             : 
    1543           0 :                         for (i = 0; i < sk_X509_num(chain); i++) {
    1544           0 :                                 X509 *mycert = X509_dup(sk_X509_value(chain, i));
    1545           0 :                                 MAKE_STD_ZVAL(zcert);
    1546           0 :                                 ZVAL_RESOURCE(zcert, zend_list_insert(mycert, php_openssl_get_x509_list_id() TSRMLS_CC));
    1547           0 :                                 add_next_index_zval(arr, zcert);
    1548             :                         }
    1549             : 
    1550             :                 } else {
    1551           0 :                         ZVAL_NULL(arr);
    1552             :                 }
    1553             : 
    1554           0 :                 php_stream_context_set_option(stream->context, "ssl", "peer_certificate_chain", arr);
    1555             :                 zval_dtor(arr);
    1556           0 :                 efree(arr);
    1557             :         }
    1558             : 
    1559          18 :         return cert_captured;
    1560             : }
    1561             : /* }}} */
    1562             : 
    1563         122 : static int php_openssl_enable_crypto(php_stream *stream,
    1564             :                 php_openssl_netstream_data_t *sslsock,
    1565             :                 php_stream_xport_crypto_param *cparam
    1566             :                 TSRMLS_DC)
    1567             : {
    1568             :         int n;
    1569         122 :         int retry = 1;
    1570             :         int cert_captured;
    1571             :         X509 *peer_cert;
    1572             : 
    1573         122 :         if (cparam->inputs.activate && !sslsock->ssl_active) {
    1574             :                 struct timeval  start_time,
    1575             :                                                 *timeout;
    1576         122 :                 int                             blocked         = sslsock->s.is_blocked,
    1577         122 :                                                 has_timeout = 0;
    1578             : 
    1579             : #ifdef HAVE_SNI
    1580         122 :                 if (sslsock->is_client) {
    1581          67 :                         enable_client_sni(stream, sslsock TSRMLS_CC);
    1582             :                 }
    1583             : #endif
    1584             : 
    1585         122 :                 if (!sslsock->state_set) {
    1586         122 :                         if (sslsock->is_client) {
    1587          67 :                                 SSL_set_connect_state(sslsock->ssl_handle);
    1588             :                         } else {
    1589          55 :                                 SSL_set_accept_state(sslsock->ssl_handle);
    1590             :                         }
    1591         122 :                         sslsock->state_set = 1;
    1592             :                 }
    1593             : 
    1594         122 :                 if (SUCCESS == php_set_sock_blocking(sslsock->s.socket, 0 TSRMLS_CC)) {
    1595         122 :                         sslsock->s.is_blocked = 0;
    1596             :                 }
    1597             :                 
    1598         122 :                 timeout = sslsock->is_client ? &sslsock->connect_timeout : &sslsock->s.timeout;
    1599         122 :                 has_timeout = !sslsock->s.is_blocked && (timeout->tv_sec || timeout->tv_usec);
    1600             :                 /* gettimeofday is not monotonic; using it here is not strictly correct */
    1601         122 :                 if (has_timeout) {
    1602         122 :                         gettimeofday(&start_time, NULL);
    1603             :                 }
    1604             :                 
    1605             :                 do {
    1606             :                         struct timeval  cur_time,
    1607         214 :                                                         elapsed_time = {0};
    1608             :                         
    1609         214 :                         if (sslsock->is_client) {
    1610         152 :                                 n = SSL_connect(sslsock->ssl_handle);
    1611             :                         } else {
    1612          62 :                                 n = SSL_accept(sslsock->ssl_handle);
    1613             :                         }
    1614             : 
    1615         214 :                         if (has_timeout) {
    1616         214 :                                 gettimeofday(&cur_time, NULL);
    1617         214 :                                 elapsed_time.tv_sec  = cur_time.tv_sec  - start_time.tv_sec;
    1618         214 :                                 elapsed_time.tv_usec = cur_time.tv_usec - start_time.tv_usec;
    1619         214 :                                 if (cur_time.tv_usec < start_time.tv_usec) {
    1620          29 :                                         elapsed_time.tv_sec  -= 1L;
    1621          29 :                                         elapsed_time.tv_usec += 1000000L;
    1622             :                                 }
    1623             :                         
    1624         477 :                                 if (elapsed_time.tv_sec > timeout->tv_sec ||
    1625         214 :                                                 (elapsed_time.tv_sec == timeout->tv_sec &&
    1626          49 :                                                 elapsed_time.tv_usec > timeout->tv_usec)) {
    1627          49 :                                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSL: Handshake timed out");
    1628          49 :                                         return -1;
    1629             :                                 }
    1630             :                         }
    1631             : 
    1632         165 :                         if (n <= 0) {
    1633             :                                 /* in case of SSL_ERROR_WANT_READ/WRITE, do not retry in non-blocking mode */
    1634         140 :                                 retry = handle_ssl_error(stream, n, blocked TSRMLS_CC);
    1635         140 :                                 if (retry) {
    1636             :                                         /* wait until something interesting happens in the socket. It may be a
    1637             :                                          * timeout. Also consider the unlikely of possibility of a write block  */
    1638          92 :                                         int err = SSL_get_error(sslsock->ssl_handle, n);
    1639             :                                         struct timeval left_time;
    1640             :                                         
    1641          92 :                                         if (has_timeout) {
    1642          92 :                                                 left_time.tv_sec  = timeout->tv_sec  - elapsed_time.tv_sec;
    1643          92 :                                                 left_time.tv_usec =     timeout->tv_usec - elapsed_time.tv_usec;
    1644          92 :                                                 if (timeout->tv_usec < elapsed_time.tv_usec) {
    1645          92 :                                                         left_time.tv_sec  -= 1L;
    1646          92 :                                                         left_time.tv_usec += 1000000L;
    1647             :                                                 }
    1648             :                                         }
    1649          92 :                                         php_pollfd_for(sslsock->s.socket, (err == SSL_ERROR_WANT_READ) ?
    1650             :                                                 (POLLIN|POLLPRI) : POLLOUT, has_timeout ? &left_time : NULL);
    1651             :                                 }
    1652             :                         } else {
    1653          25 :                                 retry = 0;
    1654             :                         }
    1655         165 :                 } while (retry);
    1656             : 
    1657          73 :                 if (sslsock->s.is_blocked != blocked && SUCCESS == php_set_sock_blocking(sslsock->s.socket, blocked TSRMLS_CC)) {
    1658          73 :                         sslsock->s.is_blocked = blocked;
    1659             :                 }
    1660             : 
    1661          73 :                 if (n == 1) {
    1662          25 :                         peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
    1663          25 :                         if (peer_cert && stream->context) {
    1664          18 :                                 cert_captured = capture_peer_certs(stream, sslsock, peer_cert TSRMLS_CC);
    1665             :                         }
    1666             : 
    1667          25 :                         if (FAILURE == apply_peer_verification_policy(sslsock->ssl_handle, peer_cert, stream TSRMLS_CC)) {
    1668           0 :                                 SSL_shutdown(sslsock->ssl_handle);
    1669           0 :                                 n = -1;
    1670             :                         } else {        
    1671          25 :                                 sslsock->ssl_active = 1;
    1672             : 
    1673          25 :                                 if (stream->context) {
    1674             :                                         zval **val;
    1675             : 
    1676          25 :                                         if (SUCCESS == php_stream_context_get_option(stream->context,
    1677          25 :                                                         "ssl", "capture_session_meta", &val) &&
    1678             :                                                 zend_is_true(*val TSRMLS_CC)
    1679           0 :                                         ) {
    1680           0 :                                                 zval *meta_arr = capture_session_meta(sslsock->ssl_handle);
    1681           0 :                                                 php_stream_context_set_option(stream->context, "ssl", "session_meta", meta_arr);
    1682             :                                                 zval_dtor(meta_arr);
    1683           0 :                                                 efree(meta_arr);
    1684             :                                         }
    1685             :                                 }
    1686             :                         }
    1687          48 :                 } else if (errno == EAGAIN) {
    1688           0 :                         n = 0;
    1689             :                 } else {
    1690          48 :                         n = -1;
    1691          48 :                         peer_cert = SSL_get_peer_certificate(sslsock->ssl_handle);
    1692          48 :                         if (peer_cert && stream->context) {
    1693           0 :                                 cert_captured = capture_peer_certs(stream, sslsock, peer_cert TSRMLS_CC);
    1694             :                         }
    1695             :                 }
    1696             : 
    1697          73 :                 if (n && peer_cert && cert_captured == 0) {
    1698           4 :                         X509_free(peer_cert);
    1699             :                 }
    1700             : 
    1701          73 :                 return n;
    1702             : 
    1703           0 :         } else if (!cparam->inputs.activate && sslsock->ssl_active) {
    1704             :                 /* deactivate - common for server/client */
    1705           0 :                 SSL_shutdown(sslsock->ssl_handle);
    1706           0 :                 sslsock->ssl_active = 0;
    1707             :         }
    1708             : 
    1709           0 :         return -1;
    1710             : }
    1711             : 
    1712         635 : static size_t php_openssl_sockop_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC) /* {{{ */
    1713             : {
    1714         635 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    1715             :         int didwrite;
    1716             :         
    1717         635 :         if (sslsock->ssl_active) {
    1718          39 :                 int retry = 1;
    1719             : 
    1720             :                 do {
    1721          39 :                         didwrite = SSL_write(sslsock->ssl_handle, buf, count);
    1722             : 
    1723          39 :                         if (didwrite <= 0) {
    1724           0 :                                 retry = handle_ssl_error(stream, didwrite, 0 TSRMLS_CC);
    1725             :                         } else {
    1726          39 :                                 break;
    1727             :                         }
    1728           0 :                 } while(retry);
    1729             : 
    1730          39 :                 if (didwrite > 0) {
    1731          39 :                         php_stream_notify_progress_increment(stream->context, didwrite, 0);
    1732             :                 }
    1733             :         } else {
    1734         596 :                 didwrite = php_stream_socket_ops.write(stream, buf, count TSRMLS_CC);
    1735             :         }
    1736             : 
    1737         635 :         if (didwrite < 0) {
    1738           0 :                 didwrite = 0;
    1739             :         }
    1740             :         
    1741         635 :         return didwrite;
    1742             : }
    1743             : /* }}} */
    1744             : 
    1745         352 : static size_t php_openssl_sockop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) /* {{{ */
    1746             : {
    1747         352 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    1748         352 :         int nr_bytes = 0;
    1749             : 
    1750         352 :         if (sslsock->ssl_active) {
    1751          33 :                 int retry = 1;
    1752             : 
    1753             :                 do {
    1754          33 :                         nr_bytes = SSL_read(sslsock->ssl_handle, buf, count);
    1755             : 
    1756          33 :                         if (sslsock->reneg && sslsock->reneg->should_close) {
    1757             :                                 /* renegotiation rate limiting triggered */
    1758           1 :                                 php_stream_xport_shutdown(stream, (stream_shutdown_t)SHUT_RDWR TSRMLS_CC);
    1759           1 :                                 nr_bytes = 0;
    1760           1 :                                 stream->eof = 1;
    1761           1 :                                 break;
    1762          32 :                         } else if (nr_bytes <= 0) {
    1763           6 :                                 retry = handle_ssl_error(stream, nr_bytes, 0 TSRMLS_CC);
    1764           6 :                                 stream->eof = (retry == 0 && errno != EAGAIN && !SSL_pending(sslsock->ssl_handle));
    1765             :                                 
    1766             :                         } else {
    1767             :                                 /* we got the data */
    1768          26 :                                 break;
    1769             :                         }
    1770           6 :                 } while (retry);
    1771             : 
    1772          33 :                 if (nr_bytes > 0) {
    1773          26 :                         php_stream_notify_progress_increment(stream->context, nr_bytes, 0);
    1774             :                 }
    1775             :         }
    1776             :         else
    1777             :         {
    1778         319 :                 nr_bytes = php_stream_socket_ops.read(stream, buf, count TSRMLS_CC);
    1779             :         }
    1780             : 
    1781         352 :         if (nr_bytes < 0) {
    1782           0 :                 nr_bytes = 0;
    1783             :         }
    1784             : 
    1785         352 :         return nr_bytes;
    1786             : }
    1787             : /* }}} */
    1788             : 
    1789        1216 : static int php_openssl_sockop_close(php_stream *stream, int close_handle TSRMLS_DC) /* {{{ */
    1790             : {
    1791        1216 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    1792             : #ifdef PHP_WIN32
    1793             :         int n;
    1794             : #endif
    1795             :         unsigned i;
    1796             : 
    1797        1216 :         if (close_handle) {
    1798        1216 :                 if (sslsock->ssl_active) {
    1799          25 :                         SSL_shutdown(sslsock->ssl_handle);
    1800          25 :                         sslsock->ssl_active = 0;
    1801             :                 }
    1802        1216 :                 if (sslsock->ssl_handle) {
    1803         122 :                         SSL_free(sslsock->ssl_handle);
    1804         122 :                         sslsock->ssl_handle = NULL;
    1805             :                 }
    1806        1216 :                 if (sslsock->ctx) {
    1807         123 :                         SSL_CTX_free(sslsock->ctx);
    1808         123 :                         sslsock->ctx = NULL;
    1809             :                 }
    1810             : #ifdef PHP_WIN32
    1811             :                 if (sslsock->s.socket == -1)
    1812             :                         sslsock->s.socket = SOCK_ERR;
    1813             : #endif
    1814        1216 :                 if (sslsock->s.socket != SOCK_ERR) {
    1815             : #ifdef PHP_WIN32
    1816             :                         /* prevent more data from coming in */
    1817             :                         shutdown(sslsock->s.socket, SHUT_RD);
    1818             : 
    1819             :                         /* try to make sure that the OS sends all data before we close the connection.
    1820             :                          * Essentially, we are waiting for the socket to become writeable, which means
    1821             :                          * that all pending data has been sent.
    1822             :                          * We use a small timeout which should encourage the OS to send the data,
    1823             :                          * but at the same time avoid hanging indefinitely.
    1824             :                          * */
    1825             :                         do {
    1826             :                                 n = php_pollfd_for_ms(sslsock->s.socket, POLLOUT, 500);
    1827             :                         } while (n == -1 && php_socket_errno() == EINTR);
    1828             : #endif
    1829         389 :                         closesocket(sslsock->s.socket);
    1830         389 :                         sslsock->s.socket = SOCK_ERR;
    1831             :                 }
    1832             :         }
    1833             : 
    1834        1216 :         if (sslsock->sni_certs) {
    1835          12 :                 for (i=0; i<sslsock->sni_cert_count; i++) {
    1836           9 :                         SSL_CTX_free(sslsock->sni_certs[i].ctx);
    1837           9 :                         pefree(sslsock->sni_certs[i].name, php_stream_is_persistent(stream));
    1838             :                 }
    1839           3 :                 pefree(sslsock->sni_certs, php_stream_is_persistent(stream));
    1840           3 :                 sslsock->sni_certs = NULL;
    1841             :         }
    1842             : 
    1843        1216 :         if (sslsock->url_name) {
    1844        1110 :                 pefree(sslsock->url_name, php_stream_is_persistent(stream));
    1845             :         }
    1846             : 
    1847        1216 :         if (sslsock->reneg) {
    1848          55 :                 pefree(sslsock->reneg, php_stream_is_persistent(stream));
    1849             :         }
    1850             : 
    1851        1216 :         pefree(sslsock, php_stream_is_persistent(stream));
    1852             : 
    1853        1216 :         return 0;
    1854             : }
    1855             : /* }}} */
    1856             : 
    1857        1216 : static int php_openssl_sockop_flush(php_stream *stream TSRMLS_DC) /* {{{ */
    1858             : {
    1859        1216 :         return php_stream_socket_ops.flush(stream TSRMLS_CC);
    1860             : }
    1861             : /* }}} */
    1862             : 
    1863           2 : static int php_openssl_sockop_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
    1864             : {
    1865           2 :         return php_stream_socket_ops.stat(stream, ssb TSRMLS_CC);
    1866             : }
    1867             : /* }}} */
    1868             : 
    1869          96 : static inline int php_openssl_tcp_sockop_accept(php_stream *stream, php_openssl_netstream_data_t *sock,
    1870             :                 php_stream_xport_param *xparam STREAMS_DC TSRMLS_DC)
    1871             : {
    1872             :         int clisock;
    1873             : 
    1874          96 :         xparam->outputs.client = NULL;
    1875             : 
    1876         576 :         clisock = php_network_accept_incoming(sock->s.socket,
    1877          96 :                         xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
    1878          96 :                         xparam->want_textaddr ? &xparam->outputs.textaddrlen : NULL,
    1879          96 :                         xparam->want_addr ? &xparam->outputs.addr : NULL,
    1880          96 :                         xparam->want_addr ? &xparam->outputs.addrlen : NULL,
    1881             :                         xparam->inputs.timeout,
    1882          96 :                         xparam->want_errortext ? &xparam->outputs.error_text : NULL,
    1883             :                         &xparam->outputs.error_code
    1884             :                         TSRMLS_CC);
    1885             : 
    1886          96 :         if (clisock >= 0) {
    1887             :                 php_openssl_netstream_data_t *clisockdata;
    1888             : 
    1889          95 :                 clisockdata = emalloc(sizeof(*clisockdata));
    1890             : 
    1891          95 :                 if (clisockdata == NULL) {
    1892           0 :                         closesocket(clisock);
    1893             :                         /* technically a fatal error */
    1894             :                 } else {
    1895             :                         /* copy underlying tcp fields */
    1896          95 :                         memset(clisockdata, 0, sizeof(*clisockdata));
    1897          95 :                         memcpy(clisockdata, sock, sizeof(clisockdata->s));
    1898             : 
    1899          95 :                         clisockdata->s.socket = clisock;
    1900             :                         
    1901          95 :                         xparam->outputs.client = php_stream_alloc_rel(stream->ops, clisockdata, NULL, "r+");
    1902          95 :                         if (xparam->outputs.client) {
    1903          95 :                                 xparam->outputs.client->context = stream->context;
    1904          95 :                                 if (stream->context) {
    1905          95 :                                         zend_list_addref(stream->context->rsrc_id);
    1906             :                                 }
    1907             :                         }
    1908             :                 }
    1909             : 
    1910          95 :                 if (xparam->outputs.client && sock->enable_on_connect) {
    1911             :                         /* remove the client bit */
    1912          54 :                         if (sock->method & STREAM_CRYPTO_IS_CLIENT) {
    1913          24 :                                 sock->method = ((sock->method >> 1) << 1);
    1914             :                         }
    1915             : 
    1916          54 :                         clisockdata->method = sock->method;
    1917             : 
    1918         108 :                         if (php_stream_xport_crypto_setup(xparam->outputs.client, clisockdata->method,
    1919          54 :                                         NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(
    1920          54 :                                         xparam->outputs.client, 1 TSRMLS_CC) < 0) {
    1921          48 :                                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to enable crypto");
    1922             : 
    1923          47 :                                 php_stream_close(xparam->outputs.client);
    1924          47 :                                 xparam->outputs.client = NULL;
    1925          47 :                                 xparam->outputs.returncode = -1;
    1926             :                         }
    1927             :                 }
    1928             :         }
    1929             :         
    1930          95 :         return xparam->outputs.client == NULL ? -1 : 0;
    1931             : }
    1932             : 
    1933        1689 : static int php_openssl_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC)
    1934             : {
    1935        1689 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    1936        1689 :         php_stream_xport_crypto_param *cparam = (php_stream_xport_crypto_param *)ptrparam;
    1937        1689 :         php_stream_xport_param *xparam = (php_stream_xport_param *)ptrparam;
    1938             : 
    1939        1689 :         switch (option) {
    1940             :                 case PHP_STREAM_OPTION_CHECK_LIVENESS:
    1941             :                         {
    1942             :                                 struct timeval tv;
    1943             :                                 char buf;
    1944          60 :                                 int alive = 1;
    1945             : 
    1946          60 :                                 if (value == -1) {
    1947           0 :                                         if (sslsock->s.timeout.tv_sec == -1) {
    1948           0 :                                                 tv.tv_sec = FG(default_socket_timeout);
    1949           0 :                                                 tv.tv_usec = 0;
    1950             :                                         } else {
    1951           0 :                                                 tv = sslsock->connect_timeout;
    1952             :                                         }
    1953             :                                 } else {
    1954          60 :                                         tv.tv_sec = value;
    1955          60 :                                         tv.tv_usec = 0;
    1956             :                                 }
    1957             : 
    1958          60 :                                 if (sslsock->s.socket == -1) {
    1959           0 :                                         alive = 0;
    1960          60 :                                 } else if (php_pollfd_for(sslsock->s.socket, PHP_POLLREADABLE|POLLPRI, &tv) > 0) {
    1961           3 :                                         if (sslsock->ssl_active) {
    1962             :                                                 int n;
    1963             : 
    1964             :                                                 do {
    1965           0 :                                                         n = SSL_peek(sslsock->ssl_handle, &buf, sizeof(buf));
    1966           0 :                                                         if (n <= 0) {
    1967           0 :                                                                 int err = SSL_get_error(sslsock->ssl_handle, n);
    1968             : 
    1969           0 :                                                                 if (err == SSL_ERROR_SYSCALL) {
    1970           0 :                                                                         alive = php_socket_errno() == EAGAIN;
    1971           0 :                                                                         break;
    1972             :                                                                 }
    1973             : 
    1974           0 :                                                                 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
    1975             :                                                                         /* re-negotiate */
    1976           0 :                                                                         continue;
    1977             :                                                                 }
    1978             : 
    1979             :                                                                 /* any other problem is a fatal error */
    1980           0 :                                                                 alive = 0;
    1981             :                                                         }
    1982             :                                                         /* either peek succeeded or there was an error; we
    1983             :                                                          * have set the alive flag appropriately */
    1984           0 :                                                         break;
    1985           0 :                                                 } while (1);
    1986           3 :                                         } else if (0 == recv(sslsock->s.socket, &buf, sizeof(buf), MSG_PEEK) && php_socket_errno() != EAGAIN) {
    1987           3 :                                                 alive = 0;
    1988             :                                         }
    1989             :                                 }
    1990          60 :                                 return alive ? PHP_STREAM_OPTION_RETURN_OK : PHP_STREAM_OPTION_RETURN_ERR;
    1991             :                         }
    1992             :                         
    1993             :                 case PHP_STREAM_OPTION_CRYPTO_API:
    1994             : 
    1995         245 :                         switch(cparam->op) {
    1996             : 
    1997             :                                 case STREAM_XPORT_CRYPTO_OP_SETUP:
    1998         123 :                                         cparam->outputs.returncode = php_openssl_setup_crypto(stream, sslsock, cparam TSRMLS_CC);
    1999         123 :                                         return PHP_STREAM_OPTION_RETURN_OK;
    2000             :                                         break;
    2001             :                                 case STREAM_XPORT_CRYPTO_OP_ENABLE:
    2002         122 :                                         cparam->outputs.returncode = php_openssl_enable_crypto(stream, sslsock, cparam TSRMLS_CC);
    2003         122 :                                         return PHP_STREAM_OPTION_RETURN_OK;
    2004             :                                         break;
    2005             :                                 default:
    2006             :                                         /* fall through */
    2007             :                                         break;
    2008             :                         }
    2009             : 
    2010           0 :                         break;
    2011             : 
    2012             :                 case PHP_STREAM_OPTION_XPORT_API:
    2013        1294 :                         switch(xparam->op) {
    2014             : 
    2015             :                                 case STREAM_XPORT_OP_CONNECT:
    2016             :                                 case STREAM_XPORT_OP_CONNECT_ASYNC:
    2017             :                                         /* TODO: Async connects need to check the enable_on_connect option when
    2018             :                                          * we notice that the connect has actually been established */
    2019         983 :                                         php_stream_socket_ops.set_option(stream, option, value, ptrparam TSRMLS_CC);
    2020             : 
    2021        1049 :                                         if ((sslsock->enable_on_connect) &&
    2022          63 :                                                 ((xparam->outputs.returncode == 0) ||
    2023           1 :                                                 (xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC && 
    2024           2 :                                                 xparam->outputs.returncode == 1 && xparam->outputs.error_code == EINPROGRESS)))
    2025             :                                         {
    2026         125 :                                                 if (php_stream_xport_crypto_setup(stream, sslsock->method, NULL TSRMLS_CC) < 0 ||
    2027          62 :                                                                 php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
    2028          50 :                                                         php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to enable crypto");
    2029          50 :                                                         xparam->outputs.returncode = -1;
    2030             :                                                 }
    2031             :                                         }
    2032         983 :                                         return PHP_STREAM_OPTION_RETURN_OK;
    2033             : 
    2034             :                                 case STREAM_XPORT_OP_ACCEPT:
    2035             :                                         /* we need to copy the additional fields that the underlying tcp transport
    2036             :                                          * doesn't know about */
    2037          96 :                                         xparam->outputs.returncode = php_openssl_tcp_sockop_accept(stream, sslsock, xparam STREAMS_CC TSRMLS_CC);
    2038             : 
    2039             :                                         
    2040          95 :                                         return PHP_STREAM_OPTION_RETURN_OK;
    2041             : 
    2042             :                                 default:
    2043             :                                         /* fall through */
    2044             :                                         break;
    2045             :                         }
    2046             :         }
    2047             : 
    2048         305 :         return php_stream_socket_ops.set_option(stream, option, value, ptrparam TSRMLS_CC);
    2049             : }
    2050             : 
    2051           6 : static int php_openssl_sockop_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
    2052             : {
    2053           6 :         php_openssl_netstream_data_t *sslsock = (php_openssl_netstream_data_t*)stream->abstract;
    2054             : 
    2055           6 :         switch(castas)  {
    2056             :                 case PHP_STREAM_AS_STDIO:
    2057           0 :                         if (sslsock->ssl_active) {
    2058           0 :                                 return FAILURE;
    2059             :                         }
    2060           0 :                         if (ret)        {
    2061           0 :                                 *ret = fdopen(sslsock->s.socket, stream->mode);
    2062           0 :                                 if (*ret) {
    2063           0 :                                         return SUCCESS;
    2064             :                                 }
    2065           0 :                                 return FAILURE;
    2066             :                         }
    2067           0 :                         return SUCCESS;
    2068             : 
    2069             :                 case PHP_STREAM_AS_FD_FOR_SELECT:
    2070           6 :                         if (ret) {
    2071           6 :                                 *(php_socket_t *)ret = sslsock->s.socket;
    2072             :                         }
    2073           6 :                         return SUCCESS;
    2074             : 
    2075             :                 case PHP_STREAM_AS_FD:
    2076             :                 case PHP_STREAM_AS_SOCKETD:
    2077           0 :                         if (sslsock->ssl_active) {
    2078           0 :                                 return FAILURE;
    2079             :                         }
    2080           0 :                         if (ret) {
    2081           0 :                                 *(php_socket_t *)ret = sslsock->s.socket;
    2082             :                         }
    2083           0 :                         return SUCCESS;
    2084             :                 default:
    2085           0 :                         return FAILURE;
    2086             :         }
    2087             : }
    2088             : 
    2089             : php_stream_ops php_openssl_socket_ops = {
    2090             :         php_openssl_sockop_write, php_openssl_sockop_read,
    2091             :         php_openssl_sockop_close, php_openssl_sockop_flush,
    2092             :         "tcp_socket/ssl",
    2093             :         NULL, /* seek */
    2094             :         php_openssl_sockop_cast,
    2095             :         php_openssl_sockop_stat,
    2096             :         php_openssl_sockop_set_option,
    2097             : };
    2098             : 
    2099          75 : static long get_crypto_method(php_stream_context *ctx, long crypto_method)
    2100             : {
    2101             :         zval **val;
    2102             : 
    2103          75 :         if (ctx && php_stream_context_get_option(ctx, "ssl", "crypto_method", &val) == SUCCESS) {
    2104          21 :                 convert_to_long_ex(val);
    2105          21 :                 crypto_method = (long)Z_LVAL_PP(val);
    2106          21 :                 crypto_method |= STREAM_CRYPTO_IS_CLIENT;
    2107             :         }
    2108             : 
    2109          75 :         return crypto_method;
    2110             : }
    2111             : 
    2112        1090 : static char *get_url_name(const char *resourcename, size_t resourcenamelen, int is_persistent TSRMLS_DC)
    2113             : {
    2114             :         php_url *url;
    2115             : 
    2116        1090 :         if (!resourcename) {
    2117           0 :                 return NULL;
    2118             :         }
    2119             : 
    2120        1090 :         url = php_url_parse_ex(resourcename, resourcenamelen);
    2121        1090 :         if (!url) {
    2122           2 :                 return NULL;
    2123             :         }
    2124             : 
    2125        1088 :         if (url->host) {
    2126        1079 :                 const char * host = url->host;
    2127        1079 :                 char * url_name = NULL;
    2128        1079 :                 size_t len = strlen(host);
    2129             : 
    2130             :                 /* skip trailing dots */
    2131        2159 :                 while (len && host[len-1] == '.') {
    2132           1 :                         --len;
    2133             :                 }
    2134             : 
    2135        1079 :                 if (len) {
    2136        1079 :                         url_name = pestrndup(host, len, is_persistent);
    2137             :                 }
    2138             : 
    2139        1079 :                 php_url_free(url);
    2140        1079 :                 return url_name;
    2141             :         }
    2142             : 
    2143           9 :         php_url_free(url);
    2144           9 :         return NULL;
    2145             : }
    2146             : 
    2147        1090 : php_stream *php_openssl_ssl_socket_factory(const char *proto, size_t protolen,
    2148             :                 const char *resourcename, size_t resourcenamelen,
    2149             :                 const char *persistent_id, int options, int flags,
    2150             :                 struct timeval *timeout,
    2151             :                 php_stream_context *context STREAMS_DC TSRMLS_DC)
    2152             : {
    2153        1090 :         php_stream *stream = NULL;
    2154        1090 :         php_openssl_netstream_data_t *sslsock = NULL;
    2155             : 
    2156        1090 :         sslsock = pemalloc(sizeof(php_openssl_netstream_data_t), persistent_id ? 1 : 0);
    2157        1090 :         memset(sslsock, 0, sizeof(*sslsock));
    2158             : 
    2159        1090 :         sslsock->s.is_blocked = 1;
    2160             :         /* this timeout is used by standard stream funcs, therefor it should use the default value */
    2161        1090 :         sslsock->s.timeout.tv_sec = FG(default_socket_timeout);
    2162        1090 :         sslsock->s.timeout.tv_usec = 0;
    2163             : 
    2164             :         /* use separate timeout for our private funcs */
    2165        1090 :         sslsock->connect_timeout.tv_sec = timeout->tv_sec;
    2166        1090 :         sslsock->connect_timeout.tv_usec = timeout->tv_usec;
    2167             : 
    2168             :         /* we don't know the socket until we have determined if we are binding or
    2169             :          * connecting */
    2170        1090 :         sslsock->s.socket = -1;
    2171             : 
    2172             :         /* Initialize context as NULL */
    2173        1090 :         sslsock->ctx = NULL; 
    2174             : 
    2175        1090 :         stream = php_stream_alloc_rel(&php_openssl_socket_ops, sslsock, persistent_id, "r+");
    2176             : 
    2177        1090 :         if (stream == NULL)     {
    2178           0 :                 pefree(sslsock, persistent_id ? 1 : 0);
    2179           0 :                 return NULL;
    2180             :         }
    2181             : 
    2182        1090 :         if (strncmp(proto, "ssl", protolen) == 0) {
    2183          71 :                 sslsock->enable_on_connect = 1;
    2184          71 :                 sslsock->method = get_crypto_method(context, STREAM_CRYPTO_METHOD_ANY_CLIENT);
    2185        1019 :         } else if (strncmp(proto, "sslv2", protolen) == 0) {
    2186             : #ifdef OPENSSL_NO_SSL2
    2187             :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "SSLv2 support is not compiled into the OpenSSL library PHP is linked against");
    2188             :                 return NULL;
    2189             : #else
    2190           0 :                 sslsock->enable_on_connect = 1;
    2191           0 :                 sslsock->method = STREAM_CRYPTO_METHOD_SSLv2_CLIENT;
    2192             : #endif
    2193        1019 :         } else if (strncmp(proto, "sslv3", protolen) == 0) {
    2194           3 :                 sslsock->enable_on_connect = 1;
    2195           3 :                 sslsock->method = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
    2196        1016 :         } else if (strncmp(proto, "tls", protolen) == 0) {
    2197           4 :                 sslsock->enable_on_connect = 1;
    2198           4 :                 sslsock->method = get_crypto_method(context, STREAM_CRYPTO_METHOD_TLS_CLIENT);
    2199        1012 :         } else if (strncmp(proto, "tlsv1.0", protolen) == 0) {
    2200           2 :                 sslsock->enable_on_connect = 1;
    2201           2 :                 sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT;
    2202        1010 :         } else if (strncmp(proto, "tlsv1.1", protolen) == 0) {
    2203             : #if OPENSSL_VERSION_NUMBER >= 0x10001001L
    2204           3 :                 sslsock->enable_on_connect = 1;
    2205           3 :                 sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
    2206             : #else
    2207             :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "TLSv1.1 support is not compiled into the OpenSSL library PHP is linked against");
    2208             :                 return NULL;
    2209             : #endif
    2210        1007 :         } else if (strncmp(proto, "tlsv1.2", protolen) == 0) {
    2211             : #if OPENSSL_VERSION_NUMBER >= 0x10001001L
    2212           4 :                 sslsock->enable_on_connect = 1;
    2213           4 :                 sslsock->method = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
    2214             : #else
    2215             :                 php_error_docref(NULL TSRMLS_CC, E_WARNING, "TLSv1.2 support is not compiled into the OpenSSL library PHP is linked against");
    2216             :                 return NULL;
    2217             : #endif
    2218             :         }
    2219             : 
    2220        1090 :         sslsock->url_name = get_url_name(resourcename, resourcenamelen, !!persistent_id TSRMLS_CC);
    2221             : 
    2222        1090 :         return stream;
    2223             : }
    2224             : 
    2225             : 
    2226             : 
    2227             : /*
    2228             :  * Local variables:
    2229             :  * tab-width: 4
    2230             :  * c-basic-offset: 4
    2231             :  * End:
    2232             :  * vim600: noet sw=4 ts=4 fdm=marker
    2233             :  * vim<600: noet sw=4 ts=4
    2234             :  */

Generated by: LCOV version 1.10

Generated at Wed, 16 Apr 2014 12:47:52 +0000 (4 days ago)

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