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

Generated by: LCOV version 1.10

Generated at Wed, 20 Jul 2016 02:56:23 +0000 (3 days ago)

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