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

Generated by: LCOV version 1.10

Generated at Mon, 04 Aug 2014 15:49:09 +0000 (23 days ago)

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