Home | History | Annotate | Download | only in vtls
      1 /***************************************************************************
      2  *                                  _   _ ____  _
      3  *  Project                     ___| | | |  _ \| |
      4  *                             / __| | | | |_) | |
      5  *                            | (__| |_| |  _ <| |___
      6  *                             \___|\___/|_| \_\_____|
      7  *
      8  * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel (at) haxx.se>, et al.
      9  *
     10  * This software is licensed as described in the file COPYING, which
     11  * you should have received as part of this distribution. The terms
     12  * are also available at https://curl.haxx.se/docs/copyright.html.
     13  *
     14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
     15  * copies of the Software, and permit persons to whom the Software is
     16  * furnished to do so, under the terms of the COPYING file.
     17  *
     18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
     19  * KIND, either express or implied.
     20  *
     21  ***************************************************************************/
     22 
     23 /*
     24  * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
     25  * but vtls.c should ever call or use these functions.
     26  */
     27 
     28 /*
     29  * The original SSLeay-using code for curl was written by Linas Vepstas and
     30  * Sampo Kellomaki 1998.
     31  */
     32 
     33 #include "curl_setup.h"
     34 
     35 #ifdef USE_OPENSSL
     36 
     37 #ifdef HAVE_LIMITS_H
     38 #include <limits.h>
     39 #endif
     40 
     41 #include "urldata.h"
     42 #include "sendf.h"
     43 #include "formdata.h" /* for the boundary function */
     44 #include "url.h" /* for the ssl config check function */
     45 #include "inet_pton.h"
     46 #include "openssl.h"
     47 #include "connect.h"
     48 #include "slist.h"
     49 #include "select.h"
     50 #include "vtls.h"
     51 #include "strcase.h"
     52 #include "hostcheck.h"
     53 #include "curl_printf.h"
     54 
     55 #include <openssl/ssl.h>
     56 #include <openssl/rand.h>
     57 #include <openssl/x509v3.h>
     58 #include <openssl/dsa.h>
     59 #include <openssl/dh.h>
     60 #include <openssl/err.h>
     61 #include <openssl/md5.h>
     62 #include <openssl/conf.h>
     63 #include <openssl/bn.h>
     64 #include <openssl/rsa.h>
     65 
     66 #ifdef HAVE_OPENSSL_PKCS12_H
     67 #include <openssl/pkcs12.h>
     68 #endif
     69 
     70 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
     71 #include <openssl/ocsp.h>
     72 #endif
     73 
     74 #include "warnless.h"
     75 #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
     76 
     77 /* The last #include files should be: */
     78 #include "curl_memory.h"
     79 #include "memdebug.h"
     80 
     81 #ifndef OPENSSL_VERSION_NUMBER
     82 #error "OPENSSL_VERSION_NUMBER not defined"
     83 #endif
     84 
     85 #if defined(HAVE_OPENSSL_ENGINE_H)
     86 #include <openssl/ui.h>
     87 #endif
     88 
     89 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
     90 #define SSL_METHOD_QUAL const
     91 #else
     92 #define SSL_METHOD_QUAL
     93 #endif
     94 
     95 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
     96 #define HAVE_ERR_REMOVE_THREAD_STATE 1
     97 #endif
     98 
     99 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
    100   OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
    101 #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
    102 #define OPENSSL_NO_SSL2
    103 #endif
    104 
    105 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
    106   !defined(LIBRESSL_VERSION_NUMBER)
    107 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
    108 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
    109 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
    110 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
    111 #define CONST_EXTS const
    112 #define CONST_ASN1_BIT_STRING const
    113 #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
    114 #else
    115 /* For OpenSSL before 1.1.0 */
    116 #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
    117 #define X509_get0_notBefore(x) X509_get_notBefore(x)
    118 #define X509_get0_notAfter(x) X509_get_notAfter(x)
    119 #define CONST_EXTS /* nope */
    120 #define CONST_ASN1_BIT_STRING /* nope */
    121 #ifdef LIBRESSL_VERSION_NUMBER
    122 static unsigned long OpenSSL_version_num(void)
    123 {
    124   return LIBRESSL_VERSION_NUMBER;
    125 }
    126 #else
    127 #define OpenSSL_version_num() SSLeay()
    128 #endif
    129 #endif
    130 
    131 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
    132   !defined(LIBRESSL_VERSION_NUMBER)
    133 #define HAVE_X509_GET0_SIGNATURE 1
    134 #endif
    135 
    136 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
    137   OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
    138   !defined(OPENSSL_NO_COMP)
    139 #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
    140 #endif
    141 
    142 #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
    143 /* not present in older OpenSSL */
    144 #define OPENSSL_load_builtin_modules(x)
    145 #endif
    146 
    147 #if defined(LIBRESSL_VERSION_NUMBER)
    148 #define OSSL_PACKAGE "LibreSSL"
    149 #elif defined(OPENSSL_IS_BORINGSSL)
    150 #define OSSL_PACKAGE "BoringSSL"
    151 #else
    152 #define OSSL_PACKAGE "OpenSSL"
    153 #endif
    154 
    155 /*
    156  * Number of bytes to read from the random number seed file. This must be
    157  * a finite value (because some entropy "files" like /dev/urandom have
    158  * an infinite length), but must be large enough to provide enough
    159  * entopy to properly seed OpenSSL's PRNG.
    160  */
    161 #define RAND_LOAD_LENGTH 1024
    162 
    163 static int passwd_callback(char *buf, int num, int encrypting,
    164                            void *global_passwd)
    165 {
    166   DEBUGASSERT(0 == encrypting);
    167 
    168   if(!encrypting) {
    169     int klen = curlx_uztosi(strlen((char *)global_passwd));
    170     if(num > klen) {
    171       memcpy(buf, global_passwd, klen+1);
    172       return klen;
    173     }
    174   }
    175   return 0;
    176 }
    177 
    178 /*
    179  * rand_enough() returns TRUE if we have seeded the random engine properly.
    180  */
    181 static bool rand_enough(void)
    182 {
    183   return (0 != RAND_status()) ? TRUE : FALSE;
    184 }
    185 
    186 static CURLcode Curl_ossl_seed(struct Curl_easy *data)
    187 {
    188   /* we have the "SSL is seeded" boolean static to prevent multiple
    189      time-consuming seedings in vain */
    190   static bool ssl_seeded = FALSE;
    191   char *buf = data->state.buffer; /* point to the big buffer */
    192   int nread=0;
    193 
    194   if(ssl_seeded)
    195     return CURLE_OK;
    196 
    197   if(rand_enough()) {
    198     /* OpenSSL 1.1.0+ will return here */
    199     ssl_seeded = TRUE;
    200     return CURLE_OK;
    201   }
    202 
    203 #ifndef RANDOM_FILE
    204   /* if RANDOM_FILE isn't defined, we only perform this if an option tells
    205      us to! */
    206   if(data->set.str[STRING_SSL_RANDOM_FILE])
    207 #define RANDOM_FILE "" /* doesn't matter won't be used */
    208 #endif
    209   {
    210     /* let the option override the define */
    211     nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
    212                              data->set.str[STRING_SSL_RANDOM_FILE]:
    213                              RANDOM_FILE),
    214                             RAND_LOAD_LENGTH);
    215     if(rand_enough())
    216       return nread;
    217   }
    218 
    219 #if defined(HAVE_RAND_EGD)
    220   /* only available in OpenSSL 0.9.5 and later */
    221   /* EGD_SOCKET is set at configure time or not at all */
    222 #ifndef EGD_SOCKET
    223   /* If we don't have the define set, we only do this if the egd-option
    224      is set */
    225   if(data->set.str[STRING_SSL_EGDSOCKET])
    226 #define EGD_SOCKET "" /* doesn't matter won't be used */
    227 #endif
    228   {
    229     /* If there's an option and a define, the option overrides the
    230        define */
    231     int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
    232                        data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
    233     if(-1 != ret) {
    234       nread += ret;
    235       if(rand_enough())
    236         return nread;
    237     }
    238   }
    239 #endif
    240 
    241   /* If we get here, it means we need to seed the PRNG using a "silly"
    242      approach! */
    243   do {
    244     unsigned char randb[64];
    245     int len = sizeof(randb);
    246     if(!RAND_bytes(randb, len))
    247       break;
    248     RAND_add(randb, len, (len >> 1));
    249   } while(!rand_enough());
    250 
    251   /* generates a default path for the random seed file */
    252   buf[0]=0; /* blank it first */
    253   RAND_file_name(buf, BUFSIZE);
    254   if(buf[0]) {
    255     /* we got a file name to try */
    256     nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
    257     if(rand_enough())
    258       return nread;
    259   }
    260 
    261   infof(data, "libcurl is now using a weak random seed!\n");
    262   return CURLE_SSL_CONNECT_ERROR; /* confusing error code */
    263 }
    264 
    265 #ifndef SSL_FILETYPE_ENGINE
    266 #define SSL_FILETYPE_ENGINE 42
    267 #endif
    268 #ifndef SSL_FILETYPE_PKCS12
    269 #define SSL_FILETYPE_PKCS12 43
    270 #endif
    271 static int do_file_type(const char *type)
    272 {
    273   if(!type || !type[0])
    274     return SSL_FILETYPE_PEM;
    275   if(strcasecompare(type, "PEM"))
    276     return SSL_FILETYPE_PEM;
    277   if(strcasecompare(type, "DER"))
    278     return SSL_FILETYPE_ASN1;
    279   if(strcasecompare(type, "ENG"))
    280     return SSL_FILETYPE_ENGINE;
    281   if(strcasecompare(type, "P12"))
    282     return SSL_FILETYPE_PKCS12;
    283   return -1;
    284 }
    285 
    286 #if defined(HAVE_OPENSSL_ENGINE_H)
    287 /*
    288  * Supply default password to the engine user interface conversation.
    289  * The password is passed by OpenSSL engine from ENGINE_load_private_key()
    290  * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
    291  */
    292 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
    293 {
    294   const char *password;
    295   switch(UI_get_string_type(uis)) {
    296   case UIT_PROMPT:
    297   case UIT_VERIFY:
    298     password = (const char *)UI_get0_user_data(ui);
    299     if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
    300       UI_set_result(ui, uis, password);
    301       return 1;
    302     }
    303   default:
    304     break;
    305   }
    306   return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
    307 }
    308 
    309 /*
    310  * Suppress interactive request for a default password if available.
    311  */
    312 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
    313 {
    314   switch(UI_get_string_type(uis)) {
    315   case UIT_PROMPT:
    316   case UIT_VERIFY:
    317     if(UI_get0_user_data(ui) &&
    318        (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
    319       return 1;
    320     }
    321   default:
    322     break;
    323   }
    324   return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
    325 }
    326 #endif
    327 
    328 static
    329 int cert_stuff(struct connectdata *conn,
    330                SSL_CTX* ctx,
    331                char *cert_file,
    332                const char *cert_type,
    333                char *key_file,
    334                const char *key_type,
    335                char *key_passwd)
    336 {
    337   struct Curl_easy *data = conn->data;
    338 
    339   int file_type = do_file_type(cert_type);
    340 
    341   if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
    342     SSL *ssl;
    343     X509 *x509;
    344     int cert_done = 0;
    345 
    346     if(key_passwd) {
    347       /* set the password in the callback userdata */
    348       SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
    349       /* Set passwd callback: */
    350       SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
    351     }
    352 
    353 
    354     switch(file_type) {
    355     case SSL_FILETYPE_PEM:
    356       /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
    357       if(SSL_CTX_use_certificate_chain_file(ctx,
    358                                             cert_file) != 1) {
    359         failf(data,
    360               "could not load PEM client certificate, " OSSL_PACKAGE
    361               " error %s, "
    362               "(no key found, wrong pass phrase, or wrong file format?)",
    363               ERR_error_string(ERR_get_error(), NULL) );
    364         return 0;
    365       }
    366       break;
    367 
    368     case SSL_FILETYPE_ASN1:
    369       /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
    370          we use the case above for PEM so this can only be performed with
    371          ASN1 files. */
    372       if(SSL_CTX_use_certificate_file(ctx,
    373                                       cert_file,
    374                                       file_type) != 1) {
    375         failf(data,
    376               "could not load ASN1 client certificate, " OSSL_PACKAGE
    377               " error %s, "
    378               "(no key found, wrong pass phrase, or wrong file format?)",
    379               ERR_error_string(ERR_get_error(), NULL) );
    380         return 0;
    381       }
    382       break;
    383     case SSL_FILETYPE_ENGINE:
    384 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
    385       {
    386         if(data->state.engine) {
    387           const char *cmd_name = "LOAD_CERT_CTRL";
    388           struct {
    389             const char *cert_id;
    390             X509 *cert;
    391           } params;
    392 
    393           params.cert_id = cert_file;
    394           params.cert = NULL;
    395 
    396           /* Does the engine supports LOAD_CERT_CTRL ? */
    397           if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
    398                           0, (void *)cmd_name, NULL)) {
    399             failf(data, "ssl engine does not support loading certificates");
    400             return 0;
    401           }
    402 
    403           /* Load the certificate from the engine */
    404           if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
    405                               0, &params, NULL, 1)) {
    406             failf(data, "ssl engine cannot load client cert with id"
    407                   " '%s' [%s]", cert_file,
    408                   ERR_error_string(ERR_get_error(), NULL));
    409             return 0;
    410           }
    411 
    412           if(!params.cert) {
    413             failf(data, "ssl engine didn't initialized the certificate "
    414                   "properly.");
    415             return 0;
    416           }
    417 
    418           if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
    419             failf(data, "unable to set client certificate");
    420             X509_free(params.cert);
    421             return 0;
    422           }
    423           X509_free(params.cert); /* we don't need the handle any more... */
    424         }
    425         else {
    426           failf(data, "crypto engine not set, can't load certificate");
    427           return 0;
    428         }
    429       }
    430       break;
    431 #else
    432       failf(data, "file type ENG for certificate not implemented");
    433       return 0;
    434 #endif
    435 
    436     case SSL_FILETYPE_PKCS12:
    437     {
    438 #ifdef HAVE_OPENSSL_PKCS12_H
    439       FILE *f;
    440       PKCS12 *p12;
    441       EVP_PKEY *pri;
    442       STACK_OF(X509) *ca = NULL;
    443 
    444       f = fopen(cert_file, "rb");
    445       if(!f) {
    446         failf(data, "could not open PKCS12 file '%s'", cert_file);
    447         return 0;
    448       }
    449       p12 = d2i_PKCS12_fp(f, NULL);
    450       fclose(f);
    451 
    452       if(!p12) {
    453         failf(data, "error reading PKCS12 file '%s'", cert_file);
    454         return 0;
    455       }
    456 
    457       PKCS12_PBE_add();
    458 
    459       if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
    460                        &ca)) {
    461         failf(data,
    462               "could not parse PKCS12 file, check password, " OSSL_PACKAGE
    463               " error %s",
    464               ERR_error_string(ERR_get_error(), NULL) );
    465         PKCS12_free(p12);
    466         return 0;
    467       }
    468 
    469       PKCS12_free(p12);
    470 
    471       if(SSL_CTX_use_certificate(ctx, x509) != 1) {
    472         failf(data,
    473               "could not load PKCS12 client certificate, " OSSL_PACKAGE
    474               " error %s",
    475               ERR_error_string(ERR_get_error(), NULL) );
    476         goto fail;
    477       }
    478 
    479       if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
    480         failf(data, "unable to use private key from PKCS12 file '%s'",
    481               cert_file);
    482         goto fail;
    483       }
    484 
    485       if(!SSL_CTX_check_private_key (ctx)) {
    486         failf(data, "private key from PKCS12 file '%s' "
    487               "does not match certificate in same file", cert_file);
    488         goto fail;
    489       }
    490       /* Set Certificate Verification chain */
    491       if(ca) {
    492         while(sk_X509_num(ca)) {
    493           /*
    494            * Note that sk_X509_pop() is used below to make sure the cert is
    495            * removed from the stack properly before getting passed to
    496            * SSL_CTX_add_extra_chain_cert(). Previously we used
    497            * sk_X509_value() instead, but then we'd clean it in the subsequent
    498            * sk_X509_pop_free() call.
    499            */
    500           X509 *x = sk_X509_pop(ca);
    501           if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
    502             X509_free(x);
    503             failf(data, "cannot add certificate to certificate chain");
    504             goto fail;
    505           }
    506           /* SSL_CTX_add_client_CA() seems to work with either sk_* function,
    507            * presumably because it duplicates what we pass to it.
    508            */
    509           if(!SSL_CTX_add_client_CA(ctx, x)) {
    510             failf(data, "cannot add certificate to client CA list");
    511             goto fail;
    512           }
    513         }
    514       }
    515 
    516       cert_done = 1;
    517   fail:
    518       EVP_PKEY_free(pri);
    519       X509_free(x509);
    520       sk_X509_pop_free(ca, X509_free);
    521 
    522       if(!cert_done)
    523         return 0; /* failure! */
    524       break;
    525 #else
    526       failf(data, "file type P12 for certificate not supported");
    527       return 0;
    528 #endif
    529     }
    530     default:
    531       failf(data, "not supported file type '%s' for certificate", cert_type);
    532       return 0;
    533     }
    534 
    535     file_type = do_file_type(key_type);
    536 
    537     switch(file_type) {
    538     case SSL_FILETYPE_PEM:
    539       if(cert_done)
    540         break;
    541       if(!key_file)
    542         /* cert & key can only be in PEM case in the same file */
    543         key_file=cert_file;
    544     case SSL_FILETYPE_ASN1:
    545       if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
    546         failf(data, "unable to set private key file: '%s' type %s",
    547               key_file, key_type?key_type:"PEM");
    548         return 0;
    549       }
    550       break;
    551     case SSL_FILETYPE_ENGINE:
    552 #ifdef HAVE_OPENSSL_ENGINE_H
    553       {                         /* XXXX still needs some work */
    554         EVP_PKEY *priv_key = NULL;
    555         if(data->state.engine) {
    556           UI_METHOD *ui_method =
    557             UI_create_method((char *)"curl user interface");
    558           if(!ui_method) {
    559             failf(data, "unable do create " OSSL_PACKAGE
    560                   " user-interface method");
    561             return 0;
    562           }
    563           UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
    564           UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
    565           UI_method_set_reader(ui_method, ssl_ui_reader);
    566           UI_method_set_writer(ui_method, ssl_ui_writer);
    567           /* the typecast below was added to please mingw32 */
    568           priv_key = (EVP_PKEY *)
    569             ENGINE_load_private_key(data->state.engine, key_file,
    570                                     ui_method,
    571                                     key_passwd);
    572           UI_destroy_method(ui_method);
    573           if(!priv_key) {
    574             failf(data, "failed to load private key from crypto engine");
    575             return 0;
    576           }
    577           if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
    578             failf(data, "unable to set private key");
    579             EVP_PKEY_free(priv_key);
    580             return 0;
    581           }
    582           EVP_PKEY_free(priv_key);  /* we don't need the handle any more... */
    583         }
    584         else {
    585           failf(data, "crypto engine not set, can't load private key");
    586           return 0;
    587         }
    588       }
    589       break;
    590 #else
    591       failf(data, "file type ENG for private key not supported");
    592       return 0;
    593 #endif
    594     case SSL_FILETYPE_PKCS12:
    595       if(!cert_done) {
    596         failf(data, "file type P12 for private key not supported");
    597         return 0;
    598       }
    599       break;
    600     default:
    601       failf(data, "not supported file type for private key");
    602       return 0;
    603     }
    604 
    605     ssl=SSL_new(ctx);
    606     if(!ssl) {
    607       failf(data, "unable to create an SSL structure");
    608       return 0;
    609     }
    610 
    611     x509=SSL_get_certificate(ssl);
    612 
    613     /* This version was provided by Evan Jordan and is supposed to not
    614        leak memory as the previous version: */
    615     if(x509) {
    616       EVP_PKEY *pktmp = X509_get_pubkey(x509);
    617       EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
    618       EVP_PKEY_free(pktmp);
    619     }
    620 
    621     SSL_free(ssl);
    622 
    623     /* If we are using DSA, we can copy the parameters from
    624      * the private key */
    625 
    626 
    627     /* Now we know that a key and cert have been set against
    628      * the SSL context */
    629     if(!SSL_CTX_check_private_key(ctx)) {
    630       failf(data, "Private key does not match the certificate public key");
    631       return 0;
    632     }
    633   }
    634   return 1;
    635 }
    636 
    637 /* returns non-zero on failure */
    638 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
    639 {
    640 #if 0
    641   return X509_NAME_oneline(a, buf, size);
    642 #else
    643   BIO *bio_out = BIO_new(BIO_s_mem());
    644   BUF_MEM *biomem;
    645   int rc;
    646 
    647   if(!bio_out)
    648     return 1; /* alloc failed! */
    649 
    650   rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
    651   BIO_get_mem_ptr(bio_out, &biomem);
    652 
    653   if((size_t)biomem->length < size)
    654     size = biomem->length;
    655   else
    656     size--; /* don't overwrite the buffer end */
    657 
    658   memcpy(buf, biomem->data, size);
    659   buf[size]=0;
    660 
    661   BIO_free(bio_out);
    662 
    663   return !rc;
    664 #endif
    665 }
    666 
    667 /* Return error string for last OpenSSL error
    668  */
    669 static char *ossl_strerror(unsigned long error, char *buf, size_t size)
    670 {
    671   /* OpenSSL 0.9.6 and later has a function named
    672      ERR_error_string_n() that takes the size of the buffer as a
    673      third argument */
    674   ERR_error_string_n(error, buf, size);
    675   return buf;
    676 }
    677 
    678 /**
    679  * Global SSL init
    680  *
    681  * @retval 0 error initializing SSL
    682  * @retval 1 SSL initialized successfully
    683  */
    684 int Curl_ossl_init(void)
    685 {
    686   OPENSSL_load_builtin_modules();
    687 
    688 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
    689   ENGINE_load_builtin_engines();
    690 #endif
    691 
    692   /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
    693      that function makes an exit() call on wrongly formatted config files
    694      which makes it hard to use in some situations. OPENSSL_config() itself
    695      calls CONF_modules_load_file() and we use that instead and we ignore
    696      its return code! */
    697 
    698   /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
    699      0.9.8e */
    700 #ifndef CONF_MFLAGS_DEFAULT_SECTION
    701 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
    702 #endif
    703 
    704   CONF_modules_load_file(NULL, NULL,
    705                          CONF_MFLAGS_DEFAULT_SECTION|
    706                          CONF_MFLAGS_IGNORE_MISSING_FILE);
    707 
    708 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
    709     !defined(LIBRESSL_VERSION_NUMBER)
    710   /* OpenSSL 1.1.0+ takes care of initialization itself */
    711 #else
    712   /* Lets get nice error messages */
    713   SSL_load_error_strings();
    714 
    715   /* Init the global ciphers and digests */
    716   if(!SSLeay_add_ssl_algorithms())
    717     return 0;
    718 
    719   OpenSSL_add_all_algorithms();
    720 #endif
    721 
    722   return 1;
    723 }
    724 
    725 /* Global cleanup */
    726 void Curl_ossl_cleanup(void)
    727 {
    728 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
    729     !defined(LIBRESSL_VERSION_NUMBER)
    730   /* OpenSSL 1.1 deprecates all these cleanup functions and
    731      turns them into no-ops in OpenSSL 1.0 compatibility mode */
    732 #else
    733   /* Free ciphers and digests lists */
    734   EVP_cleanup();
    735 
    736 #ifdef HAVE_ENGINE_CLEANUP
    737   /* Free engine list */
    738   ENGINE_cleanup();
    739 #endif
    740 
    741   /* Free OpenSSL error strings */
    742   ERR_free_strings();
    743 
    744   /* Free thread local error state, destroying hash upon zero refcount */
    745 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
    746   ERR_remove_thread_state(NULL);
    747 #else
    748   ERR_remove_state(0);
    749 #endif
    750 
    751   /* Free all memory allocated by all configuration modules */
    752   CONF_modules_free();
    753 
    754 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
    755   SSL_COMP_free_compression_methods();
    756 #endif
    757 #endif
    758 }
    759 
    760 /*
    761  * This function is used to determine connection status.
    762  *
    763  * Return codes:
    764  *     1 means the connection is still in place
    765  *     0 means the connection has been closed
    766  *    -1 means the connection status is unknown
    767  */
    768 int Curl_ossl_check_cxn(struct connectdata *conn)
    769 {
    770   /* SSL_peek takes data out of the raw recv buffer without peeking so we use
    771      recv MSG_PEEK instead. Bug #795 */
    772 #ifdef MSG_PEEK
    773   char buf;
    774   ssize_t nread;
    775   nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
    776                (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
    777   if(nread == 0)
    778     return 0; /* connection has been closed */
    779   else if(nread == 1)
    780     return 1; /* connection still in place */
    781   else if(nread == -1) {
    782       int err = SOCKERRNO;
    783       if(err == EINPROGRESS ||
    784 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
    785          err == EAGAIN ||
    786 #endif
    787          err == EWOULDBLOCK)
    788         return 1; /* connection still in place */
    789       if(err == ECONNRESET ||
    790 #ifdef ECONNABORTED
    791          err == ECONNABORTED ||
    792 #endif
    793 #ifdef ENETDOWN
    794          err == ENETDOWN ||
    795 #endif
    796 #ifdef ENETRESET
    797          err == ENETRESET ||
    798 #endif
    799 #ifdef ESHUTDOWN
    800          err == ESHUTDOWN ||
    801 #endif
    802 #ifdef ETIMEDOUT
    803          err == ETIMEDOUT ||
    804 #endif
    805          err == ENOTCONN)
    806         return 0; /* connection has been closed */
    807   }
    808 #endif
    809   return -1; /* connection status unknown */
    810 }
    811 
    812 /* Selects an OpenSSL crypto engine
    813  */
    814 CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
    815 {
    816 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
    817   ENGINE *e;
    818 
    819 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
    820   e = ENGINE_by_id(engine);
    821 #else
    822   /* avoid memory leak */
    823   for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
    824     const char *e_id = ENGINE_get_id(e);
    825     if(!strcmp(engine, e_id))
    826       break;
    827   }
    828 #endif
    829 
    830   if(!e) {
    831     failf(data, "SSL Engine '%s' not found", engine);
    832     return CURLE_SSL_ENGINE_NOTFOUND;
    833   }
    834 
    835   if(data->state.engine) {
    836     ENGINE_finish(data->state.engine);
    837     ENGINE_free(data->state.engine);
    838     data->state.engine = NULL;
    839   }
    840   if(!ENGINE_init(e)) {
    841     char buf[256];
    842 
    843     ENGINE_free(e);
    844     failf(data, "Failed to initialise SSL Engine '%s':\n%s",
    845           engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
    846     return CURLE_SSL_ENGINE_INITFAILED;
    847   }
    848   data->state.engine = e;
    849   return CURLE_OK;
    850 #else
    851   (void)engine;
    852   failf(data, "SSL Engine not supported");
    853   return CURLE_SSL_ENGINE_NOTFOUND;
    854 #endif
    855 }
    856 
    857 /* Sets engine as default for all SSL operations
    858  */
    859 CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
    860 {
    861 #ifdef HAVE_OPENSSL_ENGINE_H
    862   if(data->state.engine) {
    863     if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
    864       infof(data, "set default crypto engine '%s'\n",
    865             ENGINE_get_id(data->state.engine));
    866     }
    867     else {
    868       failf(data, "set default crypto engine '%s' failed",
    869             ENGINE_get_id(data->state.engine));
    870       return CURLE_SSL_ENGINE_SETFAILED;
    871     }
    872   }
    873 #else
    874   (void) data;
    875 #endif
    876   return CURLE_OK;
    877 }
    878 
    879 /* Return list of OpenSSL crypto engine names.
    880  */
    881 struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
    882 {
    883   struct curl_slist *list = NULL;
    884 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
    885   struct curl_slist *beg;
    886   ENGINE *e;
    887 
    888   for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
    889     beg = curl_slist_append(list, ENGINE_get_id(e));
    890     if(!beg) {
    891       curl_slist_free_all(list);
    892       return NULL;
    893     }
    894     list = beg;
    895   }
    896 #endif
    897   (void) data;
    898   return list;
    899 }
    900 
    901 
    902 static void ossl_close(struct ssl_connect_data *connssl)
    903 {
    904   if(connssl->handle) {
    905     (void)SSL_shutdown(connssl->handle);
    906     SSL_set_connect_state(connssl->handle);
    907 
    908     SSL_free (connssl->handle);
    909     connssl->handle = NULL;
    910   }
    911   if(connssl->ctx) {
    912     SSL_CTX_free (connssl->ctx);
    913     connssl->ctx = NULL;
    914   }
    915 }
    916 
    917 /*
    918  * This function is called when an SSL connection is closed.
    919  */
    920 void Curl_ossl_close(struct connectdata *conn, int sockindex)
    921 {
    922   ossl_close(&conn->ssl[sockindex]);
    923   ossl_close(&conn->proxy_ssl[sockindex]);
    924 }
    925 
    926 /*
    927  * This function is called to shut down the SSL layer but keep the
    928  * socket open (CCC - Clear Command Channel)
    929  */
    930 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
    931 {
    932   int retval = 0;
    933   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
    934   struct Curl_easy *data = conn->data;
    935   char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
    936                     to be at least 256 bytes long. */
    937   unsigned long sslerror;
    938   ssize_t nread;
    939   int buffsize;
    940   int err;
    941   int done = 0;
    942 
    943   /* This has only been tested on the proftpd server, and the mod_tls code
    944      sends a close notify alert without waiting for a close notify alert in
    945      response. Thus we wait for a close notify alert from the server, but
    946      we do not send one. Let's hope other servers do the same... */
    947 
    948   if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
    949       (void)SSL_shutdown(connssl->handle);
    950 
    951   if(connssl->handle) {
    952     buffsize = (int)sizeof(buf);
    953     while(!done) {
    954       int what = SOCKET_READABLE(conn->sock[sockindex],
    955                                  SSL_SHUTDOWN_TIMEOUT);
    956       if(what > 0) {
    957         ERR_clear_error();
    958 
    959         /* Something to read, let's do it and hope that it is the close
    960            notify alert from the server */
    961         nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
    962                                   buffsize);
    963         err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
    964 
    965         switch(err) {
    966         case SSL_ERROR_NONE: /* this is not an error */
    967         case SSL_ERROR_ZERO_RETURN: /* no more data */
    968           /* This is the expected response. There was no data but only
    969              the close notify alert */
    970           done = 1;
    971           break;
    972         case SSL_ERROR_WANT_READ:
    973           /* there's data pending, re-invoke SSL_read() */
    974           infof(data, "SSL_ERROR_WANT_READ\n");
    975           break;
    976         case SSL_ERROR_WANT_WRITE:
    977           /* SSL wants a write. Really odd. Let's bail out. */
    978           infof(data, "SSL_ERROR_WANT_WRITE\n");
    979           done = 1;
    980           break;
    981         default:
    982           /* openssl/ssl.h says "look at error stack/return value/errno" */
    983           sslerror = ERR_get_error();
    984           failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d",
    985                 ossl_strerror(sslerror, buf, sizeof(buf)),
    986                 SOCKERRNO);
    987           done = 1;
    988           break;
    989         }
    990       }
    991       else if(0 == what) {
    992         /* timeout */
    993         failf(data, "SSL shutdown timeout");
    994         done = 1;
    995       }
    996       else {
    997         /* anything that gets here is fatally bad */
    998         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
    999         retval = -1;
   1000         done = 1;
   1001       }
   1002     } /* while()-loop for the select() */
   1003 
   1004     if(data->set.verbose) {
   1005 #ifdef HAVE_SSL_GET_SHUTDOWN
   1006       switch(SSL_get_shutdown(connssl->handle)) {
   1007       case SSL_SENT_SHUTDOWN:
   1008         infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
   1009         break;
   1010       case SSL_RECEIVED_SHUTDOWN:
   1011         infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
   1012         break;
   1013       case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
   1014         infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
   1015               "SSL_RECEIVED__SHUTDOWN\n");
   1016         break;
   1017       }
   1018 #endif
   1019     }
   1020 
   1021     SSL_free (connssl->handle);
   1022     connssl->handle = NULL;
   1023   }
   1024   return retval;
   1025 }
   1026 
   1027 void Curl_ossl_session_free(void *ptr)
   1028 {
   1029   /* free the ID */
   1030   SSL_SESSION_free(ptr);
   1031 }
   1032 
   1033 /*
   1034  * This function is called when the 'data' struct is going away. Close
   1035  * down everything and free all resources!
   1036  */
   1037 void Curl_ossl_close_all(struct Curl_easy *data)
   1038 {
   1039 #ifdef HAVE_OPENSSL_ENGINE_H
   1040   if(data->state.engine) {
   1041     ENGINE_finish(data->state.engine);
   1042     ENGINE_free(data->state.engine);
   1043     data->state.engine = NULL;
   1044   }
   1045 #else
   1046   (void)data;
   1047 #endif
   1048 #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
   1049   defined(HAVE_ERR_REMOVE_THREAD_STATE)
   1050   /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
   1051      so we need to clean it here in case the thread will be killed. All OpenSSL
   1052      code should extract the error in association with the error so clearing
   1053      this queue here should be harmless at worst. */
   1054   ERR_remove_thread_state(NULL);
   1055 #endif
   1056 }
   1057 
   1058 /* ====================================================== */
   1059 
   1060 
   1061 /* Quote from RFC2818 section 3.1 "Server Identity"
   1062 
   1063    If a subjectAltName extension of type dNSName is present, that MUST
   1064    be used as the identity. Otherwise, the (most specific) Common Name
   1065    field in the Subject field of the certificate MUST be used. Although
   1066    the use of the Common Name is existing practice, it is deprecated and
   1067    Certification Authorities are encouraged to use the dNSName instead.
   1068 
   1069    Matching is performed using the matching rules specified by
   1070    [RFC2459].  If more than one identity of a given type is present in
   1071    the certificate (e.g., more than one dNSName name, a match in any one
   1072    of the set is considered acceptable.) Names may contain the wildcard
   1073    character * which is considered to match any single domain name
   1074    component or component fragment. E.g., *.a.com matches foo.a.com but
   1075    not bar.foo.a.com. f*.com matches foo.com but not bar.com.
   1076 
   1077    In some cases, the URI is specified as an IP address rather than a
   1078    hostname. In this case, the iPAddress subjectAltName must be present
   1079    in the certificate and must exactly match the IP in the URI.
   1080 
   1081 */
   1082 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
   1083 {
   1084   bool matched = FALSE;
   1085   int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
   1086   size_t addrlen = 0;
   1087   struct Curl_easy *data = conn->data;
   1088   STACK_OF(GENERAL_NAME) *altnames;
   1089 #ifdef ENABLE_IPV6
   1090   struct in6_addr addr;
   1091 #else
   1092   struct in_addr addr;
   1093 #endif
   1094   CURLcode result = CURLE_OK;
   1095   bool dNSName = FALSE; /* if a dNSName field exists in the cert */
   1096   bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
   1097   const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
   1098     conn->host.name;
   1099   const char * const dispname = SSL_IS_PROXY() ?
   1100     conn->http_proxy.host.dispname : conn->host.dispname;
   1101 
   1102 #ifdef ENABLE_IPV6
   1103   if(conn->bits.ipv6_ip &&
   1104      Curl_inet_pton(AF_INET6, hostname, &addr)) {
   1105     target = GEN_IPADD;
   1106     addrlen = sizeof(struct in6_addr);
   1107   }
   1108   else
   1109 #endif
   1110     if(Curl_inet_pton(AF_INET, hostname, &addr)) {
   1111       target = GEN_IPADD;
   1112       addrlen = sizeof(struct in_addr);
   1113     }
   1114 
   1115   /* get a "list" of alternative names */
   1116   altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
   1117 
   1118   if(altnames) {
   1119     int numalts;
   1120     int i;
   1121     bool dnsmatched = FALSE;
   1122     bool ipmatched = FALSE;
   1123 
   1124     /* get amount of alternatives, RFC2459 claims there MUST be at least
   1125        one, but we don't depend on it... */
   1126     numalts = sk_GENERAL_NAME_num(altnames);
   1127 
   1128     /* loop through all alternatives - until a dnsmatch */
   1129     for(i=0; (i < numalts) && !dnsmatched; i++) {
   1130       /* get a handle to alternative name number i */
   1131       const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
   1132 
   1133       if(check->type == GEN_DNS)
   1134         dNSName = TRUE;
   1135       else if(check->type == GEN_IPADD)
   1136         iPAddress = TRUE;
   1137 
   1138       /* only check alternatives of the same type the target is */
   1139       if(check->type == target) {
   1140         /* get data and length */
   1141         const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
   1142         size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
   1143 
   1144         switch(target) {
   1145         case GEN_DNS: /* name/pattern comparison */
   1146           /* The OpenSSL man page explicitly says: "In general it cannot be
   1147              assumed that the data returned by ASN1_STRING_data() is null
   1148              terminated or does not contain embedded nulls." But also that
   1149              "The actual format of the data will depend on the actual string
   1150              type itself: for example for and IA5String the data will be ASCII"
   1151 
   1152              Gisle researched the OpenSSL sources:
   1153              "I checked the 0.9.6 and 0.9.8 sources before my patch and
   1154              it always 0-terminates an IA5String."
   1155           */
   1156           if((altlen == strlen(altptr)) &&
   1157              /* if this isn't true, there was an embedded zero in the name
   1158                 string and we cannot match it. */
   1159              Curl_cert_hostcheck(altptr, hostname)) {
   1160             dnsmatched = TRUE;
   1161             infof(data,
   1162                   " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
   1163                   dispname, altptr);
   1164           }
   1165           break;
   1166 
   1167         case GEN_IPADD: /* IP address comparison */
   1168           /* compare alternative IP address if the data chunk is the same size
   1169              our server IP address is */
   1170           if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
   1171             ipmatched = TRUE;
   1172             infof(data,
   1173                   " subjectAltName: host \"%s\" matched cert's IP address!\n",
   1174                   dispname);
   1175           }
   1176           break;
   1177         }
   1178       }
   1179     }
   1180     GENERAL_NAMES_free(altnames);
   1181 
   1182     if(dnsmatched || ipmatched)
   1183       matched = TRUE;
   1184   }
   1185 
   1186   if(matched)
   1187     /* an alternative name matched */
   1188     ;
   1189   else if(dNSName || iPAddress) {
   1190     infof(data, " subjectAltName does not match %s\n", dispname);
   1191     failf(data, "SSL: no alternative certificate subject name matches "
   1192           "target host name '%s'", dispname);
   1193     result = CURLE_PEER_FAILED_VERIFICATION;
   1194   }
   1195   else {
   1196     /* we have to look to the last occurrence of a commonName in the
   1197        distinguished one to get the most significant one. */
   1198     int j, i=-1;
   1199 
   1200     /* The following is done because of a bug in 0.9.6b */
   1201 
   1202     unsigned char *nulstr = (unsigned char *)"";
   1203     unsigned char *peer_CN = nulstr;
   1204 
   1205     X509_NAME *name = X509_get_subject_name(server_cert);
   1206     if(name)
   1207       while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
   1208         i=j;
   1209 
   1210     /* we have the name entry and we will now convert this to a string
   1211        that we can use for comparison. Doing this we support BMPstring,
   1212        UTF8 etc. */
   1213 
   1214     if(i>=0) {
   1215       ASN1_STRING *tmp =
   1216         X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
   1217 
   1218       /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
   1219          is already UTF-8 encoded. We check for this case and copy the raw
   1220          string manually to avoid the problem. This code can be made
   1221          conditional in the future when OpenSSL has been fixed. Work-around
   1222          brought by Alexis S. L. Carvalho. */
   1223       if(tmp) {
   1224         if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
   1225           j = ASN1_STRING_length(tmp);
   1226           if(j >= 0) {
   1227             peer_CN = OPENSSL_malloc(j+1);
   1228             if(peer_CN) {
   1229               memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
   1230               peer_CN[j] = '\0';
   1231             }
   1232           }
   1233         }
   1234         else /* not a UTF8 name */
   1235           j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
   1236 
   1237         if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
   1238           /* there was a terminating zero before the end of string, this
   1239              cannot match and we return failure! */
   1240           failf(data, "SSL: illegal cert name field");
   1241           result = CURLE_PEER_FAILED_VERIFICATION;
   1242         }
   1243       }
   1244     }
   1245 
   1246     if(peer_CN == nulstr)
   1247        peer_CN = NULL;
   1248     else {
   1249       /* convert peer_CN from UTF8 */
   1250       CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
   1251       /* Curl_convert_from_utf8 calls failf if unsuccessful */
   1252       if(rc) {
   1253         OPENSSL_free(peer_CN);
   1254         return rc;
   1255       }
   1256     }
   1257 
   1258     if(result)
   1259       /* error already detected, pass through */
   1260       ;
   1261     else if(!peer_CN) {
   1262       failf(data,
   1263             "SSL: unable to obtain common name from peer certificate");
   1264       result = CURLE_PEER_FAILED_VERIFICATION;
   1265     }
   1266     else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
   1267       failf(data, "SSL: certificate subject name '%s' does not match "
   1268             "target host name '%s'", peer_CN, dispname);
   1269       result = CURLE_PEER_FAILED_VERIFICATION;
   1270     }
   1271     else {
   1272       infof(data, " common name: %s (matched)\n", peer_CN);
   1273     }
   1274     if(peer_CN)
   1275       OPENSSL_free(peer_CN);
   1276   }
   1277 
   1278   return result;
   1279 }
   1280 
   1281 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
   1282     !defined(OPENSSL_NO_OCSP)
   1283 static CURLcode verifystatus(struct connectdata *conn,
   1284                              struct ssl_connect_data *connssl)
   1285 {
   1286   int i, ocsp_status;
   1287   const unsigned char *p;
   1288   CURLcode result = CURLE_OK;
   1289   struct Curl_easy *data = conn->data;
   1290 
   1291   OCSP_RESPONSE *rsp = NULL;
   1292   OCSP_BASICRESP *br = NULL;
   1293   X509_STORE     *st = NULL;
   1294   STACK_OF(X509) *ch = NULL;
   1295 
   1296   long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
   1297 
   1298   if(!p) {
   1299     failf(data, "No OCSP response received");
   1300     result = CURLE_SSL_INVALIDCERTSTATUS;
   1301     goto end;
   1302   }
   1303 
   1304   rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
   1305   if(!rsp) {
   1306     failf(data, "Invalid OCSP response");
   1307     result = CURLE_SSL_INVALIDCERTSTATUS;
   1308     goto end;
   1309   }
   1310 
   1311   ocsp_status = OCSP_response_status(rsp);
   1312   if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
   1313     failf(data, "Invalid OCSP response status: %s (%d)",
   1314           OCSP_response_status_str(ocsp_status), ocsp_status);
   1315     result = CURLE_SSL_INVALIDCERTSTATUS;
   1316     goto end;
   1317   }
   1318 
   1319   br = OCSP_response_get1_basic(rsp);
   1320   if(!br) {
   1321     failf(data, "Invalid OCSP response");
   1322     result = CURLE_SSL_INVALIDCERTSTATUS;
   1323     goto end;
   1324   }
   1325 
   1326   ch = SSL_get_peer_cert_chain(connssl->handle);
   1327   st = SSL_CTX_get_cert_store(connssl->ctx);
   1328 
   1329 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
   1330      defined(LIBRESSL_VERSION_NUMBER))
   1331   /* The authorized responder cert in the OCSP response MUST be signed by the
   1332      peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
   1333      no problem, but if it's an intermediate cert OpenSSL has a bug where it
   1334      expects this issuer to be present in the chain embedded in the OCSP
   1335      response. So we add it if necessary. */
   1336 
   1337   /* First make sure the peer cert chain includes both a peer and an issuer,
   1338      and the OCSP response contains a responder cert. */
   1339   if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
   1340     X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
   1341 
   1342     /* Find issuer of responder cert and add it to the OCSP response chain */
   1343     for(i = 0; i < sk_X509_num(ch); i++) {
   1344       X509 *issuer = sk_X509_value(ch, i);
   1345       if(X509_check_issued(issuer, responder) == X509_V_OK) {
   1346         if(!OCSP_basic_add1_cert(br, issuer)) {
   1347           failf(data, "Could not add issuer cert to OCSP response");
   1348           result = CURLE_SSL_INVALIDCERTSTATUS;
   1349           goto end;
   1350         }
   1351       }
   1352     }
   1353   }
   1354 #endif
   1355 
   1356   if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
   1357     failf(data, "OCSP response verification failed");
   1358     result = CURLE_SSL_INVALIDCERTSTATUS;
   1359     goto end;
   1360   }
   1361 
   1362   for(i = 0; i < OCSP_resp_count(br); i++) {
   1363     int cert_status, crl_reason;
   1364     OCSP_SINGLERESP *single = NULL;
   1365 
   1366     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
   1367 
   1368     single = OCSP_resp_get0(br, i);
   1369     if(!single)
   1370       continue;
   1371 
   1372     cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
   1373                                           &thisupd, &nextupd);
   1374 
   1375     if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
   1376       failf(data, "OCSP response has expired");
   1377       result = CURLE_SSL_INVALIDCERTSTATUS;
   1378       goto end;
   1379     }
   1380 
   1381     infof(data, "SSL certificate status: %s (%d)\n",
   1382           OCSP_cert_status_str(cert_status), cert_status);
   1383 
   1384     switch(cert_status) {
   1385       case V_OCSP_CERTSTATUS_GOOD:
   1386         break;
   1387 
   1388       case V_OCSP_CERTSTATUS_REVOKED:
   1389         result = CURLE_SSL_INVALIDCERTSTATUS;
   1390 
   1391         failf(data, "SSL certificate revocation reason: %s (%d)",
   1392               OCSP_crl_reason_str(crl_reason), crl_reason);
   1393         goto end;
   1394 
   1395       case V_OCSP_CERTSTATUS_UNKNOWN:
   1396         result = CURLE_SSL_INVALIDCERTSTATUS;
   1397         goto end;
   1398     }
   1399   }
   1400 
   1401 end:
   1402   if(br) OCSP_BASICRESP_free(br);
   1403   OCSP_RESPONSE_free(rsp);
   1404 
   1405   return result;
   1406 }
   1407 #endif
   1408 
   1409 #endif /* USE_OPENSSL */
   1410 
   1411 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
   1412    and thus this cannot be done there. */
   1413 #ifdef SSL_CTRL_SET_MSG_CALLBACK
   1414 
   1415 static const char *ssl_msg_type(int ssl_ver, int msg)
   1416 {
   1417 #ifdef SSL2_VERSION_MAJOR
   1418   if(ssl_ver == SSL2_VERSION_MAJOR) {
   1419     switch (msg) {
   1420       case SSL2_MT_ERROR:
   1421         return "Error";
   1422       case SSL2_MT_CLIENT_HELLO:
   1423         return "Client hello";
   1424       case SSL2_MT_CLIENT_MASTER_KEY:
   1425         return "Client key";
   1426       case SSL2_MT_CLIENT_FINISHED:
   1427         return "Client finished";
   1428       case SSL2_MT_SERVER_HELLO:
   1429         return "Server hello";
   1430       case SSL2_MT_SERVER_VERIFY:
   1431         return "Server verify";
   1432       case SSL2_MT_SERVER_FINISHED:
   1433         return "Server finished";
   1434       case SSL2_MT_REQUEST_CERTIFICATE:
   1435         return "Request CERT";
   1436       case SSL2_MT_CLIENT_CERTIFICATE:
   1437         return "Client CERT";
   1438     }
   1439   }
   1440   else
   1441 #endif
   1442   if(ssl_ver == SSL3_VERSION_MAJOR) {
   1443     switch (msg) {
   1444       case SSL3_MT_HELLO_REQUEST:
   1445         return "Hello request";
   1446       case SSL3_MT_CLIENT_HELLO:
   1447         return "Client hello";
   1448       case SSL3_MT_SERVER_HELLO:
   1449         return "Server hello";
   1450 #ifdef SSL3_MT_NEWSESSION_TICKET
   1451       case SSL3_MT_NEWSESSION_TICKET:
   1452         return "Newsession Ticket";
   1453 #endif
   1454       case SSL3_MT_CERTIFICATE:
   1455         return "Certificate";
   1456       case SSL3_MT_SERVER_KEY_EXCHANGE:
   1457         return "Server key exchange";
   1458       case SSL3_MT_CLIENT_KEY_EXCHANGE:
   1459         return "Client key exchange";
   1460       case SSL3_MT_CERTIFICATE_REQUEST:
   1461         return "Request CERT";
   1462       case SSL3_MT_SERVER_DONE:
   1463         return "Server finished";
   1464       case SSL3_MT_CERTIFICATE_VERIFY:
   1465         return "CERT verify";
   1466       case SSL3_MT_FINISHED:
   1467         return "Finished";
   1468 #ifdef SSL3_MT_CERTIFICATE_STATUS
   1469       case SSL3_MT_CERTIFICATE_STATUS:
   1470         return "Certificate Status";
   1471 #endif
   1472     }
   1473   }
   1474   return "Unknown";
   1475 }
   1476 
   1477 static const char *tls_rt_type(int type)
   1478 {
   1479   switch(type) {
   1480 #ifdef SSL3_RT_HEADER
   1481   case SSL3_RT_HEADER:
   1482     return "TLS header";
   1483 #endif
   1484   case SSL3_RT_CHANGE_CIPHER_SPEC:
   1485     return "TLS change cipher";
   1486   case SSL3_RT_ALERT:
   1487     return "TLS alert";
   1488   case SSL3_RT_HANDSHAKE:
   1489     return "TLS handshake";
   1490   case SSL3_RT_APPLICATION_DATA:
   1491     return "TLS app data";
   1492   default:
   1493     return "TLS Unknown";
   1494   }
   1495 }
   1496 
   1497 
   1498 /*
   1499  * Our callback from the SSL/TLS layers.
   1500  */
   1501 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
   1502                           const void *buf, size_t len, SSL *ssl,
   1503                           void *userp)
   1504 {
   1505   struct Curl_easy *data;
   1506   const char *msg_name, *tls_rt_name;
   1507   char ssl_buf[1024];
   1508   char unknown[32];
   1509   int msg_type, txt_len;
   1510   const char *verstr = NULL;
   1511   struct connectdata *conn = userp;
   1512 
   1513   if(!conn || !conn->data || !conn->data->set.fdebug ||
   1514      (direction != 0 && direction != 1))
   1515     return;
   1516 
   1517   data = conn->data;
   1518 
   1519   switch(ssl_ver) {
   1520 #ifdef SSL2_VERSION /* removed in recent versions */
   1521   case SSL2_VERSION:
   1522     verstr = "SSLv2";
   1523     break;
   1524 #endif
   1525 #ifdef SSL3_VERSION
   1526   case SSL3_VERSION:
   1527     verstr = "SSLv3";
   1528     break;
   1529 #endif
   1530   case TLS1_VERSION:
   1531     verstr = "TLSv1.0";
   1532     break;
   1533 #ifdef TLS1_1_VERSION
   1534   case TLS1_1_VERSION:
   1535     verstr = "TLSv1.1";
   1536     break;
   1537 #endif
   1538 #ifdef TLS1_2_VERSION
   1539   case TLS1_2_VERSION:
   1540     verstr = "TLSv1.2";
   1541     break;
   1542 #endif
   1543 #ifdef TLS1_3_VERSION
   1544   case TLS1_3_VERSION:
   1545     verstr = "TLSv1.3";
   1546     break;
   1547 #endif
   1548   case 0:
   1549     break;
   1550   default:
   1551     snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
   1552     verstr = unknown;
   1553     break;
   1554   }
   1555 
   1556   if(ssl_ver) {
   1557     /* the info given when the version is zero is not that useful for us */
   1558 
   1559     ssl_ver >>= 8; /* check the upper 8 bits only below */
   1560 
   1561     /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
   1562      * always pass-up content-type as 0. But the interesting message-type
   1563      * is at 'buf[0]'.
   1564      */
   1565     if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
   1566       tls_rt_name = tls_rt_type(content_type);
   1567     else
   1568       tls_rt_name = "";
   1569 
   1570     msg_type = *(char *)buf;
   1571     msg_name = ssl_msg_type(ssl_ver, msg_type);
   1572 
   1573     txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
   1574                        verstr, direction?"OUT":"IN",
   1575                        tls_rt_name, msg_name, msg_type);
   1576     Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
   1577   }
   1578 
   1579   Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
   1580              CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
   1581   (void) ssl;
   1582 }
   1583 #endif
   1584 
   1585 #ifdef USE_OPENSSL
   1586 /* ====================================================== */
   1587 
   1588 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
   1589 #  define use_sni(x)  sni = (x)
   1590 #else
   1591 #  define use_sni(x)  Curl_nop_stmt
   1592 #endif
   1593 
   1594 /* Check for OpenSSL 1.0.2 which has ALPN support. */
   1595 #undef HAS_ALPN
   1596 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
   1597     && !defined(OPENSSL_NO_TLSEXT)
   1598 #  define HAS_ALPN 1
   1599 #endif
   1600 
   1601 /* Check for OpenSSL 1.0.1 which has NPN support. */
   1602 #undef HAS_NPN
   1603 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
   1604     && !defined(OPENSSL_NO_TLSEXT) \
   1605     && !defined(OPENSSL_NO_NEXTPROTONEG)
   1606 #  define HAS_NPN 1
   1607 #endif
   1608 
   1609 #ifdef HAS_NPN
   1610 
   1611 /*
   1612  * in is a list of lenght prefixed strings. this function has to select
   1613  * the protocol we want to use from the list and write its string into out.
   1614  */
   1615 
   1616 static int
   1617 select_next_protocol(unsigned char **out, unsigned char *outlen,
   1618                      const unsigned char *in, unsigned int inlen,
   1619                      const char *key, unsigned int keylen)
   1620 {
   1621   unsigned int i;
   1622   for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
   1623     if(memcmp(&in[i + 1], key, keylen) == 0) {
   1624       *out = (unsigned char *) &in[i + 1];
   1625       *outlen = in[i];
   1626       return 0;
   1627     }
   1628   }
   1629   return -1;
   1630 }
   1631 
   1632 static int
   1633 select_next_proto_cb(SSL *ssl,
   1634                      unsigned char **out, unsigned char *outlen,
   1635                      const unsigned char *in, unsigned int inlen,
   1636                      void *arg)
   1637 {
   1638   struct connectdata *conn = (struct connectdata*) arg;
   1639 
   1640   (void)ssl;
   1641 
   1642 #ifdef USE_NGHTTP2
   1643   if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
   1644      !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
   1645                            NGHTTP2_PROTO_VERSION_ID_LEN)) {
   1646     infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
   1647           NGHTTP2_PROTO_VERSION_ID);
   1648     conn->negnpn = CURL_HTTP_VERSION_2;
   1649     return SSL_TLSEXT_ERR_OK;
   1650   }
   1651 #endif
   1652 
   1653   if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
   1654                            ALPN_HTTP_1_1_LENGTH)) {
   1655     infof(conn->data, "NPN, negotiated HTTP1.1\n");
   1656     conn->negnpn = CURL_HTTP_VERSION_1_1;
   1657     return SSL_TLSEXT_ERR_OK;
   1658   }
   1659 
   1660   infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
   1661   *out = (unsigned char *)ALPN_HTTP_1_1;
   1662   *outlen = ALPN_HTTP_1_1_LENGTH;
   1663   conn->negnpn = CURL_HTTP_VERSION_1_1;
   1664 
   1665   return SSL_TLSEXT_ERR_OK;
   1666 }
   1667 #endif /* HAS_NPN */
   1668 
   1669 static const char *
   1670 get_ssl_version_txt(SSL *ssl)
   1671 {
   1672   if(!ssl)
   1673     return "";
   1674 
   1675   switch(SSL_version(ssl)) {
   1676 #ifdef TLS1_3_VERSION
   1677   case TLS1_3_VERSION:
   1678     return "TLSv1.3";
   1679 #endif
   1680 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1681   case TLS1_2_VERSION:
   1682     return "TLSv1.2";
   1683   case TLS1_1_VERSION:
   1684     return "TLSv1.1";
   1685 #endif
   1686   case TLS1_VERSION:
   1687     return "TLSv1.0";
   1688   case SSL3_VERSION:
   1689     return "SSLv3";
   1690   case SSL2_VERSION:
   1691     return "SSLv2";
   1692   }
   1693   return "unknown";
   1694 }
   1695 
   1696 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
   1697 {
   1698   CURLcode result = CURLE_OK;
   1699   char *ciphers;
   1700   struct Curl_easy *data = conn->data;
   1701   SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
   1702   X509_LOOKUP *lookup = NULL;
   1703   curl_socket_t sockfd = conn->sock[sockindex];
   1704   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
   1705   long ctx_options;
   1706 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
   1707   bool sni;
   1708 #ifdef ENABLE_IPV6
   1709   struct in6_addr addr;
   1710 #else
   1711   struct in_addr addr;
   1712 #endif
   1713 #endif
   1714   long * const certverifyresult = SSL_IS_PROXY() ?
   1715     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
   1716   const long int ssl_version = SSL_CONN_CONFIG(version);
   1717 #ifdef USE_TLS_SRP
   1718   const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
   1719 #endif
   1720   char * const ssl_cert = SSL_SET_OPTION(cert);
   1721   const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
   1722   const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
   1723   const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
   1724   const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
   1725   const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
   1726   const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
   1727     conn->host.name;
   1728 
   1729   DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
   1730 
   1731   /* Make funny stuff to get random input */
   1732   result = Curl_ossl_seed(data);
   1733   if(result)
   1734     return result;
   1735 
   1736   *certverifyresult = !X509_V_OK;
   1737 
   1738   /* check to see if we've been told to use an explicit SSL/TLS version */
   1739 
   1740   switch(ssl_version) {
   1741   case CURL_SSLVERSION_DEFAULT:
   1742   case CURL_SSLVERSION_TLSv1:
   1743   case CURL_SSLVERSION_TLSv1_0:
   1744   case CURL_SSLVERSION_TLSv1_1:
   1745   case CURL_SSLVERSION_TLSv1_2:
   1746   case CURL_SSLVERSION_TLSv1_3:
   1747     /* it will be handled later with the context options */
   1748 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
   1749     !defined(LIBRESSL_VERSION_NUMBER)
   1750     req_method = TLS_client_method();
   1751 #else
   1752     req_method = SSLv23_client_method();
   1753 #endif
   1754     use_sni(TRUE);
   1755     break;
   1756   case CURL_SSLVERSION_SSLv2:
   1757 #ifdef OPENSSL_NO_SSL2
   1758     failf(data, OSSL_PACKAGE " was built without SSLv2 support");
   1759     return CURLE_NOT_BUILT_IN;
   1760 #else
   1761 #ifdef USE_TLS_SRP
   1762     if(ssl_authtype == CURL_TLSAUTH_SRP)
   1763       return CURLE_SSL_CONNECT_ERROR;
   1764 #endif
   1765     req_method = SSLv2_client_method();
   1766     use_sni(FALSE);
   1767     break;
   1768 #endif
   1769   case CURL_SSLVERSION_SSLv3:
   1770 #ifdef OPENSSL_NO_SSL3_METHOD
   1771     failf(data, OSSL_PACKAGE " was built without SSLv3 support");
   1772     return CURLE_NOT_BUILT_IN;
   1773 #else
   1774 #ifdef USE_TLS_SRP
   1775     if(ssl_authtype == CURL_TLSAUTH_SRP)
   1776       return CURLE_SSL_CONNECT_ERROR;
   1777 #endif
   1778     req_method = SSLv3_client_method();
   1779     use_sni(FALSE);
   1780     break;
   1781 #endif
   1782   default:
   1783     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
   1784     return CURLE_SSL_CONNECT_ERROR;
   1785   }
   1786 
   1787   if(connssl->ctx)
   1788     SSL_CTX_free(connssl->ctx);
   1789   connssl->ctx = SSL_CTX_new(req_method);
   1790 
   1791   if(!connssl->ctx) {
   1792     failf(data, "SSL: couldn't create a context: %s",
   1793           ERR_error_string(ERR_peek_error(), NULL));
   1794     return CURLE_OUT_OF_MEMORY;
   1795   }
   1796 
   1797 #ifdef SSL_MODE_RELEASE_BUFFERS
   1798   SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
   1799 #endif
   1800 
   1801 #ifdef SSL_CTRL_SET_MSG_CALLBACK
   1802   if(data->set.fdebug && data->set.verbose) {
   1803     /* the SSL trace callback is only used for verbose logging */
   1804     SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
   1805     SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
   1806   }
   1807 #endif
   1808 
   1809   /* OpenSSL contains code to work-around lots of bugs and flaws in various
   1810      SSL-implementations. SSL_CTX_set_options() is used to enabled those
   1811      work-arounds. The man page for this option states that SSL_OP_ALL enables
   1812      all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
   1813      enable the bug workaround options if compatibility with somewhat broken
   1814      implementations is desired."
   1815 
   1816      The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
   1817      disable "rfc4507bis session ticket support".  rfc4507bis was later turned
   1818      into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
   1819 
   1820      The enabled extension concerns the session management. I wonder how often
   1821      libcurl stops a connection and then resumes a TLS session. also, sending
   1822      the session data is some overhead. .I suggest that you just use your
   1823      proposed patch (which explicitly disables TICKET).
   1824 
   1825      If someone writes an application with libcurl and openssl who wants to
   1826      enable the feature, one can do this in the SSL callback.
   1827 
   1828      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
   1829      interoperability with web server Netscape Enterprise Server 2.0.1 which
   1830      was released back in 1996.
   1831 
   1832      Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
   1833      become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
   1834      CVE-2010-4180 when using previous OpenSSL versions we no longer enable
   1835      this option regardless of OpenSSL version and SSL_OP_ALL definition.
   1836 
   1837      OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
   1838      (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
   1839      SSL_OP_ALL that _disables_ that work-around despite the fact that
   1840      SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
   1841      keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
   1842      must not be set.
   1843   */
   1844 
   1845   ctx_options = SSL_OP_ALL;
   1846 
   1847 #ifdef SSL_OP_NO_TICKET
   1848   ctx_options |= SSL_OP_NO_TICKET;
   1849 #endif
   1850 
   1851 #ifdef SSL_OP_NO_COMPRESSION
   1852   ctx_options |= SSL_OP_NO_COMPRESSION;
   1853 #endif
   1854 
   1855 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
   1856   /* mitigate CVE-2010-4180 */
   1857   ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
   1858 #endif
   1859 
   1860 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
   1861   /* unless the user explicitly ask to allow the protocol vulnerability we
   1862      use the work-around */
   1863   if(!SSL_SET_OPTION(enable_beast))
   1864     ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
   1865 #endif
   1866 
   1867   switch(ssl_version) {
   1868   case CURL_SSLVERSION_SSLv3:
   1869 #ifdef USE_TLS_SRP
   1870     if(ssl_authtype == CURL_TLSAUTH_SRP) {
   1871       infof(data, "Set version TLSv1.x for SRP authorisation\n");
   1872     }
   1873 #endif
   1874     ctx_options |= SSL_OP_NO_SSLv2;
   1875     ctx_options |= SSL_OP_NO_TLSv1;
   1876 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1877     ctx_options |= SSL_OP_NO_TLSv1_1;
   1878     ctx_options |= SSL_OP_NO_TLSv1_2;
   1879 #ifdef TLS1_3_VERSION
   1880     ctx_options |= SSL_OP_NO_TLSv1_3;
   1881 #endif
   1882 #endif
   1883     break;
   1884 
   1885   case CURL_SSLVERSION_DEFAULT:
   1886   case CURL_SSLVERSION_TLSv1:
   1887     ctx_options |= SSL_OP_NO_SSLv2;
   1888     ctx_options |= SSL_OP_NO_SSLv3;
   1889     break;
   1890 
   1891   case CURL_SSLVERSION_TLSv1_0:
   1892     ctx_options |= SSL_OP_NO_SSLv2;
   1893     ctx_options |= SSL_OP_NO_SSLv3;
   1894 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1895     ctx_options |= SSL_OP_NO_TLSv1_1;
   1896     ctx_options |= SSL_OP_NO_TLSv1_2;
   1897 #ifdef TLS1_3_VERSION
   1898     ctx_options |= SSL_OP_NO_TLSv1_3;
   1899 #endif
   1900 #endif
   1901     break;
   1902 
   1903   case CURL_SSLVERSION_TLSv1_1:
   1904 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1905     ctx_options |= SSL_OP_NO_SSLv2;
   1906     ctx_options |= SSL_OP_NO_SSLv3;
   1907     ctx_options |= SSL_OP_NO_TLSv1;
   1908     ctx_options |= SSL_OP_NO_TLSv1_2;
   1909 #ifdef TLS1_3_VERSION
   1910     ctx_options |= SSL_OP_NO_TLSv1_3;
   1911 #endif
   1912     break;
   1913 #else
   1914     failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
   1915     return CURLE_NOT_BUILT_IN;
   1916 #endif
   1917 
   1918   case CURL_SSLVERSION_TLSv1_2:
   1919 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1920     ctx_options |= SSL_OP_NO_SSLv2;
   1921     ctx_options |= SSL_OP_NO_SSLv3;
   1922     ctx_options |= SSL_OP_NO_TLSv1;
   1923     ctx_options |= SSL_OP_NO_TLSv1_1;
   1924 #ifdef TLS1_3_VERSION
   1925     ctx_options |= SSL_OP_NO_TLSv1_3;
   1926 #endif
   1927     break;
   1928 #else
   1929     failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
   1930     return CURLE_NOT_BUILT_IN;
   1931 #endif
   1932 
   1933   case CURL_SSLVERSION_TLSv1_3:
   1934 #ifdef TLS1_3_VERSION
   1935     SSL_CTX_set_max_proto_version(connssl->ctx, TLS1_3_VERSION);
   1936     ctx_options |= SSL_OP_NO_SSLv2;
   1937     ctx_options |= SSL_OP_NO_SSLv3;
   1938     ctx_options |= SSL_OP_NO_TLSv1;
   1939     ctx_options |= SSL_OP_NO_TLSv1_1;
   1940     ctx_options |= SSL_OP_NO_TLSv1_2;
   1941     break;
   1942 #else
   1943     failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
   1944     return CURLE_NOT_BUILT_IN;
   1945 #endif
   1946 
   1947   case CURL_SSLVERSION_SSLv2:
   1948 #ifndef OPENSSL_NO_SSL2
   1949     ctx_options |= SSL_OP_NO_SSLv3;
   1950     ctx_options |= SSL_OP_NO_TLSv1;
   1951 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
   1952     ctx_options |= SSL_OP_NO_TLSv1_1;
   1953     ctx_options |= SSL_OP_NO_TLSv1_2;
   1954 #ifdef TLS1_3_VERSION
   1955     ctx_options |= SSL_OP_NO_TLSv1_3;
   1956 #endif
   1957 #endif
   1958     break;
   1959 #else
   1960     failf(data, OSSL_PACKAGE " was built without SSLv2 support");
   1961     return CURLE_NOT_BUILT_IN;
   1962 #endif
   1963 
   1964   default:
   1965     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
   1966     return CURLE_SSL_CONNECT_ERROR;
   1967   }
   1968 
   1969   SSL_CTX_set_options(connssl->ctx, ctx_options);
   1970 
   1971 #ifdef HAS_NPN
   1972   if(conn->bits.tls_enable_npn)
   1973     SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
   1974 #endif
   1975 
   1976 #ifdef HAS_ALPN
   1977   if(conn->bits.tls_enable_alpn) {
   1978     int cur = 0;
   1979     unsigned char protocols[128];
   1980 
   1981 #ifdef USE_NGHTTP2
   1982     if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
   1983       protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
   1984 
   1985       memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
   1986           NGHTTP2_PROTO_VERSION_ID_LEN);
   1987       cur += NGHTTP2_PROTO_VERSION_ID_LEN;
   1988       infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
   1989     }
   1990 #endif
   1991 
   1992     protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
   1993     memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
   1994     cur += ALPN_HTTP_1_1_LENGTH;
   1995     infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
   1996 
   1997     /* expects length prefixed preference ordered list of protocols in wire
   1998      * format
   1999      */
   2000     SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
   2001   }
   2002 #endif
   2003 
   2004   if(ssl_cert || ssl_cert_type) {
   2005     if(!cert_stuff(conn, connssl->ctx, ssl_cert, ssl_cert_type,
   2006                    SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
   2007                    SSL_SET_OPTION(key_passwd))) {
   2008       /* failf() is already done in cert_stuff() */
   2009       return CURLE_SSL_CERTPROBLEM;
   2010     }
   2011   }
   2012 
   2013   ciphers = SSL_CONN_CONFIG(cipher_list);
   2014   if(!ciphers)
   2015     ciphers = (char *)DEFAULT_CIPHER_SELECTION;
   2016   if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
   2017     failf(data, "failed setting cipher list: %s", ciphers);
   2018     return CURLE_SSL_CIPHER;
   2019   }
   2020   infof(data, "Cipher selection: %s\n", ciphers);
   2021 
   2022 #ifdef USE_TLS_SRP
   2023   if(ssl_authtype == CURL_TLSAUTH_SRP) {
   2024     char * const ssl_username = SSL_SET_OPTION(username);
   2025 
   2026     infof(data, "Using TLS-SRP username: %s\n", ssl_username);
   2027 
   2028     if(!SSL_CTX_set_srp_username(connssl->ctx, ssl_username)) {
   2029       failf(data, "Unable to set SRP user name");
   2030       return CURLE_BAD_FUNCTION_ARGUMENT;
   2031     }
   2032     if(!SSL_CTX_set_srp_password(connssl->ctx, SSL_SET_OPTION(password))) {
   2033       failf(data, "failed setting SRP password");
   2034       return CURLE_BAD_FUNCTION_ARGUMENT;
   2035     }
   2036     if(!SSL_CONN_CONFIG(cipher_list)) {
   2037       infof(data, "Setting cipher list SRP\n");
   2038 
   2039       if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
   2040         failf(data, "failed setting SRP cipher list");
   2041         return CURLE_SSL_CIPHER;
   2042       }
   2043     }
   2044   }
   2045 #endif
   2046 
   2047   if(ssl_cafile || ssl_capath) {
   2048     /* tell SSL where to find CA certificates that are used to verify
   2049        the servers certificate. */
   2050     if(!SSL_CTX_load_verify_locations(connssl->ctx, ssl_cafile, ssl_capath)) {
   2051       if(verifypeer) {
   2052         /* Fail if we insist on successfully verifying the server. */
   2053         failf(data, "error setting certificate verify locations:\n"
   2054               "  CAfile: %s\n  CApath: %s",
   2055               ssl_cafile ? ssl_cafile : "none",
   2056               ssl_capath ? ssl_capath : "none");
   2057         return CURLE_SSL_CACERT_BADFILE;
   2058       }
   2059       else {
   2060         /* Just continue with a warning if no strict  certificate verification
   2061            is required. */
   2062         infof(data, "error setting certificate verify locations,"
   2063               " continuing anyway:\n");
   2064       }
   2065     }
   2066     else {
   2067       /* Everything is fine. */
   2068       infof(data, "successfully set certificate verify locations:\n");
   2069     }
   2070     infof(data,
   2071           "  CAfile: %s\n"
   2072           "  CApath: %s\n",
   2073           ssl_cafile ? ssl_cafile : "none",
   2074           ssl_capath ? ssl_capath : "none");
   2075   }
   2076 #ifdef CURL_CA_FALLBACK
   2077   else if(verifypeer) {
   2078     /* verfying the peer without any CA certificates won't
   2079        work so use openssl's built in default as fallback */
   2080     SSL_CTX_set_default_verify_paths(connssl->ctx);
   2081   }
   2082 #endif
   2083 
   2084   if(ssl_crlfile) {
   2085     /* tell SSL where to find CRL file that is used to check certificate
   2086      * revocation */
   2087     lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
   2088                                  X509_LOOKUP_file());
   2089     if(!lookup ||
   2090        (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
   2091       failf(data, "error loading CRL file: %s", ssl_crlfile);
   2092       return CURLE_SSL_CRL_BADFILE;
   2093     }
   2094     else {
   2095       /* Everything is fine. */
   2096       infof(data, "successfully load CRL file:\n");
   2097       X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
   2098                            X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
   2099     }
   2100     infof(data, "  CRLfile: %s\n", ssl_crlfile);
   2101   }
   2102 
   2103   /* Try building a chain using issuers in the trusted store first to avoid
   2104   problems with server-sent legacy intermediates.
   2105   Newer versions of OpenSSL do alternate chain checking by default which
   2106   gives us the same fix without as much of a performance hit (slight), so we
   2107   prefer that if available.
   2108   https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
   2109   */
   2110 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
   2111   if(verifypeer) {
   2112     X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
   2113                          X509_V_FLAG_TRUSTED_FIRST);
   2114   }
   2115 #endif
   2116 
   2117   /* SSL always tries to verify the peer, this only says whether it should
   2118    * fail to connect if the verification fails, or if it should continue
   2119    * anyway. In the latter case the result of the verification is checked with
   2120    * SSL_get_verify_result() below. */
   2121   SSL_CTX_set_verify(connssl->ctx,
   2122                      verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
   2123 
   2124   /* give application a chance to interfere with SSL set up. */
   2125   if(data->set.ssl.fsslctx) {
   2126     result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
   2127                                       data->set.ssl.fsslctxp);
   2128     if(result) {
   2129       failf(data, "error signaled by ssl ctx callback");
   2130       return result;
   2131     }
   2132   }
   2133 
   2134   /* Lets make an SSL structure */
   2135   if(connssl->handle)
   2136     SSL_free(connssl->handle);
   2137   connssl->handle = SSL_new(connssl->ctx);
   2138   if(!connssl->handle) {
   2139     failf(data, "SSL: couldn't create a context (handle)!");
   2140     return CURLE_OUT_OF_MEMORY;
   2141   }
   2142 
   2143 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
   2144     !defined(OPENSSL_NO_OCSP)
   2145   if(SSL_CONN_CONFIG(verifystatus))
   2146     SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
   2147 #endif
   2148 
   2149   SSL_set_connect_state(connssl->handle);
   2150 
   2151   connssl->server_cert = 0x0;
   2152 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
   2153   if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
   2154 #ifdef ENABLE_IPV6
   2155      (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
   2156 #endif
   2157      sni &&
   2158      !SSL_set_tlsext_host_name(connssl->handle, hostname))
   2159     infof(data, "WARNING: failed to configure server name indication (SNI) "
   2160           "TLS extension\n");
   2161 #endif
   2162 
   2163   /* Check if there's a cached ID we can/should use here! */
   2164   if(data->set.general_ssl.sessionid) {
   2165     void *ssl_sessionid = NULL;
   2166 
   2167     Curl_ssl_sessionid_lock(conn);
   2168     if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
   2169       /* we got a session id, use it! */
   2170       if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
   2171         Curl_ssl_sessionid_unlock(conn);
   2172         failf(data, "SSL: SSL_set_session failed: %s",
   2173               ERR_error_string(ERR_get_error(), NULL));
   2174         return CURLE_SSL_CONNECT_ERROR;
   2175       }
   2176       /* Informational message */
   2177       infof (data, "SSL re-using session ID\n");
   2178     }
   2179     Curl_ssl_sessionid_unlock(conn);
   2180   }
   2181 
   2182   if(conn->proxy_ssl[sockindex].use) {
   2183     BIO *const bio = BIO_new(BIO_f_ssl());
   2184     DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
   2185     DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
   2186     DEBUGASSERT(bio != NULL);
   2187     BIO_set_ssl(bio, conn->proxy_ssl[sockindex].handle, FALSE);
   2188     SSL_set_bio(connssl->handle, bio, bio);
   2189   }
   2190   else if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
   2191     /* pass the raw socket into the SSL layers */
   2192     failf(data, "SSL: SSL_set_fd failed: %s",
   2193           ERR_error_string(ERR_get_error(), NULL));
   2194     return CURLE_SSL_CONNECT_ERROR;
   2195   }
   2196 
   2197   connssl->connecting_state = ssl_connect_2;
   2198 
   2199   return CURLE_OK;
   2200 }
   2201 
   2202 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
   2203 {
   2204   struct Curl_easy *data = conn->data;
   2205   int err;
   2206   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
   2207   long * const certverifyresult = SSL_IS_PROXY() ?
   2208     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
   2209   DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
   2210               || ssl_connect_2_reading == connssl->connecting_state
   2211               || ssl_connect_2_writing == connssl->connecting_state);
   2212 
   2213   ERR_clear_error();
   2214 
   2215   err = SSL_connect(connssl->handle);
   2216 
   2217   /* 1  is fine
   2218      0  is "not successful but was shut down controlled"
   2219      <0 is "handshake was not successful, because a fatal error occurred" */
   2220   if(1 != err) {
   2221     int detail = SSL_get_error(connssl->handle, err);
   2222 
   2223     if(SSL_ERROR_WANT_READ == detail) {
   2224       connssl->connecting_state = ssl_connect_2_reading;
   2225       return CURLE_OK;
   2226     }
   2227     else if(SSL_ERROR_WANT_WRITE == detail) {
   2228       connssl->connecting_state = ssl_connect_2_writing;
   2229       return CURLE_OK;
   2230     }
   2231     else {
   2232       /* untreated error */
   2233       unsigned long errdetail;
   2234       char error_buffer[256]=""; /* OpenSSL documents that this must be at
   2235                                     least 256 bytes long. */
   2236       CURLcode result;
   2237       long lerr;
   2238       int lib;
   2239       int reason;
   2240 
   2241       /* the connection failed, we're not waiting for anything else. */
   2242       connssl->connecting_state = ssl_connect_2;
   2243 
   2244       /* Get the earliest error code from the thread's error queue and removes
   2245          the entry. */
   2246       errdetail = ERR_get_error();
   2247 
   2248       /* Extract which lib and reason */
   2249       lib = ERR_GET_LIB(errdetail);
   2250       reason = ERR_GET_REASON(errdetail);
   2251 
   2252       if((lib == ERR_LIB_SSL) &&
   2253          (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
   2254         result = CURLE_SSL_CACERT;
   2255 
   2256         lerr = SSL_get_verify_result(connssl->handle);
   2257         if(lerr != X509_V_OK) {
   2258           *certverifyresult = lerr;
   2259           snprintf(error_buffer, sizeof(error_buffer),
   2260                    "SSL certificate problem: %s",
   2261                    X509_verify_cert_error_string(lerr));
   2262         }
   2263         else
   2264           /* strcpy() is fine here as long as the string fits within
   2265              error_buffer */
   2266           strcpy(error_buffer, "SSL certificate verification failed");
   2267       }
   2268       else {
   2269         result = CURLE_SSL_CONNECT_ERROR;
   2270         ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
   2271       }
   2272 
   2273       /* detail is already set to the SSL error above */
   2274 
   2275       /* If we e.g. use SSLv2 request-method and the server doesn't like us
   2276        * (RST connection etc.), OpenSSL gives no explanation whatsoever and
   2277        * the SO_ERROR is also lost.
   2278        */
   2279       if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
   2280         const char * const hostname = SSL_IS_PROXY() ?
   2281           conn->http_proxy.host.name : conn->host.name;
   2282         const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
   2283         failf(data, "Unknown SSL protocol error in connection to %s:%ld ",
   2284               hostname, port);
   2285         return result;
   2286       }
   2287 
   2288       /* Could be a CERT problem */
   2289       failf(data, "%s", error_buffer);
   2290 
   2291       return result;
   2292     }
   2293   }
   2294   else {
   2295     /* we have been connected fine, we're not waiting for anything else. */
   2296     connssl->connecting_state = ssl_connect_3;
   2297 
   2298     /* Informational message */
   2299     infof(data, "SSL connection using %s / %s\n",
   2300           get_ssl_version_txt(connssl->handle),
   2301           SSL_get_cipher(connssl->handle));
   2302 
   2303 #ifdef HAS_ALPN
   2304     /* Sets data and len to negotiated protocol, len is 0 if no protocol was
   2305      * negotiated
   2306      */
   2307     if(conn->bits.tls_enable_alpn) {
   2308       const unsigned char *neg_protocol;
   2309       unsigned int len;
   2310       SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
   2311       if(len != 0) {
   2312         infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
   2313 
   2314 #ifdef USE_NGHTTP2
   2315         if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
   2316            !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
   2317           conn->negnpn = CURL_HTTP_VERSION_2;
   2318         }
   2319         else
   2320 #endif
   2321         if(len == ALPN_HTTP_1_1_LENGTH &&
   2322            !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
   2323           conn->negnpn = CURL_HTTP_VERSION_1_1;
   2324         }
   2325       }
   2326       else
   2327         infof(data, "ALPN, server did not agree to a protocol\n");
   2328     }
   2329 #endif
   2330 
   2331     return CURLE_OK;
   2332   }
   2333 }
   2334 
   2335 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
   2336 {
   2337   int i, ilen;
   2338 
   2339   if((ilen = (int)len) < 0)
   2340     return 1; /* buffer too big */
   2341 
   2342   i = i2t_ASN1_OBJECT(buf, ilen, a);
   2343 
   2344   if(i >= ilen)
   2345     return 1; /* buffer too small */
   2346 
   2347   return 0;
   2348 }
   2349 
   2350 #define push_certinfo(_label, _num) \
   2351 do {                              \
   2352   long info_len = BIO_get_mem_data(mem, &ptr); \
   2353   Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
   2354   if(1!=BIO_reset(mem))                                          \
   2355     break;                                                       \
   2356 } WHILE_FALSE
   2357 
   2358 static void pubkey_show(struct Curl_easy *data,
   2359                         BIO *mem,
   2360                         int num,
   2361                         const char *type,
   2362                         const char *name,
   2363 #ifdef HAVE_OPAQUE_RSA_DSA_DH
   2364                         const
   2365 #endif
   2366                         BIGNUM *bn)
   2367 {
   2368   char *ptr;
   2369   char namebuf[32];
   2370 
   2371   snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
   2372 
   2373   if(bn)
   2374     BN_print(mem, bn);
   2375   push_certinfo(namebuf, num);
   2376 }
   2377 
   2378 #ifdef HAVE_OPAQUE_RSA_DSA_DH
   2379 #define print_pubkey_BN(_type, _name, _num)              \
   2380   pubkey_show(data, mem, _num, #_type, #_name, _name)
   2381 
   2382 #else
   2383 #define print_pubkey_BN(_type, _name, _num)    \
   2384 do {                              \
   2385   if(_type->_name) { \
   2386     pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
   2387   } \
   2388 } WHILE_FALSE
   2389 #endif
   2390 
   2391 static int X509V3_ext(struct Curl_easy *data,
   2392                       int certnum,
   2393                       CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
   2394 {
   2395   int i;
   2396   size_t j;
   2397 
   2398   if((int)sk_X509_EXTENSION_num(exts) <= 0)
   2399     /* no extensions, bail out */
   2400     return 1;
   2401 
   2402   for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
   2403     ASN1_OBJECT *obj;
   2404     X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
   2405     BUF_MEM *biomem;
   2406     char buf[512];
   2407     char *ptr=buf;
   2408     char namebuf[128];
   2409     BIO *bio_out = BIO_new(BIO_s_mem());
   2410 
   2411     if(!bio_out)
   2412       return 1;
   2413 
   2414     obj = X509_EXTENSION_get_object(ext);
   2415 
   2416     asn1_object_dump(obj, namebuf, sizeof(namebuf));
   2417 
   2418     if(!X509V3_EXT_print(bio_out, ext, 0, 0))
   2419       ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
   2420 
   2421     BIO_get_mem_ptr(bio_out, &biomem);
   2422 
   2423     for(j = 0; j < (size_t)biomem->length; j++) {
   2424       const char *sep="";
   2425       if(biomem->data[j] == '\n') {
   2426         sep=", ";
   2427         j++; /* skip the newline */
   2428       };
   2429       while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
   2430         j++;
   2431       if(j<(size_t)biomem->length)
   2432         ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
   2433                       biomem->data[j]);
   2434     }
   2435 
   2436     Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
   2437 
   2438     BIO_free(bio_out);
   2439 
   2440   }
   2441   return 0; /* all is fine */
   2442 }
   2443 
   2444 static CURLcode get_cert_chain(struct connectdata *conn,
   2445                                struct ssl_connect_data *connssl)
   2446 
   2447 {
   2448   CURLcode result;
   2449   STACK_OF(X509) *sk;
   2450   int i;
   2451   struct Curl_easy *data = conn->data;
   2452   int numcerts;
   2453   BIO *mem;
   2454 
   2455   sk = SSL_get_peer_cert_chain(connssl->handle);
   2456   if(!sk) {
   2457     return CURLE_OUT_OF_MEMORY;
   2458   }
   2459 
   2460   numcerts = sk_X509_num(sk);
   2461 
   2462   result = Curl_ssl_init_certinfo(data, numcerts);
   2463   if(result) {
   2464     return result;
   2465   }
   2466 
   2467   mem = BIO_new(BIO_s_mem());
   2468 
   2469   for(i = 0; i < numcerts; i++) {
   2470     ASN1_INTEGER *num;
   2471     X509 *x = sk_X509_value(sk, i);
   2472     EVP_PKEY *pubkey=NULL;
   2473     int j;
   2474     char *ptr;
   2475     CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
   2476 
   2477     X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
   2478     push_certinfo("Subject", i);
   2479 
   2480     X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
   2481     push_certinfo("Issuer", i);
   2482 
   2483     BIO_printf(mem, "%lx", X509_get_version(x));
   2484     push_certinfo("Version", i);
   2485 
   2486     num = X509_get_serialNumber(x);
   2487     if(num->type == V_ASN1_NEG_INTEGER)
   2488       BIO_puts(mem, "-");
   2489     for(j = 0; j < num->length; j++)
   2490       BIO_printf(mem, "%02x", num->data[j]);
   2491     push_certinfo("Serial Number", i);
   2492 
   2493 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
   2494     {
   2495       const X509_ALGOR *palg = NULL;
   2496       ASN1_STRING *a = ASN1_STRING_new();
   2497       if(a) {
   2498         X509_get0_signature(&psig, &palg, x);
   2499         X509_signature_print(mem, palg, a);
   2500         ASN1_STRING_free(a);
   2501 
   2502         if(palg) {
   2503           i2a_ASN1_OBJECT(mem, palg->algorithm);
   2504           push_certinfo("Public Key Algorithm", i);
   2505         }
   2506       }
   2507       X509V3_ext(data, i, X509_get0_extensions(x));
   2508     }
   2509 #else
   2510     {
   2511       /* before OpenSSL 1.0.2 */
   2512       X509_CINF *cinf = x->cert_info;
   2513 
   2514       i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
   2515       push_certinfo("Signature Algorithm", i);
   2516 
   2517       i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
   2518       push_certinfo("Public Key Algorithm", i);
   2519 
   2520       X509V3_ext(data, i, cinf->extensions);
   2521 
   2522       psig = x->signature;
   2523     }
   2524 #endif
   2525 
   2526     ASN1_TIME_print(mem, X509_get0_notBefore(x));
   2527     push_certinfo("Start date", i);
   2528 
   2529     ASN1_TIME_print(mem, X509_get0_notAfter(x));
   2530     push_certinfo("Expire date", i);
   2531 
   2532     pubkey = X509_get_pubkey(x);
   2533     if(!pubkey)
   2534       infof(data, "   Unable to load public key\n");
   2535     else {
   2536       int pktype;
   2537 #ifdef HAVE_OPAQUE_EVP_PKEY
   2538       pktype = EVP_PKEY_id(pubkey);
   2539 #else
   2540       pktype = pubkey->type;
   2541 #endif
   2542       switch(pktype) {
   2543       case EVP_PKEY_RSA:
   2544       {
   2545         RSA *rsa;
   2546 #ifdef HAVE_OPAQUE_EVP_PKEY
   2547         rsa = EVP_PKEY_get0_RSA(pubkey);
   2548 #else
   2549         rsa = pubkey->pkey.rsa;
   2550 #endif
   2551 
   2552 #ifdef HAVE_OPAQUE_RSA_DSA_DH
   2553         {
   2554           const BIGNUM *n;
   2555           const BIGNUM *e;
   2556           const BIGNUM *d;
   2557           const BIGNUM *p;
   2558           const BIGNUM *q;
   2559           const BIGNUM *dmp1;
   2560           const BIGNUM *dmq1;
   2561           const BIGNUM *iqmp;
   2562 
   2563           RSA_get0_key(rsa, &n, &e, &d);
   2564           RSA_get0_factors(rsa, &p, &q);
   2565           RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
   2566           BN_print(mem, n);
   2567           push_certinfo("RSA Public Key", i);
   2568           print_pubkey_BN(rsa, n, i);
   2569           print_pubkey_BN(rsa, e, i);
   2570           print_pubkey_BN(rsa, d, i);
   2571           print_pubkey_BN(rsa, p, i);
   2572           print_pubkey_BN(rsa, q, i);
   2573           print_pubkey_BN(rsa, dmp1, i);
   2574           print_pubkey_BN(rsa, dmq1, i);
   2575           print_pubkey_BN(rsa, iqmp, i);
   2576         }
   2577 #else
   2578         BIO_printf(mem, "%d", BN_num_bits(rsa->n));
   2579         push_certinfo("RSA Public Key", i);
   2580         print_pubkey_BN(rsa, n, i);
   2581         print_pubkey_BN(rsa, e, i);
   2582         print_pubkey_BN(rsa, d, i);
   2583         print_pubkey_BN(rsa, p, i);
   2584         print_pubkey_BN(rsa, q, i);
   2585         print_pubkey_BN(rsa, dmp1, i);
   2586         print_pubkey_BN(rsa, dmq1, i);
   2587         print_pubkey_BN(rsa, iqmp, i);
   2588 #endif
   2589 
   2590         break;
   2591       }
   2592       case EVP_PKEY_DSA:
   2593       {
   2594         DSA *dsa;
   2595 #ifdef HAVE_OPAQUE_EVP_PKEY
   2596         dsa = EVP_PKEY_get0_DSA(pubkey);
   2597 #else
   2598         dsa = pubkey->pkey.dsa;
   2599 #endif
   2600 #ifdef HAVE_OPAQUE_RSA_DSA_DH
   2601         {
   2602           const BIGNUM *p;
   2603           const BIGNUM *q;
   2604           const BIGNUM *g;
   2605           const BIGNUM *priv_key;
   2606           const BIGNUM *pub_key;
   2607 
   2608           DSA_get0_pqg(dsa, &p, &q, &g);
   2609           DSA_get0_key(dsa, &pub_key, &priv_key);
   2610 
   2611           print_pubkey_BN(dsa, p, i);
   2612           print_pubkey_BN(dsa, q, i);
   2613           print_pubkey_BN(dsa, g, i);
   2614           print_pubkey_BN(dsa, priv_key, i);
   2615           print_pubkey_BN(dsa, pub_key, i);
   2616         }
   2617 #else
   2618         print_pubkey_BN(dsa, p, i);
   2619         print_pubkey_BN(dsa, q, i);
   2620         print_pubkey_BN(dsa, g, i);
   2621         print_pubkey_BN(dsa, priv_key, i);
   2622         print_pubkey_BN(dsa, pub_key, i);
   2623 #endif
   2624         break;
   2625       }
   2626       case EVP_PKEY_DH:
   2627       {
   2628         DH *dh;
   2629 #ifdef HAVE_OPAQUE_EVP_PKEY
   2630         dh = EVP_PKEY_get0_DH(pubkey);
   2631 #else
   2632         dh = pubkey->pkey.dh;
   2633 #endif
   2634 #ifdef HAVE_OPAQUE_RSA_DSA_DH
   2635         {
   2636           const BIGNUM *p;
   2637           const BIGNUM *q;
   2638           const BIGNUM *g;
   2639           const BIGNUM *priv_key;
   2640           const BIGNUM *pub_key;
   2641           DH_get0_pqg(dh, &p, &q, &g);
   2642           DH_get0_key(dh, &pub_key, &priv_key);
   2643           print_pubkey_BN(dh, p, i);
   2644           print_pubkey_BN(dh, q, i);
   2645           print_pubkey_BN(dh, g, i);
   2646           print_pubkey_BN(dh, priv_key, i);
   2647           print_pubkey_BN(dh, pub_key, i);
   2648        }
   2649 #else
   2650         print_pubkey_BN(dh, p, i);
   2651         print_pubkey_BN(dh, g, i);
   2652         print_pubkey_BN(dh, priv_key, i);
   2653         print_pubkey_BN(dh, pub_key, i);
   2654 #endif
   2655         break;
   2656       }
   2657 #if 0
   2658       case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
   2659         /* left TODO */
   2660         break;
   2661 #endif
   2662       }
   2663       EVP_PKEY_free(pubkey);
   2664     }
   2665 
   2666     if(psig) {
   2667       for(j = 0; j < psig->length; j++)
   2668         BIO_printf(mem, "%02x:", psig->data[j]);
   2669       push_certinfo("Signature", i);
   2670     }
   2671 
   2672     PEM_write_bio_X509(mem, x);
   2673     push_certinfo("Cert", i);
   2674   }
   2675 
   2676   BIO_free(mem);
   2677 
   2678   return CURLE_OK;
   2679 }
   2680 
   2681 /*
   2682  * Heavily modified from:
   2683  * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
   2684  */
   2685 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
   2686                                     const char *pinnedpubkey)
   2687 {
   2688   /* Scratch */
   2689   int len1 = 0, len2 = 0;
   2690   unsigned char *buff1 = NULL, *temp = NULL;
   2691 
   2692   /* Result is returned to caller */
   2693   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
   2694 
   2695   /* if a path wasn't specified, don't pin */
   2696   if(!pinnedpubkey)
   2697     return CURLE_OK;
   2698 
   2699   if(!cert)
   2700     return result;
   2701 
   2702   do {
   2703     /* Begin Gyrations to get the subjectPublicKeyInfo     */
   2704     /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
   2705 
   2706     /* https://groups.google.com/group/mailing.openssl.users/browse_thread
   2707      /thread/d61858dae102c6c7 */
   2708     len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
   2709     if(len1 < 1)
   2710       break; /* failed */
   2711 
   2712     /* https://www.openssl.org/docs/crypto/buffer.html */
   2713     buff1 = temp = malloc(len1);
   2714     if(!buff1)
   2715       break; /* failed */
   2716 
   2717     /* https://www.openssl.org/docs/crypto/d2i_X509.html */
   2718     len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
   2719 
   2720     /*
   2721      * These checks are verifying we got back the same values as when we
   2722      * sized the buffer. It's pretty weak since they should always be the
   2723      * same. But it gives us something to test.
   2724      */
   2725     if((len1 != len2) || !temp || ((temp - buff1) != len1))
   2726       break; /* failed */
   2727 
   2728     /* End Gyrations */
   2729 
   2730     /* The one good exit point */
   2731     result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
   2732   } while(0);
   2733 
   2734   /* https://www.openssl.org/docs/crypto/buffer.html */
   2735   if(buff1)
   2736     free(buff1);
   2737 
   2738   return result;
   2739 }
   2740 
   2741 /*
   2742  * Get the server cert, verify it and show it etc, only call failf() if the
   2743  * 'strict' argument is TRUE as otherwise all this is for informational
   2744  * purposes only!
   2745  *
   2746  * We check certificates to authenticate the server; otherwise we risk
   2747  * man-in-the-middle attack.
   2748  */
   2749 static CURLcode servercert(struct connectdata *conn,
   2750                            struct ssl_connect_data *connssl,
   2751                            bool strict)
   2752 {
   2753   CURLcode result = CURLE_OK;
   2754   int rc;
   2755   long lerr, len;
   2756   struct Curl_easy *data = conn->data;
   2757   X509 *issuer;
   2758   FILE *fp;
   2759   char *buffer = data->state.buffer;
   2760   const char *ptr;
   2761   long * const certverifyresult = SSL_IS_PROXY() ?
   2762     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
   2763   BIO *mem = BIO_new(BIO_s_mem());
   2764 
   2765   if(data->set.ssl.certinfo)
   2766     /* we've been asked to gather certificate info! */
   2767     (void)get_cert_chain(conn, connssl);
   2768 
   2769   connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
   2770   if(!connssl->server_cert) {
   2771     if(!strict)
   2772       return CURLE_OK;
   2773 
   2774     failf(data, "SSL: couldn't get peer certificate!");
   2775     return CURLE_PEER_FAILED_VERIFICATION;
   2776   }
   2777 
   2778   infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
   2779 
   2780   rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
   2781                          buffer, BUFSIZE);
   2782   infof(data, " subject: %s\n", rc?"[NONE]":buffer);
   2783 
   2784   ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
   2785   len = BIO_get_mem_data(mem, (char **) &ptr);
   2786   infof(data, " start date: %.*s\n", len, ptr);
   2787   rc = BIO_reset(mem);
   2788 
   2789   ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
   2790   len = BIO_get_mem_data(mem, (char **) &ptr);
   2791   infof(data, " expire date: %.*s\n", len, ptr);
   2792   rc = BIO_reset(mem);
   2793 
   2794   BIO_free(mem);
   2795 
   2796   if(SSL_CONN_CONFIG(verifyhost)) {
   2797     result = verifyhost(conn, connssl->server_cert);
   2798     if(result) {
   2799       X509_free(connssl->server_cert);
   2800       connssl->server_cert = NULL;
   2801       return result;
   2802     }
   2803   }
   2804 
   2805   rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
   2806                          buffer, BUFSIZE);
   2807   if(rc) {
   2808     if(strict)
   2809       failf(data, "SSL: couldn't get X509-issuer name!");
   2810     result = CURLE_SSL_CONNECT_ERROR;
   2811   }
   2812   else {
   2813     infof(data, " issuer: %s\n", buffer);
   2814 
   2815     /* We could do all sorts of certificate verification stuff here before
   2816        deallocating the certificate. */
   2817 
   2818     /* e.g. match issuer name with provided issuer certificate */
   2819     if(SSL_SET_OPTION(issuercert)) {
   2820       fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
   2821       if(!fp) {
   2822         if(strict)
   2823           failf(data, "SSL: Unable to open issuer cert (%s)",
   2824                 SSL_SET_OPTION(issuercert));
   2825         X509_free(connssl->server_cert);
   2826         connssl->server_cert = NULL;
   2827         return CURLE_SSL_ISSUER_ERROR;
   2828       }
   2829 
   2830       issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
   2831       if(!issuer) {
   2832         if(strict)
   2833           failf(data, "SSL: Unable to read issuer cert (%s)",
   2834                 SSL_SET_OPTION(issuercert));
   2835         X509_free(connssl->server_cert);
   2836         X509_free(issuer);
   2837         fclose(fp);
   2838         return CURLE_SSL_ISSUER_ERROR;
   2839       }
   2840 
   2841       fclose(fp);
   2842 
   2843       if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
   2844         if(strict)
   2845           failf(data, "SSL: Certificate issuer check failed (%s)",
   2846                 SSL_SET_OPTION(issuercert));
   2847         X509_free(connssl->server_cert);
   2848         X509_free(issuer);
   2849         connssl->server_cert = NULL;
   2850         return CURLE_SSL_ISSUER_ERROR;
   2851       }
   2852 
   2853       infof(data, " SSL certificate issuer check ok (%s)\n",
   2854             SSL_SET_OPTION(issuercert));
   2855       X509_free(issuer);
   2856     }
   2857 
   2858     lerr = *certverifyresult = SSL_get_verify_result(connssl->handle);
   2859 
   2860     if(*certverifyresult != X509_V_OK) {
   2861       if(SSL_CONN_CONFIG(verifypeer)) {
   2862         /* We probably never reach this, because SSL_connect() will fail
   2863            and we return earlier if verifypeer is set? */
   2864         if(strict)
   2865           failf(data, "SSL certificate verify result: %s (%ld)",
   2866                 X509_verify_cert_error_string(lerr), lerr);
   2867         result = CURLE_PEER_FAILED_VERIFICATION;
   2868       }
   2869       else
   2870         infof(data, " SSL certificate verify result: %s (%ld),"
   2871               " continuing anyway.\n",
   2872               X509_verify_cert_error_string(lerr), lerr);
   2873     }
   2874     else
   2875       infof(data, " SSL certificate verify ok.\n");
   2876   }
   2877 
   2878 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
   2879     !defined(OPENSSL_NO_OCSP)
   2880   if(SSL_CONN_CONFIG(verifystatus)) {
   2881     result = verifystatus(conn, connssl);
   2882     if(result) {
   2883       X509_free(connssl->server_cert);
   2884       connssl->server_cert = NULL;
   2885       return result;
   2886     }
   2887   }
   2888 #endif
   2889 
   2890   if(!strict)
   2891     /* when not strict, we don't bother about the verify cert problems */
   2892     result = CURLE_OK;
   2893 
   2894   ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
   2895   if(!result && ptr) {
   2896     result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
   2897     if(result)
   2898       failf(data, "SSL: public key does not match pinned public key!");
   2899   }
   2900 
   2901   X509_free(connssl->server_cert);
   2902   connssl->server_cert = NULL;
   2903   connssl->connecting_state = ssl_connect_done;
   2904 
   2905   return result;
   2906 }
   2907 
   2908 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
   2909 {
   2910   CURLcode result = CURLE_OK;
   2911   struct Curl_easy *data = conn->data;
   2912   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
   2913 
   2914   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
   2915 
   2916   if(data->set.general_ssl.sessionid) {
   2917     bool incache;
   2918     SSL_SESSION *our_ssl_sessionid;
   2919     void *old_ssl_sessionid = NULL;
   2920 
   2921     our_ssl_sessionid = SSL_get1_session(connssl->handle);
   2922 
   2923     /* SSL_get1_session() will increment the reference count and the session
   2924         will stay in memory until explicitly freed with SSL_SESSION_free(3),
   2925         regardless of its state. */
   2926 
   2927     Curl_ssl_sessionid_lock(conn);
   2928     incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
   2929                                       sockindex));
   2930     if(incache) {
   2931       if(old_ssl_sessionid != our_ssl_sessionid) {
   2932         infof(data, "old SSL session ID is stale, removing\n");
   2933         Curl_ssl_delsessionid(conn, old_ssl_sessionid);
   2934         incache = FALSE;
   2935       }
   2936     }
   2937 
   2938     if(!incache) {
   2939       result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
   2940                                       0 /* unknown size */, sockindex);
   2941       if(result) {
   2942         Curl_ssl_sessionid_unlock(conn);
   2943         failf(data, "failed to store ssl session");
   2944         return result;
   2945       }
   2946     }
   2947     else {
   2948       /* Session was incache, so refcount already incremented earlier.
   2949         * Avoid further increments with each SSL_get1_session() call.
   2950         * This does not free the session as refcount remains > 0
   2951         */
   2952       SSL_SESSION_free(our_ssl_sessionid);
   2953     }
   2954     Curl_ssl_sessionid_unlock(conn);
   2955   }
   2956 
   2957   /*
   2958    * We check certificates to authenticate the server; otherwise we risk
   2959    * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
   2960    * verify the peer ignore faults and failures from the server cert
   2961    * operations.
   2962    */
   2963 
   2964   result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
   2965                                       SSL_CONN_CONFIG(verifyhost)));
   2966 
   2967   if(!result)
   2968     connssl->connecting_state = ssl_connect_done;
   2969 
   2970   return result;
   2971 }
   2972 
   2973 static Curl_recv ossl_recv;
   2974 static Curl_send ossl_send;
   2975 
   2976 static CURLcode ossl_connect_common(struct connectdata *conn,
   2977                                     int sockindex,
   2978                                     bool nonblocking,
   2979                                     bool *done)
   2980 {
   2981   CURLcode result;
   2982   struct Curl_easy *data = conn->data;
   2983   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
   2984   curl_socket_t sockfd = conn->sock[sockindex];
   2985   time_t timeout_ms;
   2986   int what;
   2987 
   2988   /* check if the connection has already been established */
   2989   if(ssl_connection_complete == connssl->state) {
   2990     *done = TRUE;
   2991     return CURLE_OK;
   2992   }
   2993 
   2994   if(ssl_connect_1 == connssl->connecting_state) {
   2995     /* Find out how much more time we're allowed */
   2996     timeout_ms = Curl_timeleft(data, NULL, TRUE);
   2997 
   2998     if(timeout_ms < 0) {
   2999       /* no need to continue if time already is up */
   3000       failf(data, "SSL connection timeout");
   3001       return CURLE_OPERATION_TIMEDOUT;
   3002     }
   3003 
   3004     result = ossl_connect_step1(conn, sockindex);
   3005     if(result)
   3006       return result;
   3007   }
   3008 
   3009   while(ssl_connect_2 == connssl->connecting_state ||
   3010         ssl_connect_2_reading == connssl->connecting_state ||
   3011         ssl_connect_2_writing == connssl->connecting_state) {
   3012 
   3013     /* check allowed time left */
   3014     timeout_ms = Curl_timeleft(data, NULL, TRUE);
   3015 
   3016     if(timeout_ms < 0) {
   3017       /* no need to continue if time already is up */
   3018       failf(data, "SSL connection timeout");
   3019       return CURLE_OPERATION_TIMEDOUT;
   3020     }
   3021 
   3022     /* if ssl is expecting something, check if it's available. */
   3023     if(connssl->connecting_state == ssl_connect_2_reading ||
   3024        connssl->connecting_state == ssl_connect_2_writing) {
   3025 
   3026       curl_socket_t writefd = ssl_connect_2_writing==
   3027         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
   3028       curl_socket_t readfd = ssl_connect_2_reading==
   3029         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
   3030 
   3031       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
   3032                                nonblocking?0:timeout_ms);
   3033       if(what < 0) {
   3034         /* fatal error */
   3035         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
   3036         return CURLE_SSL_CONNECT_ERROR;
   3037       }
   3038       else if(0 == what) {
   3039         if(nonblocking) {
   3040           *done = FALSE;
   3041           return CURLE_OK;
   3042         }
   3043         else {
   3044           /* timeout */
   3045           failf(data, "SSL connection timeout");
   3046           return CURLE_OPERATION_TIMEDOUT;
   3047         }
   3048       }
   3049       /* socket is readable or writable */
   3050     }
   3051 
   3052     /* Run transaction, and return to the caller if it failed or if this
   3053      * connection is done nonblocking and this loop would execute again. This
   3054      * permits the owner of a multi handle to abort a connection attempt
   3055      * before step2 has completed while ensuring that a client using select()
   3056      * or epoll() will always have a valid fdset to wait on.
   3057      */
   3058     result = ossl_connect_step2(conn, sockindex);
   3059     if(result || (nonblocking &&
   3060                   (ssl_connect_2 == connssl->connecting_state ||
   3061                    ssl_connect_2_reading == connssl->connecting_state ||
   3062                    ssl_connect_2_writing == connssl->connecting_state)))
   3063       return result;
   3064 
   3065   } /* repeat step2 until all transactions are done. */
   3066 
   3067   if(ssl_connect_3 == connssl->connecting_state) {
   3068     result = ossl_connect_step3(conn, sockindex);
   3069     if(result)
   3070       return result;
   3071   }
   3072 
   3073   if(ssl_connect_done == connssl->connecting_state) {
   3074     connssl->state = ssl_connection_complete;
   3075     conn->recv[sockindex] = ossl_recv;
   3076     conn->send[sockindex] = ossl_send;
   3077     *done = TRUE;
   3078   }
   3079   else
   3080     *done = FALSE;
   3081 
   3082   /* Reset our connect state machine */
   3083   connssl->connecting_state = ssl_connect_1;
   3084 
   3085   return CURLE_OK;
   3086 }
   3087 
   3088 CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
   3089                                        int sockindex,
   3090                                        bool *done)
   3091 {
   3092   return ossl_connect_common(conn, sockindex, TRUE, done);
   3093 }
   3094 
   3095 CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
   3096 {
   3097   CURLcode result;
   3098   bool done = FALSE;
   3099 
   3100   result = ossl_connect_common(conn, sockindex, FALSE, &done);
   3101   if(result)
   3102     return result;
   3103 
   3104   DEBUGASSERT(done);
   3105 
   3106   return CURLE_OK;
   3107 }
   3108 
   3109 bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
   3110 {
   3111   if(conn->ssl[connindex].handle)
   3112     /* SSL is in use */
   3113     return (0 != SSL_pending(conn->ssl[connindex].handle) ||
   3114            (conn->proxy_ssl[connindex].handle &&
   3115             0 != SSL_pending(conn->proxy_ssl[connindex].handle))) ?
   3116            TRUE : FALSE;
   3117   else
   3118     return FALSE;
   3119 }
   3120 
   3121 static ssize_t ossl_send(struct connectdata *conn,
   3122                          int sockindex,
   3123                          const void *mem,
   3124                          size_t len,
   3125                          CURLcode *curlcode)
   3126 {
   3127   /* SSL_write() is said to return 'int' while write() and send() returns
   3128      'size_t' */
   3129   int err;
   3130   char error_buffer[256]; /* OpenSSL documents that this must be at least 256
   3131                              bytes long. */
   3132   unsigned long sslerror;
   3133   int memlen;
   3134   int rc;
   3135 
   3136   ERR_clear_error();
   3137 
   3138   memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
   3139   rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
   3140 
   3141   if(rc <= 0) {
   3142     err = SSL_get_error(conn->ssl[sockindex].handle, rc);
   3143 
   3144     switch(err) {
   3145     case SSL_ERROR_WANT_READ:
   3146     case SSL_ERROR_WANT_WRITE:
   3147       /* The operation did not complete; the same TLS/SSL I/O function
   3148          should be called again later. This is basically an EWOULDBLOCK
   3149          equivalent. */
   3150       *curlcode = CURLE_AGAIN;
   3151       return -1;
   3152     case SSL_ERROR_SYSCALL:
   3153       failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
   3154             SOCKERRNO);
   3155       *curlcode = CURLE_SEND_ERROR;
   3156       return -1;
   3157     case SSL_ERROR_SSL:
   3158       /*  A failure in the SSL library occurred, usually a protocol error.
   3159           The OpenSSL error queue contains more information on the error. */
   3160       sslerror = ERR_get_error();
   3161       if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
   3162          ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
   3163          conn->ssl[sockindex].state == ssl_connection_complete &&
   3164          conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
   3165         char ver[120];
   3166         Curl_ossl_version(ver, 120);
   3167         failf(conn->data, "Error: %s does not support double SSL tunneling.",
   3168               ver);
   3169       }
   3170       else
   3171         failf(conn->data, "SSL_write() error: %s",
   3172               ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
   3173       *curlcode = CURLE_SEND_ERROR;
   3174       return -1;
   3175     }
   3176     /* a true error */
   3177     failf(conn->data, "SSL_write() return error %d", err);
   3178     *curlcode = CURLE_SEND_ERROR;
   3179     return -1;
   3180   }
   3181   *curlcode = CURLE_OK;
   3182   return (ssize_t)rc; /* number of bytes */
   3183 }
   3184 
   3185 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
   3186                          int num,                  /* socketindex */
   3187                          char *buf,                /* store read data here */
   3188                          size_t buffersize,        /* max amount to read */
   3189                          CURLcode *curlcode)
   3190 {
   3191   char error_buffer[256]; /* OpenSSL documents that this must be at
   3192                              least 256 bytes long. */
   3193   unsigned long sslerror;
   3194   ssize_t nread;
   3195   int buffsize;
   3196 
   3197   ERR_clear_error();
   3198 
   3199   buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
   3200   nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
   3201   if(nread <= 0) {
   3202     /* failed SSL_read */
   3203     int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
   3204 
   3205     switch(err) {
   3206     case SSL_ERROR_NONE: /* this is not an error */
   3207     case SSL_ERROR_ZERO_RETURN: /* no more data */
   3208       break;
   3209     case SSL_ERROR_WANT_READ:
   3210     case SSL_ERROR_WANT_WRITE:
   3211       /* there's data pending, re-invoke SSL_read() */
   3212       *curlcode = CURLE_AGAIN;
   3213       return -1;
   3214     default:
   3215       /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
   3216          value/errno" */
   3217       /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
   3218       sslerror = ERR_get_error();
   3219       if((nread < 0) || sslerror) {
   3220         /* If the return code was negative or there actually is an error in the
   3221            queue */
   3222         failf(conn->data, "SSL read: %s, errno %d",
   3223               ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)),
   3224               SOCKERRNO);
   3225         *curlcode = CURLE_RECV_ERROR;
   3226         return -1;
   3227       }
   3228     }
   3229   }
   3230   return nread;
   3231 }
   3232 
   3233 size_t Curl_ossl_version(char *buffer, size_t size)
   3234 {
   3235 #ifdef OPENSSL_IS_BORINGSSL
   3236   return snprintf(buffer, size, OSSL_PACKAGE);
   3237 #else /* OPENSSL_IS_BORINGSSL */
   3238   char sub[3];
   3239   unsigned long ssleay_value;
   3240   sub[2]='\0';
   3241   sub[1]='\0';
   3242   ssleay_value=OpenSSL_version_num();
   3243   if(ssleay_value < 0x906000) {
   3244     ssleay_value=SSLEAY_VERSION_NUMBER;
   3245     sub[0]='\0';
   3246   }
   3247   else {
   3248     if(ssleay_value&0xff0) {
   3249       int minor_ver = (ssleay_value >> 4) & 0xff;
   3250       if(minor_ver > 26) {
   3251         /* handle extended version introduced for 0.9.8za */
   3252         sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
   3253         sub[0] = 'z';
   3254       }
   3255       else {
   3256         sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
   3257       }
   3258     }
   3259     else
   3260       sub[0]='\0';
   3261   }
   3262 
   3263   return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
   3264                   OSSL_PACKAGE,
   3265                   (ssleay_value>>28)&0xf,
   3266                   (ssleay_value>>20)&0xff,
   3267                   (ssleay_value>>12)&0xff,
   3268                   sub);
   3269 #endif /* OPENSSL_IS_BORINGSSL */
   3270 }
   3271 
   3272 /* can be called with data == NULL */
   3273 int Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
   3274                      size_t length)
   3275 {
   3276   if(data) {
   3277     if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
   3278       return 1; /* couldn't seed for some reason */
   3279   }
   3280   else {
   3281     if(!rand_enough())
   3282       return 1;
   3283   }
   3284   RAND_bytes(entropy, curlx_uztosi(length));
   3285   return 0; /* 0 as in no problem */
   3286 }
   3287 
   3288 void Curl_ossl_md5sum(unsigned char *tmp, /* input */
   3289                       size_t tmplen,
   3290                       unsigned char *md5sum /* output */,
   3291                       size_t unused)
   3292 {
   3293   MD5_CTX MD5pw;
   3294   (void)unused;
   3295   MD5_Init(&MD5pw);
   3296   MD5_Update(&MD5pw, tmp, tmplen);
   3297   MD5_Final(md5sum, &MD5pw);
   3298 }
   3299 
   3300 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
   3301 void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
   3302                       size_t tmplen,
   3303                       unsigned char *sha256sum /* output */,
   3304                       size_t unused)
   3305 {
   3306   SHA256_CTX SHA256pw;
   3307   (void)unused;
   3308   SHA256_Init(&SHA256pw);
   3309   SHA256_Update(&SHA256pw, tmp, tmplen);
   3310   SHA256_Final(sha256sum, &SHA256pw);
   3311 }
   3312 #endif
   3313 
   3314 bool Curl_ossl_cert_status_request(void)
   3315 {
   3316 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
   3317     !defined(OPENSSL_NO_OCSP)
   3318   return TRUE;
   3319 #else
   3320   return FALSE;
   3321 #endif
   3322 }
   3323 #endif /* USE_OPENSSL */
   3324