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: 730 970 75.3 %
Date: 2015-09-02 Functions: 43 44 97.7 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Wed, 02 Sep 2015 17:19:14 +0000 (28 hours ago)

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