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: 638 889 71.8 %
Date: 2014-10-30 Functions: 37 41 90.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Thu, 30 Oct 2014 07:41:35 +0000 (41 hours ago)

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