openssl.c
Go to the documentation of this file.
00001 /***************************************************************************
00002  *                                  _   _ ____  _
00003  *  Project                     ___| | | |  _ \| |
00004  *                             / __| | | | |_) | |
00005  *                            | (__| |_| |  _ <| |___
00006  *                             \___|\___/|_| \_\_____|
00007  *
00008  * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
00009  *
00010  * This software is licensed as described in the file COPYING, which
00011  * you should have received as part of this distribution. The terms
00012  * are also available at https://curl.haxx.se/docs/copyright.html.
00013  *
00014  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
00015  * copies of the Software, and permit persons to whom the Software is
00016  * furnished to do so, under the terms of the COPYING file.
00017  *
00018  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
00019  * KIND, either express or implied.
00020  *
00021  ***************************************************************************/
00022 
00023 /*
00024  * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
00025  * but vtls.c should ever call or use these functions.
00026  */
00027 
00028 /*
00029  * The original SSLeay-using code for curl was written by Linas Vepstas and
00030  * Sampo Kellomaki 1998.
00031  */
00032 
00033 #include "curl_setup.h"
00034 
00035 #ifdef USE_OPENSSL
00036 
00037 #ifdef HAVE_LIMITS_H
00038 #include <limits.h>
00039 #endif
00040 
00041 #include "urldata.h"
00042 #include "sendf.h"
00043 #include "formdata.h" /* for the boundary function */
00044 #include "url.h" /* for the ssl config check function */
00045 #include "inet_pton.h"
00046 #include "openssl.h"
00047 #include "connect.h"
00048 #include "slist.h"
00049 #include "select.h"
00050 #include "vtls.h"
00051 #include "strcase.h"
00052 #include "hostcheck.h"
00053 #include "curl_printf.h"
00054 
00055 #include <openssl/ssl.h>
00056 #include <openssl/rand.h>
00057 #include <openssl/x509v3.h>
00058 #include <openssl/dsa.h>
00059 #include <openssl/dh.h>
00060 #include <openssl/err.h>
00061 #include <openssl/md5.h>
00062 #include <openssl/conf.h>
00063 #include <openssl/bn.h>
00064 #include <openssl/rsa.h>
00065 
00066 #ifdef HAVE_OPENSSL_PKCS12_H
00067 #include <openssl/pkcs12.h>
00068 #endif
00069 
00070 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
00071 #include <openssl/ocsp.h>
00072 #endif
00073 
00074 #include "warnless.h"
00075 #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
00076 
00077 /* The last #include files should be: */
00078 #include "curl_memory.h"
00079 #include "memdebug.h"
00080 
00081 #ifndef OPENSSL_VERSION_NUMBER
00082 #error "OPENSSL_VERSION_NUMBER not defined"
00083 #endif
00084 
00085 #if defined(HAVE_OPENSSL_ENGINE_H)
00086 #include <openssl/ui.h>
00087 #endif
00088 
00089 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
00090 #define SSL_METHOD_QUAL const
00091 #else
00092 #define SSL_METHOD_QUAL
00093 #endif
00094 
00095 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
00096 #define HAVE_ERR_REMOVE_THREAD_STATE 1
00097 #endif
00098 
00099 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
00100   OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
00101 #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
00102 #define OPENSSL_NO_SSL2
00103 #endif
00104 
00105 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
00106   !defined(LIBRESSL_VERSION_NUMBER)
00107 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
00108 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
00109 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
00110 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
00111 #define CONST_EXTS const
00112 #define CONST_ASN1_BIT_STRING const
00113 #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
00114 #else
00115 /* For OpenSSL before 1.1.0 */
00116 #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
00117 #define X509_get0_notBefore(x) X509_get_notBefore(x)
00118 #define X509_get0_notAfter(x) X509_get_notAfter(x)
00119 #define CONST_EXTS /* nope */
00120 #define CONST_ASN1_BIT_STRING /* nope */
00121 #ifdef LIBRESSL_VERSION_NUMBER
00122 static unsigned long OpenSSL_version_num(void)
00123 {
00124   return LIBRESSL_VERSION_NUMBER;
00125 }
00126 #else
00127 #define OpenSSL_version_num() SSLeay()
00128 #endif
00129 #endif
00130 
00131 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
00132   !defined(LIBRESSL_VERSION_NUMBER)
00133 #define HAVE_X509_GET0_SIGNATURE 1
00134 #endif
00135 
00136 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
00137   OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
00138   !defined(OPENSSL_NO_COMP)
00139 #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
00140 #endif
00141 
00142 #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
00143 /* not present in older OpenSSL */
00144 #define OPENSSL_load_builtin_modules(x)
00145 #endif
00146 
00147 #if defined(LIBRESSL_VERSION_NUMBER)
00148 #define OSSL_PACKAGE "LibreSSL"
00149 #elif defined(OPENSSL_IS_BORINGSSL)
00150 #define OSSL_PACKAGE "BoringSSL"
00151 #else
00152 #define OSSL_PACKAGE "OpenSSL"
00153 #endif
00154 
00155 /*
00156  * Number of bytes to read from the random number seed file. This must be
00157  * a finite value (because some entropy "files" like /dev/urandom have
00158  * an infinite length), but must be large enough to provide enough
00159  * entopy to properly seed OpenSSL's PRNG.
00160  */
00161 #define RAND_LOAD_LENGTH 1024
00162 
00163 static int passwd_callback(char *buf, int num, int encrypting,
00164                            void *global_passwd)
00165 {
00166   DEBUGASSERT(0 == encrypting);
00167 
00168   if(!encrypting) {
00169     int klen = curlx_uztosi(strlen((char *)global_passwd));
00170     if(num > klen) {
00171       memcpy(buf, global_passwd, klen+1);
00172       return klen;
00173     }
00174   }
00175   return 0;
00176 }
00177 
00178 /*
00179  * rand_enough() returns TRUE if we have seeded the random engine properly.
00180  */
00181 static bool rand_enough(void)
00182 {
00183   return (0 != RAND_status()) ? TRUE : FALSE;
00184 }
00185 
00186 static CURLcode Curl_ossl_seed(struct Curl_easy *data)
00187 {
00188   /* we have the "SSL is seeded" boolean static to prevent multiple
00189      time-consuming seedings in vain */
00190   static bool ssl_seeded = FALSE;
00191   char *buf = data->state.buffer; /* point to the big buffer */
00192   int nread=0;
00193 
00194   if(ssl_seeded)
00195     return CURLE_OK;
00196 
00197   if(rand_enough()) {
00198     /* OpenSSL 1.1.0+ will return here */
00199     ssl_seeded = TRUE;
00200     return CURLE_OK;
00201   }
00202 
00203 #ifndef RANDOM_FILE
00204   /* if RANDOM_FILE isn't defined, we only perform this if an option tells
00205      us to! */
00206   if(data->set.str[STRING_SSL_RANDOM_FILE])
00207 #define RANDOM_FILE "" /* doesn't matter won't be used */
00208 #endif
00209   {
00210     /* let the option override the define */
00211     nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
00212                              data->set.str[STRING_SSL_RANDOM_FILE]:
00213                              RANDOM_FILE),
00214                             RAND_LOAD_LENGTH);
00215     if(rand_enough())
00216       return nread;
00217   }
00218 
00219 #if defined(HAVE_RAND_EGD)
00220   /* only available in OpenSSL 0.9.5 and later */
00221   /* EGD_SOCKET is set at configure time or not at all */
00222 #ifndef EGD_SOCKET
00223   /* If we don't have the define set, we only do this if the egd-option
00224      is set */
00225   if(data->set.str[STRING_SSL_EGDSOCKET])
00226 #define EGD_SOCKET "" /* doesn't matter won't be used */
00227 #endif
00228   {
00229     /* If there's an option and a define, the option overrides the
00230        define */
00231     int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
00232                        data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
00233     if(-1 != ret) {
00234       nread += ret;
00235       if(rand_enough())
00236         return nread;
00237     }
00238   }
00239 #endif
00240 
00241   /* If we get here, it means we need to seed the PRNG using a "silly"
00242      approach! */
00243   do {
00244     unsigned char randb[64];
00245     int len = sizeof(randb);
00246     if(!RAND_bytes(randb, len))
00247       break;
00248     RAND_add(randb, len, (len >> 1));
00249   } while(!rand_enough());
00250 
00251   /* generates a default path for the random seed file */
00252   buf[0]=0; /* blank it first */
00253   RAND_file_name(buf, BUFSIZE);
00254   if(buf[0]) {
00255     /* we got a file name to try */
00256     nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
00257     if(rand_enough())
00258       return nread;
00259   }
00260 
00261   infof(data, "libcurl is now using a weak random seed!\n");
00262   return CURLE_SSL_CONNECT_ERROR; /* confusing error code */
00263 }
00264 
00265 #ifndef SSL_FILETYPE_ENGINE
00266 #define SSL_FILETYPE_ENGINE 42
00267 #endif
00268 #ifndef SSL_FILETYPE_PKCS12
00269 #define SSL_FILETYPE_PKCS12 43
00270 #endif
00271 static int do_file_type(const char *type)
00272 {
00273   if(!type || !type[0])
00274     return SSL_FILETYPE_PEM;
00275   if(strcasecompare(type, "PEM"))
00276     return SSL_FILETYPE_PEM;
00277   if(strcasecompare(type, "DER"))
00278     return SSL_FILETYPE_ASN1;
00279   if(strcasecompare(type, "ENG"))
00280     return SSL_FILETYPE_ENGINE;
00281   if(strcasecompare(type, "P12"))
00282     return SSL_FILETYPE_PKCS12;
00283   return -1;
00284 }
00285 
00286 #if defined(HAVE_OPENSSL_ENGINE_H)
00287 /*
00288  * Supply default password to the engine user interface conversation.
00289  * The password is passed by OpenSSL engine from ENGINE_load_private_key()
00290  * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
00291  */
00292 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
00293 {
00294   const char *password;
00295   switch(UI_get_string_type(uis)) {
00296   case UIT_PROMPT:
00297   case UIT_VERIFY:
00298     password = (const char *)UI_get0_user_data(ui);
00299     if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
00300       UI_set_result(ui, uis, password);
00301       return 1;
00302     }
00303   default:
00304     break;
00305   }
00306   return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
00307 }
00308 
00309 /*
00310  * Suppress interactive request for a default password if available.
00311  */
00312 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
00313 {
00314   switch(UI_get_string_type(uis)) {
00315   case UIT_PROMPT:
00316   case UIT_VERIFY:
00317     if(UI_get0_user_data(ui) &&
00318        (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
00319       return 1;
00320     }
00321   default:
00322     break;
00323   }
00324   return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
00325 }
00326 #endif
00327 
00328 static
00329 int cert_stuff(struct connectdata *conn,
00330                SSL_CTX* ctx,
00331                char *cert_file,
00332                const char *cert_type,
00333                char *key_file,
00334                const char *key_type,
00335                char *key_passwd)
00336 {
00337   struct Curl_easy *data = conn->data;
00338 
00339   int file_type = do_file_type(cert_type);
00340 
00341   if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
00342     SSL *ssl;
00343     X509 *x509;
00344     int cert_done = 0;
00345 
00346     if(key_passwd) {
00347       /* set the password in the callback userdata */
00348       SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
00349       /* Set passwd callback: */
00350       SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
00351     }
00352 
00353 
00354     switch(file_type) {
00355     case SSL_FILETYPE_PEM:
00356       /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
00357       if(SSL_CTX_use_certificate_chain_file(ctx,
00358                                             cert_file) != 1) {
00359         failf(data,
00360               "could not load PEM client certificate, " OSSL_PACKAGE
00361               " error %s, "
00362               "(no key found, wrong pass phrase, or wrong file format?)",
00363               ERR_error_string(ERR_get_error(), NULL) );
00364         return 0;
00365       }
00366       break;
00367 
00368     case SSL_FILETYPE_ASN1:
00369       /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
00370          we use the case above for PEM so this can only be performed with
00371          ASN1 files. */
00372       if(SSL_CTX_use_certificate_file(ctx,
00373                                       cert_file,
00374                                       file_type) != 1) {
00375         failf(data,
00376               "could not load ASN1 client certificate, " OSSL_PACKAGE
00377               " error %s, "
00378               "(no key found, wrong pass phrase, or wrong file format?)",
00379               ERR_error_string(ERR_get_error(), NULL) );
00380         return 0;
00381       }
00382       break;
00383     case SSL_FILETYPE_ENGINE:
00384 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
00385       {
00386         if(data->state.engine) {
00387           const char *cmd_name = "LOAD_CERT_CTRL";
00388           struct {
00389             const char *cert_id;
00390             X509 *cert;
00391           } params;
00392 
00393           params.cert_id = cert_file;
00394           params.cert = NULL;
00395 
00396           /* Does the engine supports LOAD_CERT_CTRL ? */
00397           if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
00398                           0, (void *)cmd_name, NULL)) {
00399             failf(data, "ssl engine does not support loading certificates");
00400             return 0;
00401           }
00402 
00403           /* Load the certificate from the engine */
00404           if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
00405                               0, &params, NULL, 1)) {
00406             failf(data, "ssl engine cannot load client cert with id"
00407                   " '%s' [%s]", cert_file,
00408                   ERR_error_string(ERR_get_error(), NULL));
00409             return 0;
00410           }
00411 
00412           if(!params.cert) {
00413             failf(data, "ssl engine didn't initialized the certificate "
00414                   "properly.");
00415             return 0;
00416           }
00417 
00418           if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
00419             failf(data, "unable to set client certificate");
00420             X509_free(params.cert);
00421             return 0;
00422           }
00423           X509_free(params.cert); /* we don't need the handle any more... */
00424         }
00425         else {
00426           failf(data, "crypto engine not set, can't load certificate");
00427           return 0;
00428         }
00429       }
00430       break;
00431 #else
00432       failf(data, "file type ENG for certificate not implemented");
00433       return 0;
00434 #endif
00435 
00436     case SSL_FILETYPE_PKCS12:
00437     {
00438 #ifdef HAVE_OPENSSL_PKCS12_H
00439       FILE *f;
00440       PKCS12 *p12;
00441       EVP_PKEY *pri;
00442       STACK_OF(X509) *ca = NULL;
00443 
00444       f = fopen(cert_file, "rb");
00445       if(!f) {
00446         failf(data, "could not open PKCS12 file '%s'", cert_file);
00447         return 0;
00448       }
00449       p12 = d2i_PKCS12_fp(f, NULL);
00450       fclose(f);
00451 
00452       if(!p12) {
00453         failf(data, "error reading PKCS12 file '%s'", cert_file);
00454         return 0;
00455       }
00456 
00457       PKCS12_PBE_add();
00458 
00459       if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
00460                        &ca)) {
00461         failf(data,
00462               "could not parse PKCS12 file, check password, " OSSL_PACKAGE
00463               " error %s",
00464               ERR_error_string(ERR_get_error(), NULL) );
00465         PKCS12_free(p12);
00466         return 0;
00467       }
00468 
00469       PKCS12_free(p12);
00470 
00471       if(SSL_CTX_use_certificate(ctx, x509) != 1) {
00472         failf(data,
00473               "could not load PKCS12 client certificate, " OSSL_PACKAGE
00474               " error %s",
00475               ERR_error_string(ERR_get_error(), NULL) );
00476         goto fail;
00477       }
00478 
00479       if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
00480         failf(data, "unable to use private key from PKCS12 file '%s'",
00481               cert_file);
00482         goto fail;
00483       }
00484 
00485       if(!SSL_CTX_check_private_key (ctx)) {
00486         failf(data, "private key from PKCS12 file '%s' "
00487               "does not match certificate in same file", cert_file);
00488         goto fail;
00489       }
00490       /* Set Certificate Verification chain */
00491       if(ca) {
00492         while(sk_X509_num(ca)) {
00493           /*
00494            * Note that sk_X509_pop() is used below to make sure the cert is
00495            * removed from the stack properly before getting passed to
00496            * SSL_CTX_add_extra_chain_cert(). Previously we used
00497            * sk_X509_value() instead, but then we'd clean it in the subsequent
00498            * sk_X509_pop_free() call.
00499            */
00500           X509 *x = sk_X509_pop(ca);
00501           if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
00502             X509_free(x);
00503             failf(data, "cannot add certificate to certificate chain");
00504             goto fail;
00505           }
00506           /* SSL_CTX_add_client_CA() seems to work with either sk_* function,
00507            * presumably because it duplicates what we pass to it.
00508            */
00509           if(!SSL_CTX_add_client_CA(ctx, x)) {
00510             failf(data, "cannot add certificate to client CA list");
00511             goto fail;
00512           }
00513         }
00514       }
00515 
00516       cert_done = 1;
00517   fail:
00518       EVP_PKEY_free(pri);
00519       X509_free(x509);
00520       sk_X509_pop_free(ca, X509_free);
00521 
00522       if(!cert_done)
00523         return 0; /* failure! */
00524       break;
00525 #else
00526       failf(data, "file type P12 for certificate not supported");
00527       return 0;
00528 #endif
00529     }
00530     default:
00531       failf(data, "not supported file type '%s' for certificate", cert_type);
00532       return 0;
00533     }
00534 
00535     file_type = do_file_type(key_type);
00536 
00537     switch(file_type) {
00538     case SSL_FILETYPE_PEM:
00539       if(cert_done)
00540         break;
00541       if(!key_file)
00542         /* cert & key can only be in PEM case in the same file */
00543         key_file=cert_file;
00544     case SSL_FILETYPE_ASN1:
00545       if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
00546         failf(data, "unable to set private key file: '%s' type %s",
00547               key_file, key_type?key_type:"PEM");
00548         return 0;
00549       }
00550       break;
00551     case SSL_FILETYPE_ENGINE:
00552 #ifdef HAVE_OPENSSL_ENGINE_H
00553       {                         /* XXXX still needs some work */
00554         EVP_PKEY *priv_key = NULL;
00555         if(data->state.engine) {
00556           UI_METHOD *ui_method =
00557             UI_create_method((char *)"curl user interface");
00558           if(!ui_method) {
00559             failf(data, "unable do create " OSSL_PACKAGE
00560                   " user-interface method");
00561             return 0;
00562           }
00563           UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
00564           UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
00565           UI_method_set_reader(ui_method, ssl_ui_reader);
00566           UI_method_set_writer(ui_method, ssl_ui_writer);
00567           /* the typecast below was added to please mingw32 */
00568           priv_key = (EVP_PKEY *)
00569             ENGINE_load_private_key(data->state.engine, key_file,
00570                                     ui_method,
00571                                     key_passwd);
00572           UI_destroy_method(ui_method);
00573           if(!priv_key) {
00574             failf(data, "failed to load private key from crypto engine");
00575             return 0;
00576           }
00577           if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
00578             failf(data, "unable to set private key");
00579             EVP_PKEY_free(priv_key);
00580             return 0;
00581           }
00582           EVP_PKEY_free(priv_key);  /* we don't need the handle any more... */
00583         }
00584         else {
00585           failf(data, "crypto engine not set, can't load private key");
00586           return 0;
00587         }
00588       }
00589       break;
00590 #else
00591       failf(data, "file type ENG for private key not supported");
00592       return 0;
00593 #endif
00594     case SSL_FILETYPE_PKCS12:
00595       if(!cert_done) {
00596         failf(data, "file type P12 for private key not supported");
00597         return 0;
00598       }
00599       break;
00600     default:
00601       failf(data, "not supported file type for private key");
00602       return 0;
00603     }
00604 
00605     ssl=SSL_new(ctx);
00606     if(!ssl) {
00607       failf(data, "unable to create an SSL structure");
00608       return 0;
00609     }
00610 
00611     x509=SSL_get_certificate(ssl);
00612 
00613     /* This version was provided by Evan Jordan and is supposed to not
00614        leak memory as the previous version: */
00615     if(x509) {
00616       EVP_PKEY *pktmp = X509_get_pubkey(x509);
00617       EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
00618       EVP_PKEY_free(pktmp);
00619     }
00620 
00621     SSL_free(ssl);
00622 
00623     /* If we are using DSA, we can copy the parameters from
00624      * the private key */
00625 
00626 
00627     /* Now we know that a key and cert have been set against
00628      * the SSL context */
00629     if(!SSL_CTX_check_private_key(ctx)) {
00630       failf(data, "Private key does not match the certificate public key");
00631       return 0;
00632     }
00633   }
00634   return 1;
00635 }
00636 
00637 /* returns non-zero on failure */
00638 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
00639 {
00640 #if 0
00641   return X509_NAME_oneline(a, buf, size);
00642 #else
00643   BIO *bio_out = BIO_new(BIO_s_mem());
00644   BUF_MEM *biomem;
00645   int rc;
00646 
00647   if(!bio_out)
00648     return 1; /* alloc failed! */
00649 
00650   rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
00651   BIO_get_mem_ptr(bio_out, &biomem);
00652 
00653   if((size_t)biomem->length < size)
00654     size = biomem->length;
00655   else
00656     size--; /* don't overwrite the buffer end */
00657 
00658   memcpy(buf, biomem->data, size);
00659   buf[size]=0;
00660 
00661   BIO_free(bio_out);
00662 
00663   return !rc;
00664 #endif
00665 }
00666 
00667 /* Return error string for last OpenSSL error
00668  */
00669 static char *ossl_strerror(unsigned long error, char *buf, size_t size)
00670 {
00671   /* OpenSSL 0.9.6 and later has a function named
00672      ERR_error_string_n() that takes the size of the buffer as a
00673      third argument */
00674   ERR_error_string_n(error, buf, size);
00675   return buf;
00676 }
00677 
00684 int Curl_ossl_init(void)
00685 {
00686   OPENSSL_load_builtin_modules();
00687 
00688 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
00689   ENGINE_load_builtin_engines();
00690 #endif
00691 
00692   /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
00693      that function makes an exit() call on wrongly formatted config files
00694      which makes it hard to use in some situations. OPENSSL_config() itself
00695      calls CONF_modules_load_file() and we use that instead and we ignore
00696      its return code! */
00697 
00698   /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
00699      0.9.8e */
00700 #ifndef CONF_MFLAGS_DEFAULT_SECTION
00701 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
00702 #endif
00703 
00704   CONF_modules_load_file(NULL, NULL,
00705                          CONF_MFLAGS_DEFAULT_SECTION|
00706                          CONF_MFLAGS_IGNORE_MISSING_FILE);
00707 
00708 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
00709     !defined(LIBRESSL_VERSION_NUMBER)
00710   /* OpenSSL 1.1.0+ takes care of initialization itself */
00711 #else
00712   /* Lets get nice error messages */
00713   SSL_load_error_strings();
00714 
00715   /* Init the global ciphers and digests */
00716   if(!SSLeay_add_ssl_algorithms())
00717     return 0;
00718 
00719   OpenSSL_add_all_algorithms();
00720 #endif
00721 
00722   return 1;
00723 }
00724 
00725 /* Global cleanup */
00726 void Curl_ossl_cleanup(void)
00727 {
00728 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
00729     !defined(LIBRESSL_VERSION_NUMBER)
00730   /* OpenSSL 1.1 deprecates all these cleanup functions and
00731      turns them into no-ops in OpenSSL 1.0 compatibility mode */
00732 #else
00733   /* Free ciphers and digests lists */
00734   EVP_cleanup();
00735 
00736 #ifdef HAVE_ENGINE_CLEANUP
00737   /* Free engine list */
00738   ENGINE_cleanup();
00739 #endif
00740 
00741   /* Free OpenSSL error strings */
00742   ERR_free_strings();
00743 
00744   /* Free thread local error state, destroying hash upon zero refcount */
00745 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
00746   ERR_remove_thread_state(NULL);
00747 #else
00748   ERR_remove_state(0);
00749 #endif
00750 
00751   /* Free all memory allocated by all configuration modules */
00752   CONF_modules_free();
00753 
00754 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
00755   SSL_COMP_free_compression_methods();
00756 #endif
00757 #endif
00758 }
00759 
00760 /*
00761  * This function is used to determine connection status.
00762  *
00763  * Return codes:
00764  *     1 means the connection is still in place
00765  *     0 means the connection has been closed
00766  *    -1 means the connection status is unknown
00767  */
00768 int Curl_ossl_check_cxn(struct connectdata *conn)
00769 {
00770   /* SSL_peek takes data out of the raw recv buffer without peeking so we use
00771      recv MSG_PEEK instead. Bug #795 */
00772 #ifdef MSG_PEEK
00773   char buf;
00774   ssize_t nread;
00775   nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
00776                (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
00777   if(nread == 0)
00778     return 0; /* connection has been closed */
00779   else if(nread == 1)
00780     return 1; /* connection still in place */
00781   else if(nread == -1) {
00782       int err = SOCKERRNO;
00783       if(err == EINPROGRESS ||
00784 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
00785          err == EAGAIN ||
00786 #endif
00787          err == EWOULDBLOCK)
00788         return 1; /* connection still in place */
00789       if(err == ECONNRESET ||
00790 #ifdef ECONNABORTED
00791          err == ECONNABORTED ||
00792 #endif
00793 #ifdef ENETDOWN
00794          err == ENETDOWN ||
00795 #endif
00796 #ifdef ENETRESET
00797          err == ENETRESET ||
00798 #endif
00799 #ifdef ESHUTDOWN
00800          err == ESHUTDOWN ||
00801 #endif
00802 #ifdef ETIMEDOUT
00803          err == ETIMEDOUT ||
00804 #endif
00805          err == ENOTCONN)
00806         return 0; /* connection has been closed */
00807   }
00808 #endif
00809   return -1; /* connection status unknown */
00810 }
00811 
00812 /* Selects an OpenSSL crypto engine
00813  */
00814 CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
00815 {
00816 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
00817   ENGINE *e;
00818 
00819 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
00820   e = ENGINE_by_id(engine);
00821 #else
00822   /* avoid memory leak */
00823   for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
00824     const char *e_id = ENGINE_get_id(e);
00825     if(!strcmp(engine, e_id))
00826       break;
00827   }
00828 #endif
00829 
00830   if(!e) {
00831     failf(data, "SSL Engine '%s' not found", engine);
00832     return CURLE_SSL_ENGINE_NOTFOUND;
00833   }
00834 
00835   if(data->state.engine) {
00836     ENGINE_finish(data->state.engine);
00837     ENGINE_free(data->state.engine);
00838     data->state.engine = NULL;
00839   }
00840   if(!ENGINE_init(e)) {
00841     char buf[256];
00842 
00843     ENGINE_free(e);
00844     failf(data, "Failed to initialise SSL Engine '%s':\n%s",
00845           engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
00846     return CURLE_SSL_ENGINE_INITFAILED;
00847   }
00848   data->state.engine = e;
00849   return CURLE_OK;
00850 #else
00851   (void)engine;
00852   failf(data, "SSL Engine not supported");
00853   return CURLE_SSL_ENGINE_NOTFOUND;
00854 #endif
00855 }
00856 
00857 /* Sets engine as default for all SSL operations
00858  */
00859 CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
00860 {
00861 #ifdef HAVE_OPENSSL_ENGINE_H
00862   if(data->state.engine) {
00863     if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
00864       infof(data, "set default crypto engine '%s'\n",
00865             ENGINE_get_id(data->state.engine));
00866     }
00867     else {
00868       failf(data, "set default crypto engine '%s' failed",
00869             ENGINE_get_id(data->state.engine));
00870       return CURLE_SSL_ENGINE_SETFAILED;
00871     }
00872   }
00873 #else
00874   (void) data;
00875 #endif
00876   return CURLE_OK;
00877 }
00878 
00879 /* Return list of OpenSSL crypto engine names.
00880  */
00881 struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
00882 {
00883   struct curl_slist *list = NULL;
00884 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
00885   struct curl_slist *beg;
00886   ENGINE *e;
00887 
00888   for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
00889     beg = curl_slist_append(list, ENGINE_get_id(e));
00890     if(!beg) {
00891       curl_slist_free_all(list);
00892       return NULL;
00893     }
00894     list = beg;
00895   }
00896 #endif
00897   (void) data;
00898   return list;
00899 }
00900 
00901 
00902 static void ossl_close(struct ssl_connect_data *connssl)
00903 {
00904   if(connssl->handle) {
00905     (void)SSL_shutdown(connssl->handle);
00906     SSL_set_connect_state(connssl->handle);
00907 
00908     SSL_free(connssl->handle);
00909     connssl->handle = NULL;
00910   }
00911   if(connssl->ctx) {
00912     SSL_CTX_free(connssl->ctx);
00913     connssl->ctx = NULL;
00914   }
00915 }
00916 
00917 /*
00918  * This function is called when an SSL connection is closed.
00919  */
00920 void Curl_ossl_close(struct connectdata *conn, int sockindex)
00921 {
00922   ossl_close(&conn->ssl[sockindex]);
00923   ossl_close(&conn->proxy_ssl[sockindex]);
00924 }
00925 
00926 /*
00927  * This function is called to shut down the SSL layer but keep the
00928  * socket open (CCC - Clear Command Channel)
00929  */
00930 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
00931 {
00932   int retval = 0;
00933   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
00934   struct Curl_easy *data = conn->data;
00935   char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
00936                     to be at least 256 bytes long. */
00937   unsigned long sslerror;
00938   ssize_t nread;
00939   int buffsize;
00940   int err;
00941   int done = 0;
00942 
00943   /* This has only been tested on the proftpd server, and the mod_tls code
00944      sends a close notify alert without waiting for a close notify alert in
00945      response. Thus we wait for a close notify alert from the server, but
00946      we do not send one. Let's hope other servers do the same... */
00947 
00948   if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
00949       (void)SSL_shutdown(connssl->handle);
00950 
00951   if(connssl->handle) {
00952     buffsize = (int)sizeof(buf);
00953     while(!done) {
00954       int what = SOCKET_READABLE(conn->sock[sockindex],
00955                                  SSL_SHUTDOWN_TIMEOUT);
00956       if(what > 0) {
00957         ERR_clear_error();
00958 
00959         /* Something to read, let's do it and hope that it is the close
00960            notify alert from the server */
00961         nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
00962                                   buffsize);
00963         err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
00964 
00965         switch(err) {
00966         case SSL_ERROR_NONE: /* this is not an error */
00967         case SSL_ERROR_ZERO_RETURN: /* no more data */
00968           /* This is the expected response. There was no data but only
00969              the close notify alert */
00970           done = 1;
00971           break;
00972         case SSL_ERROR_WANT_READ:
00973           /* there's data pending, re-invoke SSL_read() */
00974           infof(data, "SSL_ERROR_WANT_READ\n");
00975           break;
00976         case SSL_ERROR_WANT_WRITE:
00977           /* SSL wants a write. Really odd. Let's bail out. */
00978           infof(data, "SSL_ERROR_WANT_WRITE\n");
00979           done = 1;
00980           break;
00981         default:
00982           /* openssl/ssl.h says "look at error stack/return value/errno" */
00983           sslerror = ERR_get_error();
00984           failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d",
00985                 ossl_strerror(sslerror, buf, sizeof(buf)),
00986                 SOCKERRNO);
00987           done = 1;
00988           break;
00989         }
00990       }
00991       else if(0 == what) {
00992         /* timeout */
00993         failf(data, "SSL shutdown timeout");
00994         done = 1;
00995       }
00996       else {
00997         /* anything that gets here is fatally bad */
00998         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
00999         retval = -1;
01000         done = 1;
01001       }
01002     } /* while()-loop for the select() */
01003 
01004     if(data->set.verbose) {
01005 #ifdef HAVE_SSL_GET_SHUTDOWN
01006       switch(SSL_get_shutdown(connssl->handle)) {
01007       case SSL_SENT_SHUTDOWN:
01008         infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
01009         break;
01010       case SSL_RECEIVED_SHUTDOWN:
01011         infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
01012         break;
01013       case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
01014         infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
01015               "SSL_RECEIVED__SHUTDOWN\n");
01016         break;
01017       }
01018 #endif
01019     }
01020 
01021     SSL_free(connssl->handle);
01022     connssl->handle = NULL;
01023   }
01024   return retval;
01025 }
01026 
01027 void Curl_ossl_session_free(void *ptr)
01028 {
01029   /* free the ID */
01030   SSL_SESSION_free(ptr);
01031 }
01032 
01033 /*
01034  * This function is called when the 'data' struct is going away. Close
01035  * down everything and free all resources!
01036  */
01037 void Curl_ossl_close_all(struct Curl_easy *data)
01038 {
01039 #ifdef HAVE_OPENSSL_ENGINE_H
01040   if(data->state.engine) {
01041     ENGINE_finish(data->state.engine);
01042     ENGINE_free(data->state.engine);
01043     data->state.engine = NULL;
01044   }
01045 #else
01046   (void)data;
01047 #endif
01048 #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
01049   defined(HAVE_ERR_REMOVE_THREAD_STATE)
01050   /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
01051      so we need to clean it here in case the thread will be killed. All OpenSSL
01052      code should extract the error in association with the error so clearing
01053      this queue here should be harmless at worst. */
01054   ERR_remove_thread_state(NULL);
01055 #endif
01056 }
01057 
01058 /* ====================================================== */
01059 
01060 
01061 /* Quote from RFC2818 section 3.1 "Server Identity"
01062 
01063    If a subjectAltName extension of type dNSName is present, that MUST
01064    be used as the identity. Otherwise, the (most specific) Common Name
01065    field in the Subject field of the certificate MUST be used. Although
01066    the use of the Common Name is existing practice, it is deprecated and
01067    Certification Authorities are encouraged to use the dNSName instead.
01068 
01069    Matching is performed using the matching rules specified by
01070    [RFC2459].  If more than one identity of a given type is present in
01071    the certificate (e.g., more than one dNSName name, a match in any one
01072    of the set is considered acceptable.) Names may contain the wildcard
01073    character * which is considered to match any single domain name
01074    component or component fragment. E.g., *.a.com matches foo.a.com but
01075    not bar.foo.a.com. f*.com matches foo.com but not bar.com.
01076 
01077    In some cases, the URI is specified as an IP address rather than a
01078    hostname. In this case, the iPAddress subjectAltName must be present
01079    in the certificate and must exactly match the IP in the URI.
01080 
01081 */
01082 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
01083 {
01084   bool matched = FALSE;
01085   int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
01086   size_t addrlen = 0;
01087   struct Curl_easy *data = conn->data;
01088   STACK_OF(GENERAL_NAME) *altnames;
01089 #ifdef ENABLE_IPV6
01090   struct in6_addr addr;
01091 #else
01092   struct in_addr addr;
01093 #endif
01094   CURLcode result = CURLE_OK;
01095   bool dNSName = FALSE; /* if a dNSName field exists in the cert */
01096   bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
01097   const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
01098     conn->host.name;
01099   const char * const dispname = SSL_IS_PROXY() ?
01100     conn->http_proxy.host.dispname : conn->host.dispname;
01101 
01102 #ifdef ENABLE_IPV6
01103   if(conn->bits.ipv6_ip &&
01104      Curl_inet_pton(AF_INET6, hostname, &addr)) {
01105     target = GEN_IPADD;
01106     addrlen = sizeof(struct in6_addr);
01107   }
01108   else
01109 #endif
01110     if(Curl_inet_pton(AF_INET, hostname, &addr)) {
01111       target = GEN_IPADD;
01112       addrlen = sizeof(struct in_addr);
01113     }
01114 
01115   /* get a "list" of alternative names */
01116   altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
01117 
01118   if(altnames) {
01119     int numalts;
01120     int i;
01121     bool dnsmatched = FALSE;
01122     bool ipmatched = FALSE;
01123 
01124     /* get amount of alternatives, RFC2459 claims there MUST be at least
01125        one, but we don't depend on it... */
01126     numalts = sk_GENERAL_NAME_num(altnames);
01127 
01128     /* loop through all alternatives - until a dnsmatch */
01129     for(i=0; (i < numalts) && !dnsmatched; i++) {
01130       /* get a handle to alternative name number i */
01131       const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
01132 
01133       if(check->type == GEN_DNS)
01134         dNSName = TRUE;
01135       else if(check->type == GEN_IPADD)
01136         iPAddress = TRUE;
01137 
01138       /* only check alternatives of the same type the target is */
01139       if(check->type == target) {
01140         /* get data and length */
01141         const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
01142         size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
01143 
01144         switch(target) {
01145         case GEN_DNS: /* name/pattern comparison */
01146           /* The OpenSSL man page explicitly says: "In general it cannot be
01147              assumed that the data returned by ASN1_STRING_data() is null
01148              terminated or does not contain embedded nulls." But also that
01149              "The actual format of the data will depend on the actual string
01150              type itself: for example for and IA5String the data will be ASCII"
01151 
01152              Gisle researched the OpenSSL sources:
01153              "I checked the 0.9.6 and 0.9.8 sources before my patch and
01154              it always 0-terminates an IA5String."
01155           */
01156           if((altlen == strlen(altptr)) &&
01157              /* if this isn't true, there was an embedded zero in the name
01158                 string and we cannot match it. */
01159              Curl_cert_hostcheck(altptr, hostname)) {
01160             dnsmatched = TRUE;
01161             infof(data,
01162                   " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
01163                   dispname, altptr);
01164           }
01165           break;
01166 
01167         case GEN_IPADD: /* IP address comparison */
01168           /* compare alternative IP address if the data chunk is the same size
01169              our server IP address is */
01170           if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
01171             ipmatched = TRUE;
01172             infof(data,
01173                   " subjectAltName: host \"%s\" matched cert's IP address!\n",
01174                   dispname);
01175           }
01176           break;
01177         }
01178       }
01179     }
01180     GENERAL_NAMES_free(altnames);
01181 
01182     if(dnsmatched || ipmatched)
01183       matched = TRUE;
01184   }
01185 
01186   if(matched)
01187     /* an alternative name matched */
01188     ;
01189   else if(dNSName || iPAddress) {
01190     infof(data, " subjectAltName does not match %s\n", dispname);
01191     failf(data, "SSL: no alternative certificate subject name matches "
01192           "target host name '%s'", dispname);
01193     result = CURLE_PEER_FAILED_VERIFICATION;
01194   }
01195   else {
01196     /* we have to look to the last occurrence of a commonName in the
01197        distinguished one to get the most significant one. */
01198     int j, i=-1;
01199 
01200     /* The following is done because of a bug in 0.9.6b */
01201 
01202     unsigned char *nulstr = (unsigned char *)"";
01203     unsigned char *peer_CN = nulstr;
01204 
01205     X509_NAME *name = X509_get_subject_name(server_cert);
01206     if(name)
01207       while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
01208         i=j;
01209 
01210     /* we have the name entry and we will now convert this to a string
01211        that we can use for comparison. Doing this we support BMPstring,
01212        UTF8 etc. */
01213 
01214     if(i>=0) {
01215       ASN1_STRING *tmp =
01216         X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
01217 
01218       /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
01219          is already UTF-8 encoded. We check for this case and copy the raw
01220          string manually to avoid the problem. This code can be made
01221          conditional in the future when OpenSSL has been fixed. Work-around
01222          brought by Alexis S. L. Carvalho. */
01223       if(tmp) {
01224         if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
01225           j = ASN1_STRING_length(tmp);
01226           if(j >= 0) {
01227             peer_CN = OPENSSL_malloc(j+1);
01228             if(peer_CN) {
01229               memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
01230               peer_CN[j] = '\0';
01231             }
01232           }
01233         }
01234         else /* not a UTF8 name */
01235           j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
01236 
01237         if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
01238           /* there was a terminating zero before the end of string, this
01239              cannot match and we return failure! */
01240           failf(data, "SSL: illegal cert name field");
01241           result = CURLE_PEER_FAILED_VERIFICATION;
01242         }
01243       }
01244     }
01245 
01246     if(peer_CN == nulstr)
01247        peer_CN = NULL;
01248     else {
01249       /* convert peer_CN from UTF8 */
01250       CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
01251       /* Curl_convert_from_utf8 calls failf if unsuccessful */
01252       if(rc) {
01253         OPENSSL_free(peer_CN);
01254         return rc;
01255       }
01256     }
01257 
01258     if(result)
01259       /* error already detected, pass through */
01260       ;
01261     else if(!peer_CN) {
01262       failf(data,
01263             "SSL: unable to obtain common name from peer certificate");
01264       result = CURLE_PEER_FAILED_VERIFICATION;
01265     }
01266     else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
01267       failf(data, "SSL: certificate subject name '%s' does not match "
01268             "target host name '%s'", peer_CN, dispname);
01269       result = CURLE_PEER_FAILED_VERIFICATION;
01270     }
01271     else {
01272       infof(data, " common name: %s (matched)\n", peer_CN);
01273     }
01274     if(peer_CN)
01275       OPENSSL_free(peer_CN);
01276   }
01277 
01278   return result;
01279 }
01280 
01281 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
01282     !defined(OPENSSL_NO_OCSP)
01283 static CURLcode verifystatus(struct connectdata *conn,
01284                              struct ssl_connect_data *connssl)
01285 {
01286   int i, ocsp_status;
01287   const unsigned char *p;
01288   CURLcode result = CURLE_OK;
01289   struct Curl_easy *data = conn->data;
01290 
01291   OCSP_RESPONSE *rsp = NULL;
01292   OCSP_BASICRESP *br = NULL;
01293   X509_STORE     *st = NULL;
01294   STACK_OF(X509) *ch = NULL;
01295 
01296   long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
01297 
01298   if(!p) {
01299     failf(data, "No OCSP response received");
01300     result = CURLE_SSL_INVALIDCERTSTATUS;
01301     goto end;
01302   }
01303 
01304   rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
01305   if(!rsp) {
01306     failf(data, "Invalid OCSP response");
01307     result = CURLE_SSL_INVALIDCERTSTATUS;
01308     goto end;
01309   }
01310 
01311   ocsp_status = OCSP_response_status(rsp);
01312   if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
01313     failf(data, "Invalid OCSP response status: %s (%d)",
01314           OCSP_response_status_str(ocsp_status), ocsp_status);
01315     result = CURLE_SSL_INVALIDCERTSTATUS;
01316     goto end;
01317   }
01318 
01319   br = OCSP_response_get1_basic(rsp);
01320   if(!br) {
01321     failf(data, "Invalid OCSP response");
01322     result = CURLE_SSL_INVALIDCERTSTATUS;
01323     goto end;
01324   }
01325 
01326   ch = SSL_get_peer_cert_chain(connssl->handle);
01327   st = SSL_CTX_get_cert_store(connssl->ctx);
01328 
01329 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
01330      defined(LIBRESSL_VERSION_NUMBER))
01331   /* The authorized responder cert in the OCSP response MUST be signed by the
01332      peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
01333      no problem, but if it's an intermediate cert OpenSSL has a bug where it
01334      expects this issuer to be present in the chain embedded in the OCSP
01335      response. So we add it if necessary. */
01336 
01337   /* First make sure the peer cert chain includes both a peer and an issuer,
01338      and the OCSP response contains a responder cert. */
01339   if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
01340     X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
01341 
01342     /* Find issuer of responder cert and add it to the OCSP response chain */
01343     for(i = 0; i < sk_X509_num(ch); i++) {
01344       X509 *issuer = sk_X509_value(ch, i);
01345       if(X509_check_issued(issuer, responder) == X509_V_OK) {
01346         if(!OCSP_basic_add1_cert(br, issuer)) {
01347           failf(data, "Could not add issuer cert to OCSP response");
01348           result = CURLE_SSL_INVALIDCERTSTATUS;
01349           goto end;
01350         }
01351       }
01352     }
01353   }
01354 #endif
01355 
01356   if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
01357     failf(data, "OCSP response verification failed");
01358     result = CURLE_SSL_INVALIDCERTSTATUS;
01359     goto end;
01360   }
01361 
01362   for(i = 0; i < OCSP_resp_count(br); i++) {
01363     int cert_status, crl_reason;
01364     OCSP_SINGLERESP *single = NULL;
01365 
01366     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
01367 
01368     single = OCSP_resp_get0(br, i);
01369     if(!single)
01370       continue;
01371 
01372     cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
01373                                           &thisupd, &nextupd);
01374 
01375     if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
01376       failf(data, "OCSP response has expired");
01377       result = CURLE_SSL_INVALIDCERTSTATUS;
01378       goto end;
01379     }
01380 
01381     infof(data, "SSL certificate status: %s (%d)\n",
01382           OCSP_cert_status_str(cert_status), cert_status);
01383 
01384     switch(cert_status) {
01385       case V_OCSP_CERTSTATUS_GOOD:
01386         break;
01387 
01388       case V_OCSP_CERTSTATUS_REVOKED:
01389         result = CURLE_SSL_INVALIDCERTSTATUS;
01390 
01391         failf(data, "SSL certificate revocation reason: %s (%d)",
01392               OCSP_crl_reason_str(crl_reason), crl_reason);
01393         goto end;
01394 
01395       case V_OCSP_CERTSTATUS_UNKNOWN:
01396         result = CURLE_SSL_INVALIDCERTSTATUS;
01397         goto end;
01398     }
01399   }
01400 
01401 end:
01402   if(br) OCSP_BASICRESP_free(br);
01403   OCSP_RESPONSE_free(rsp);
01404 
01405   return result;
01406 }
01407 #endif
01408 
01409 #endif /* USE_OPENSSL */
01410 
01411 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
01412    and thus this cannot be done there. */
01413 #ifdef SSL_CTRL_SET_MSG_CALLBACK
01414 
01415 static const char *ssl_msg_type(int ssl_ver, int msg)
01416 {
01417 #ifdef SSL2_VERSION_MAJOR
01418   if(ssl_ver == SSL2_VERSION_MAJOR) {
01419     switch(msg) {
01420       case SSL2_MT_ERROR:
01421         return "Error";
01422       case SSL2_MT_CLIENT_HELLO:
01423         return "Client hello";
01424       case SSL2_MT_CLIENT_MASTER_KEY:
01425         return "Client key";
01426       case SSL2_MT_CLIENT_FINISHED:
01427         return "Client finished";
01428       case SSL2_MT_SERVER_HELLO:
01429         return "Server hello";
01430       case SSL2_MT_SERVER_VERIFY:
01431         return "Server verify";
01432       case SSL2_MT_SERVER_FINISHED:
01433         return "Server finished";
01434       case SSL2_MT_REQUEST_CERTIFICATE:
01435         return "Request CERT";
01436       case SSL2_MT_CLIENT_CERTIFICATE:
01437         return "Client CERT";
01438     }
01439   }
01440   else
01441 #endif
01442   if(ssl_ver == SSL3_VERSION_MAJOR) {
01443     switch(msg) {
01444       case SSL3_MT_HELLO_REQUEST:
01445         return "Hello request";
01446       case SSL3_MT_CLIENT_HELLO:
01447         return "Client hello";
01448       case SSL3_MT_SERVER_HELLO:
01449         return "Server hello";
01450 #ifdef SSL3_MT_NEWSESSION_TICKET
01451       case SSL3_MT_NEWSESSION_TICKET:
01452         return "Newsession Ticket";
01453 #endif
01454       case SSL3_MT_CERTIFICATE:
01455         return "Certificate";
01456       case SSL3_MT_SERVER_KEY_EXCHANGE:
01457         return "Server key exchange";
01458       case SSL3_MT_CLIENT_KEY_EXCHANGE:
01459         return "Client key exchange";
01460       case SSL3_MT_CERTIFICATE_REQUEST:
01461         return "Request CERT";
01462       case SSL3_MT_SERVER_DONE:
01463         return "Server finished";
01464       case SSL3_MT_CERTIFICATE_VERIFY:
01465         return "CERT verify";
01466       case SSL3_MT_FINISHED:
01467         return "Finished";
01468 #ifdef SSL3_MT_CERTIFICATE_STATUS
01469       case SSL3_MT_CERTIFICATE_STATUS:
01470         return "Certificate Status";
01471 #endif
01472     }
01473   }
01474   return "Unknown";
01475 }
01476 
01477 static const char *tls_rt_type(int type)
01478 {
01479   switch(type) {
01480 #ifdef SSL3_RT_HEADER
01481   case SSL3_RT_HEADER:
01482     return "TLS header";
01483 #endif
01484   case SSL3_RT_CHANGE_CIPHER_SPEC:
01485     return "TLS change cipher";
01486   case SSL3_RT_ALERT:
01487     return "TLS alert";
01488   case SSL3_RT_HANDSHAKE:
01489     return "TLS handshake";
01490   case SSL3_RT_APPLICATION_DATA:
01491     return "TLS app data";
01492   default:
01493     return "TLS Unknown";
01494   }
01495 }
01496 
01497 
01498 /*
01499  * Our callback from the SSL/TLS layers.
01500  */
01501 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
01502                           const void *buf, size_t len, SSL *ssl,
01503                           void *userp)
01504 {
01505   struct Curl_easy *data;
01506   const char *msg_name, *tls_rt_name;
01507   char ssl_buf[1024];
01508   char unknown[32];
01509   int msg_type, txt_len;
01510   const char *verstr = NULL;
01511   struct connectdata *conn = userp;
01512 
01513   if(!conn || !conn->data || !conn->data->set.fdebug ||
01514      (direction != 0 && direction != 1))
01515     return;
01516 
01517   data = conn->data;
01518 
01519   switch(ssl_ver) {
01520 #ifdef SSL2_VERSION /* removed in recent versions */
01521   case SSL2_VERSION:
01522     verstr = "SSLv2";
01523     break;
01524 #endif
01525 #ifdef SSL3_VERSION
01526   case SSL3_VERSION:
01527     verstr = "SSLv3";
01528     break;
01529 #endif
01530   case TLS1_VERSION:
01531     verstr = "TLSv1.0";
01532     break;
01533 #ifdef TLS1_1_VERSION
01534   case TLS1_1_VERSION:
01535     verstr = "TLSv1.1";
01536     break;
01537 #endif
01538 #ifdef TLS1_2_VERSION
01539   case TLS1_2_VERSION:
01540     verstr = "TLSv1.2";
01541     break;
01542 #endif
01543 #ifdef TLS1_3_VERSION
01544   case TLS1_3_VERSION:
01545     verstr = "TLSv1.3";
01546     break;
01547 #endif
01548   case 0:
01549     break;
01550   default:
01551     snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
01552     verstr = unknown;
01553     break;
01554   }
01555 
01556   if(ssl_ver) {
01557     /* the info given when the version is zero is not that useful for us */
01558 
01559     ssl_ver >>= 8; /* check the upper 8 bits only below */
01560 
01561     /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
01562      * always pass-up content-type as 0. But the interesting message-type
01563      * is at 'buf[0]'.
01564      */
01565     if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
01566       tls_rt_name = tls_rt_type(content_type);
01567     else
01568       tls_rt_name = "";
01569 
01570     msg_type = *(char *)buf;
01571     msg_name = ssl_msg_type(ssl_ver, msg_type);
01572 
01573     txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
01574                        verstr, direction?"OUT":"IN",
01575                        tls_rt_name, msg_name, msg_type);
01576     Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
01577   }
01578 
01579   Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
01580              CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
01581   (void) ssl;
01582 }
01583 #endif
01584 
01585 #ifdef USE_OPENSSL
01586 /* ====================================================== */
01587 
01588 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
01589 #  define use_sni(x)  sni = (x)
01590 #else
01591 #  define use_sni(x)  Curl_nop_stmt
01592 #endif
01593 
01594 /* Check for OpenSSL 1.0.2 which has ALPN support. */
01595 #undef HAS_ALPN
01596 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
01597     && !defined(OPENSSL_NO_TLSEXT)
01598 #  define HAS_ALPN 1
01599 #endif
01600 
01601 /* Check for OpenSSL 1.0.1 which has NPN support. */
01602 #undef HAS_NPN
01603 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
01604     && !defined(OPENSSL_NO_TLSEXT) \
01605     && !defined(OPENSSL_NO_NEXTPROTONEG)
01606 #  define HAS_NPN 1
01607 #endif
01608 
01609 #ifdef HAS_NPN
01610 
01611 /*
01612  * in is a list of lenght prefixed strings. this function has to select
01613  * the protocol we want to use from the list and write its string into out.
01614  */
01615 
01616 static int
01617 select_next_protocol(unsigned char **out, unsigned char *outlen,
01618                      const unsigned char *in, unsigned int inlen,
01619                      const char *key, unsigned int keylen)
01620 {
01621   unsigned int i;
01622   for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
01623     if(memcmp(&in[i + 1], key, keylen) == 0) {
01624       *out = (unsigned char *) &in[i + 1];
01625       *outlen = in[i];
01626       return 0;
01627     }
01628   }
01629   return -1;
01630 }
01631 
01632 static int
01633 select_next_proto_cb(SSL *ssl,
01634                      unsigned char **out, unsigned char *outlen,
01635                      const unsigned char *in, unsigned int inlen,
01636                      void *arg)
01637 {
01638   struct connectdata *conn = (struct connectdata*) arg;
01639 
01640   (void)ssl;
01641 
01642 #ifdef USE_NGHTTP2
01643   if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
01644      !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
01645                            NGHTTP2_PROTO_VERSION_ID_LEN)) {
01646     infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
01647           NGHTTP2_PROTO_VERSION_ID);
01648     conn->negnpn = CURL_HTTP_VERSION_2;
01649     return SSL_TLSEXT_ERR_OK;
01650   }
01651 #endif
01652 
01653   if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
01654                            ALPN_HTTP_1_1_LENGTH)) {
01655     infof(conn->data, "NPN, negotiated HTTP1.1\n");
01656     conn->negnpn = CURL_HTTP_VERSION_1_1;
01657     return SSL_TLSEXT_ERR_OK;
01658   }
01659 
01660   infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
01661   *out = (unsigned char *)ALPN_HTTP_1_1;
01662   *outlen = ALPN_HTTP_1_1_LENGTH;
01663   conn->negnpn = CURL_HTTP_VERSION_1_1;
01664 
01665   return SSL_TLSEXT_ERR_OK;
01666 }
01667 #endif /* HAS_NPN */
01668 
01669 static const char *
01670 get_ssl_version_txt(SSL *ssl)
01671 {
01672   if(!ssl)
01673     return "";
01674 
01675   switch(SSL_version(ssl)) {
01676 #ifdef TLS1_3_VERSION
01677   case TLS1_3_VERSION:
01678     return "TLSv1.3";
01679 #endif
01680 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01681   case TLS1_2_VERSION:
01682     return "TLSv1.2";
01683   case TLS1_1_VERSION:
01684     return "TLSv1.1";
01685 #endif
01686   case TLS1_VERSION:
01687     return "TLSv1.0";
01688   case SSL3_VERSION:
01689     return "SSLv3";
01690   case SSL2_VERSION:
01691     return "SSLv2";
01692   }
01693   return "unknown";
01694 }
01695 
01696 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
01697 {
01698   CURLcode result = CURLE_OK;
01699   char *ciphers;
01700   struct Curl_easy *data = conn->data;
01701   SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
01702   X509_LOOKUP *lookup = NULL;
01703   curl_socket_t sockfd = conn->sock[sockindex];
01704   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
01705   long ctx_options;
01706 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
01707   bool sni;
01708 #ifdef ENABLE_IPV6
01709   struct in6_addr addr;
01710 #else
01711   struct in_addr addr;
01712 #endif
01713 #endif
01714   long * const certverifyresult = SSL_IS_PROXY() ?
01715     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
01716   const long int ssl_version = SSL_CONN_CONFIG(version);
01717 #ifdef USE_TLS_SRP
01718   const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
01719 #endif
01720   char * const ssl_cert = SSL_SET_OPTION(cert);
01721   const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
01722   const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
01723   const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
01724   const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
01725   const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
01726   const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
01727     conn->host.name;
01728 
01729   DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
01730 
01731   /* Make funny stuff to get random input */
01732   result = Curl_ossl_seed(data);
01733   if(result)
01734     return result;
01735 
01736   *certverifyresult = !X509_V_OK;
01737 
01738   /* check to see if we've been told to use an explicit SSL/TLS version */
01739 
01740   switch(ssl_version) {
01741   case CURL_SSLVERSION_DEFAULT:
01742   case CURL_SSLVERSION_TLSv1:
01743   case CURL_SSLVERSION_TLSv1_0:
01744   case CURL_SSLVERSION_TLSv1_1:
01745   case CURL_SSLVERSION_TLSv1_2:
01746   case CURL_SSLVERSION_TLSv1_3:
01747     /* it will be handled later with the context options */
01748 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
01749     !defined(LIBRESSL_VERSION_NUMBER)
01750     req_method = TLS_client_method();
01751 #else
01752     req_method = SSLv23_client_method();
01753 #endif
01754     use_sni(TRUE);
01755     break;
01756   case CURL_SSLVERSION_SSLv2:
01757 #ifdef OPENSSL_NO_SSL2
01758     failf(data, OSSL_PACKAGE " was built without SSLv2 support");
01759     return CURLE_NOT_BUILT_IN;
01760 #else
01761 #ifdef USE_TLS_SRP
01762     if(ssl_authtype == CURL_TLSAUTH_SRP)
01763       return CURLE_SSL_CONNECT_ERROR;
01764 #endif
01765     req_method = SSLv2_client_method();
01766     use_sni(FALSE);
01767     break;
01768 #endif
01769   case CURL_SSLVERSION_SSLv3:
01770 #ifdef OPENSSL_NO_SSL3_METHOD
01771     failf(data, OSSL_PACKAGE " was built without SSLv3 support");
01772     return CURLE_NOT_BUILT_IN;
01773 #else
01774 #ifdef USE_TLS_SRP
01775     if(ssl_authtype == CURL_TLSAUTH_SRP)
01776       return CURLE_SSL_CONNECT_ERROR;
01777 #endif
01778     req_method = SSLv3_client_method();
01779     use_sni(FALSE);
01780     break;
01781 #endif
01782   default:
01783     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
01784     return CURLE_SSL_CONNECT_ERROR;
01785   }
01786 
01787   if(connssl->ctx)
01788     SSL_CTX_free(connssl->ctx);
01789   connssl->ctx = SSL_CTX_new(req_method);
01790 
01791   if(!connssl->ctx) {
01792     failf(data, "SSL: couldn't create a context: %s",
01793           ERR_error_string(ERR_peek_error(), NULL));
01794     return CURLE_OUT_OF_MEMORY;
01795   }
01796 
01797 #ifdef SSL_MODE_RELEASE_BUFFERS
01798   SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
01799 #endif
01800 
01801 #ifdef SSL_CTRL_SET_MSG_CALLBACK
01802   if(data->set.fdebug && data->set.verbose) {
01803     /* the SSL trace callback is only used for verbose logging */
01804     SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
01805     SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
01806   }
01807 #endif
01808 
01809   /* OpenSSL contains code to work-around lots of bugs and flaws in various
01810      SSL-implementations. SSL_CTX_set_options() is used to enabled those
01811      work-arounds. The man page for this option states that SSL_OP_ALL enables
01812      all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
01813      enable the bug workaround options if compatibility with somewhat broken
01814      implementations is desired."
01815 
01816      The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
01817      disable "rfc4507bis session ticket support".  rfc4507bis was later turned
01818      into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
01819 
01820      The enabled extension concerns the session management. I wonder how often
01821      libcurl stops a connection and then resumes a TLS session. also, sending
01822      the session data is some overhead. .I suggest that you just use your
01823      proposed patch (which explicitly disables TICKET).
01824 
01825      If someone writes an application with libcurl and openssl who wants to
01826      enable the feature, one can do this in the SSL callback.
01827 
01828      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
01829      interoperability with web server Netscape Enterprise Server 2.0.1 which
01830      was released back in 1996.
01831 
01832      Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
01833      become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
01834      CVE-2010-4180 when using previous OpenSSL versions we no longer enable
01835      this option regardless of OpenSSL version and SSL_OP_ALL definition.
01836 
01837      OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
01838      (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
01839      SSL_OP_ALL that _disables_ that work-around despite the fact that
01840      SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
01841      keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
01842      must not be set.
01843   */
01844 
01845   ctx_options = SSL_OP_ALL;
01846 
01847 #ifdef SSL_OP_NO_TICKET
01848   ctx_options |= SSL_OP_NO_TICKET;
01849 #endif
01850 
01851 #ifdef SSL_OP_NO_COMPRESSION
01852   ctx_options |= SSL_OP_NO_COMPRESSION;
01853 #endif
01854 
01855 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
01856   /* mitigate CVE-2010-4180 */
01857   ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
01858 #endif
01859 
01860 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
01861   /* unless the user explicitly ask to allow the protocol vulnerability we
01862      use the work-around */
01863   if(!SSL_SET_OPTION(enable_beast))
01864     ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
01865 #endif
01866 
01867   switch(ssl_version) {
01868   case CURL_SSLVERSION_SSLv3:
01869 #ifdef USE_TLS_SRP
01870     if(ssl_authtype == CURL_TLSAUTH_SRP) {
01871       infof(data, "Set version TLSv1.x for SRP authorisation\n");
01872     }
01873 #endif
01874     ctx_options |= SSL_OP_NO_SSLv2;
01875     ctx_options |= SSL_OP_NO_TLSv1;
01876 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01877     ctx_options |= SSL_OP_NO_TLSv1_1;
01878     ctx_options |= SSL_OP_NO_TLSv1_2;
01879 #ifdef TLS1_3_VERSION
01880     ctx_options |= SSL_OP_NO_TLSv1_3;
01881 #endif
01882 #endif
01883     break;
01884 
01885   case CURL_SSLVERSION_DEFAULT:
01886   case CURL_SSLVERSION_TLSv1:
01887     ctx_options |= SSL_OP_NO_SSLv2;
01888     ctx_options |= SSL_OP_NO_SSLv3;
01889     break;
01890 
01891   case CURL_SSLVERSION_TLSv1_0:
01892     ctx_options |= SSL_OP_NO_SSLv2;
01893     ctx_options |= SSL_OP_NO_SSLv3;
01894 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01895     ctx_options |= SSL_OP_NO_TLSv1_1;
01896     ctx_options |= SSL_OP_NO_TLSv1_2;
01897 #ifdef TLS1_3_VERSION
01898     ctx_options |= SSL_OP_NO_TLSv1_3;
01899 #endif
01900 #endif
01901     break;
01902 
01903   case CURL_SSLVERSION_TLSv1_1:
01904 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01905     ctx_options |= SSL_OP_NO_SSLv2;
01906     ctx_options |= SSL_OP_NO_SSLv3;
01907     ctx_options |= SSL_OP_NO_TLSv1;
01908     ctx_options |= SSL_OP_NO_TLSv1_2;
01909 #ifdef TLS1_3_VERSION
01910     ctx_options |= SSL_OP_NO_TLSv1_3;
01911 #endif
01912     break;
01913 #else
01914     failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
01915     return CURLE_NOT_BUILT_IN;
01916 #endif
01917 
01918   case CURL_SSLVERSION_TLSv1_2:
01919 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01920     ctx_options |= SSL_OP_NO_SSLv2;
01921     ctx_options |= SSL_OP_NO_SSLv3;
01922     ctx_options |= SSL_OP_NO_TLSv1;
01923     ctx_options |= SSL_OP_NO_TLSv1_1;
01924 #ifdef TLS1_3_VERSION
01925     ctx_options |= SSL_OP_NO_TLSv1_3;
01926 #endif
01927     break;
01928 #else
01929     failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
01930     return CURLE_NOT_BUILT_IN;
01931 #endif
01932 
01933   case CURL_SSLVERSION_TLSv1_3:
01934 #ifdef TLS1_3_VERSION
01935     SSL_CTX_set_max_proto_version(connssl->ctx, TLS1_3_VERSION);
01936     ctx_options |= SSL_OP_NO_SSLv2;
01937     ctx_options |= SSL_OP_NO_SSLv3;
01938     ctx_options |= SSL_OP_NO_TLSv1;
01939     ctx_options |= SSL_OP_NO_TLSv1_1;
01940     ctx_options |= SSL_OP_NO_TLSv1_2;
01941     break;
01942 #else
01943     failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
01944     return CURLE_NOT_BUILT_IN;
01945 #endif
01946 
01947   case CURL_SSLVERSION_SSLv2:
01948 #ifndef OPENSSL_NO_SSL2
01949     ctx_options |= SSL_OP_NO_SSLv3;
01950     ctx_options |= SSL_OP_NO_TLSv1;
01951 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
01952     ctx_options |= SSL_OP_NO_TLSv1_1;
01953     ctx_options |= SSL_OP_NO_TLSv1_2;
01954 #ifdef TLS1_3_VERSION
01955     ctx_options |= SSL_OP_NO_TLSv1_3;
01956 #endif
01957 #endif
01958     break;
01959 #else
01960     failf(data, OSSL_PACKAGE " was built without SSLv2 support");
01961     return CURLE_NOT_BUILT_IN;
01962 #endif
01963 
01964   default:
01965     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
01966     return CURLE_SSL_CONNECT_ERROR;
01967   }
01968 
01969   SSL_CTX_set_options(connssl->ctx, ctx_options);
01970 
01971 #ifdef HAS_NPN
01972   if(conn->bits.tls_enable_npn)
01973     SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
01974 #endif
01975 
01976 #ifdef HAS_ALPN
01977   if(conn->bits.tls_enable_alpn) {
01978     int cur = 0;
01979     unsigned char protocols[128];
01980 
01981 #ifdef USE_NGHTTP2
01982     if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
01983       protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
01984 
01985       memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
01986           NGHTTP2_PROTO_VERSION_ID_LEN);
01987       cur += NGHTTP2_PROTO_VERSION_ID_LEN;
01988       infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
01989     }
01990 #endif
01991 
01992     protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
01993     memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
01994     cur += ALPN_HTTP_1_1_LENGTH;
01995     infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
01996 
01997     /* expects length prefixed preference ordered list of protocols in wire
01998      * format
01999      */
02000     SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
02001   }
02002 #endif
02003 
02004   if(ssl_cert || ssl_cert_type) {
02005     if(!cert_stuff(conn, connssl->ctx, ssl_cert, ssl_cert_type,
02006                    SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
02007                    SSL_SET_OPTION(key_passwd))) {
02008       /* failf() is already done in cert_stuff() */
02009       return CURLE_SSL_CERTPROBLEM;
02010     }
02011   }
02012 
02013   ciphers = SSL_CONN_CONFIG(cipher_list);
02014   if(!ciphers)
02015     ciphers = (char *)DEFAULT_CIPHER_SELECTION;
02016   if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
02017     failf(data, "failed setting cipher list: %s", ciphers);
02018     return CURLE_SSL_CIPHER;
02019   }
02020   infof(data, "Cipher selection: %s\n", ciphers);
02021 
02022 #ifdef USE_TLS_SRP
02023   if(ssl_authtype == CURL_TLSAUTH_SRP) {
02024     char * const ssl_username = SSL_SET_OPTION(username);
02025 
02026     infof(data, "Using TLS-SRP username: %s\n", ssl_username);
02027 
02028     if(!SSL_CTX_set_srp_username(connssl->ctx, ssl_username)) {
02029       failf(data, "Unable to set SRP user name");
02030       return CURLE_BAD_FUNCTION_ARGUMENT;
02031     }
02032     if(!SSL_CTX_set_srp_password(connssl->ctx, SSL_SET_OPTION(password))) {
02033       failf(data, "failed setting SRP password");
02034       return CURLE_BAD_FUNCTION_ARGUMENT;
02035     }
02036     if(!SSL_CONN_CONFIG(cipher_list)) {
02037       infof(data, "Setting cipher list SRP\n");
02038 
02039       if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
02040         failf(data, "failed setting SRP cipher list");
02041         return CURLE_SSL_CIPHER;
02042       }
02043     }
02044   }
02045 #endif
02046 
02047   if(ssl_cafile || ssl_capath) {
02048     /* tell SSL where to find CA certificates that are used to verify
02049        the servers certificate. */
02050     if(!SSL_CTX_load_verify_locations(connssl->ctx, ssl_cafile, ssl_capath)) {
02051       if(verifypeer) {
02052         /* Fail if we insist on successfully verifying the server. */
02053         failf(data, "error setting certificate verify locations:\n"
02054               "  CAfile: %s\n  CApath: %s",
02055               ssl_cafile ? ssl_cafile : "none",
02056               ssl_capath ? ssl_capath : "none");
02057         return CURLE_SSL_CACERT_BADFILE;
02058       }
02059       else {
02060         /* Just continue with a warning if no strict  certificate verification
02061            is required. */
02062         infof(data, "error setting certificate verify locations,"
02063               " continuing anyway:\n");
02064       }
02065     }
02066     else {
02067       /* Everything is fine. */
02068       infof(data, "successfully set certificate verify locations:\n");
02069     }
02070     infof(data,
02071           "  CAfile: %s\n"
02072           "  CApath: %s\n",
02073           ssl_cafile ? ssl_cafile : "none",
02074           ssl_capath ? ssl_capath : "none");
02075   }
02076 #ifdef CURL_CA_FALLBACK
02077   else if(verifypeer) {
02078     /* verfying the peer without any CA certificates won't
02079        work so use openssl's built in default as fallback */
02080     SSL_CTX_set_default_verify_paths(connssl->ctx);
02081   }
02082 #endif
02083 
02084   if(ssl_crlfile) {
02085     /* tell SSL where to find CRL file that is used to check certificate
02086      * revocation */
02087     lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
02088                                  X509_LOOKUP_file());
02089     if(!lookup ||
02090        (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
02091       failf(data, "error loading CRL file: %s", ssl_crlfile);
02092       return CURLE_SSL_CRL_BADFILE;
02093     }
02094     else {
02095       /* Everything is fine. */
02096       infof(data, "successfully load CRL file:\n");
02097       X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
02098                            X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
02099     }
02100     infof(data, "  CRLfile: %s\n", ssl_crlfile);
02101   }
02102 
02103   /* Try building a chain using issuers in the trusted store first to avoid
02104   problems with server-sent legacy intermediates.
02105   Newer versions of OpenSSL do alternate chain checking by default which
02106   gives us the same fix without as much of a performance hit (slight), so we
02107   prefer that if available.
02108   https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
02109   */
02110 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
02111   if(verifypeer) {
02112     X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
02113                          X509_V_FLAG_TRUSTED_FIRST);
02114   }
02115 #endif
02116 
02117   /* SSL always tries to verify the peer, this only says whether it should
02118    * fail to connect if the verification fails, or if it should continue
02119    * anyway. In the latter case the result of the verification is checked with
02120    * SSL_get_verify_result() below. */
02121   SSL_CTX_set_verify(connssl->ctx,
02122                      verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
02123 
02124   /* give application a chance to interfere with SSL set up. */
02125   if(data->set.ssl.fsslctx) {
02126     result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
02127                                       data->set.ssl.fsslctxp);
02128     if(result) {
02129       failf(data, "error signaled by ssl ctx callback");
02130       return result;
02131     }
02132   }
02133 
02134   /* Lets make an SSL structure */
02135   if(connssl->handle)
02136     SSL_free(connssl->handle);
02137   connssl->handle = SSL_new(connssl->ctx);
02138   if(!connssl->handle) {
02139     failf(data, "SSL: couldn't create a context (handle)!");
02140     return CURLE_OUT_OF_MEMORY;
02141   }
02142 
02143 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
02144     !defined(OPENSSL_NO_OCSP)
02145   if(SSL_CONN_CONFIG(verifystatus))
02146     SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
02147 #endif
02148 
02149   SSL_set_connect_state(connssl->handle);
02150 
02151   connssl->server_cert = 0x0;
02152 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
02153   if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
02154 #ifdef ENABLE_IPV6
02155      (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
02156 #endif
02157      sni &&
02158      !SSL_set_tlsext_host_name(connssl->handle, hostname))
02159     infof(data, "WARNING: failed to configure server name indication (SNI) "
02160           "TLS extension\n");
02161 #endif
02162 
02163   /* Check if there's a cached ID we can/should use here! */
02164   if(data->set.general_ssl.sessionid) {
02165     void *ssl_sessionid = NULL;
02166 
02167     Curl_ssl_sessionid_lock(conn);
02168     if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
02169       /* we got a session id, use it! */
02170       if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
02171         Curl_ssl_sessionid_unlock(conn);
02172         failf(data, "SSL: SSL_set_session failed: %s",
02173               ERR_error_string(ERR_get_error(), NULL));
02174         return CURLE_SSL_CONNECT_ERROR;
02175       }
02176       /* Informational message */
02177       infof(data, "SSL re-using session ID\n");
02178     }
02179     Curl_ssl_sessionid_unlock(conn);
02180   }
02181 
02182   if(conn->proxy_ssl[sockindex].use) {
02183     BIO *const bio = BIO_new(BIO_f_ssl());
02184     DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
02185     DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
02186     DEBUGASSERT(bio != NULL);
02187     BIO_set_ssl(bio, conn->proxy_ssl[sockindex].handle, FALSE);
02188     SSL_set_bio(connssl->handle, bio, bio);
02189   }
02190   else if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
02191     /* pass the raw socket into the SSL layers */
02192     failf(data, "SSL: SSL_set_fd failed: %s",
02193           ERR_error_string(ERR_get_error(), NULL));
02194     return CURLE_SSL_CONNECT_ERROR;
02195   }
02196 
02197   connssl->connecting_state = ssl_connect_2;
02198 
02199   return CURLE_OK;
02200 }
02201 
02202 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
02203 {
02204   struct Curl_easy *data = conn->data;
02205   int err;
02206   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
02207   long * const certverifyresult = SSL_IS_PROXY() ?
02208     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
02209   DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
02210               || ssl_connect_2_reading == connssl->connecting_state
02211               || ssl_connect_2_writing == connssl->connecting_state);
02212 
02213   ERR_clear_error();
02214 
02215   err = SSL_connect(connssl->handle);
02216 
02217   /* 1  is fine
02218      0  is "not successful but was shut down controlled"
02219      <0 is "handshake was not successful, because a fatal error occurred" */
02220   if(1 != err) {
02221     int detail = SSL_get_error(connssl->handle, err);
02222 
02223     if(SSL_ERROR_WANT_READ == detail) {
02224       connssl->connecting_state = ssl_connect_2_reading;
02225       return CURLE_OK;
02226     }
02227     else if(SSL_ERROR_WANT_WRITE == detail) {
02228       connssl->connecting_state = ssl_connect_2_writing;
02229       return CURLE_OK;
02230     }
02231     else {
02232       /* untreated error */
02233       unsigned long errdetail;
02234       char error_buffer[256]=""; /* OpenSSL documents that this must be at
02235                                     least 256 bytes long. */
02236       CURLcode result;
02237       long lerr;
02238       int lib;
02239       int reason;
02240 
02241       /* the connection failed, we're not waiting for anything else. */
02242       connssl->connecting_state = ssl_connect_2;
02243 
02244       /* Get the earliest error code from the thread's error queue and removes
02245          the entry. */
02246       errdetail = ERR_get_error();
02247 
02248       /* Extract which lib and reason */
02249       lib = ERR_GET_LIB(errdetail);
02250       reason = ERR_GET_REASON(errdetail);
02251 
02252       if((lib == ERR_LIB_SSL) &&
02253          (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
02254         result = CURLE_SSL_CACERT;
02255 
02256         lerr = SSL_get_verify_result(connssl->handle);
02257         if(lerr != X509_V_OK) {
02258           *certverifyresult = lerr;
02259           snprintf(error_buffer, sizeof(error_buffer),
02260                    "SSL certificate problem: %s",
02261                    X509_verify_cert_error_string(lerr));
02262         }
02263         else
02264           /* strcpy() is fine here as long as the string fits within
02265              error_buffer */
02266           strcpy(error_buffer, "SSL certificate verification failed");
02267       }
02268       else {
02269         result = CURLE_SSL_CONNECT_ERROR;
02270         ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
02271       }
02272 
02273       /* detail is already set to the SSL error above */
02274 
02275       /* If we e.g. use SSLv2 request-method and the server doesn't like us
02276        * (RST connection etc.), OpenSSL gives no explanation whatsoever and
02277        * the SO_ERROR is also lost.
02278        */
02279       if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
02280         const char * const hostname = SSL_IS_PROXY() ?
02281           conn->http_proxy.host.name : conn->host.name;
02282         const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
02283         failf(data, "Unknown SSL protocol error in connection to %s:%ld ",
02284               hostname, port);
02285         return result;
02286       }
02287 
02288       /* Could be a CERT problem */
02289       failf(data, "%s", error_buffer);
02290 
02291       return result;
02292     }
02293   }
02294   else {
02295     /* we have been connected fine, we're not waiting for anything else. */
02296     connssl->connecting_state = ssl_connect_3;
02297 
02298     /* Informational message */
02299     infof(data, "SSL connection using %s / %s\n",
02300           get_ssl_version_txt(connssl->handle),
02301           SSL_get_cipher(connssl->handle));
02302 
02303 #ifdef HAS_ALPN
02304     /* Sets data and len to negotiated protocol, len is 0 if no protocol was
02305      * negotiated
02306      */
02307     if(conn->bits.tls_enable_alpn) {
02308       const unsigned char *neg_protocol;
02309       unsigned int len;
02310       SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
02311       if(len != 0) {
02312         infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
02313 
02314 #ifdef USE_NGHTTP2
02315         if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
02316            !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
02317           conn->negnpn = CURL_HTTP_VERSION_2;
02318         }
02319         else
02320 #endif
02321         if(len == ALPN_HTTP_1_1_LENGTH &&
02322            !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
02323           conn->negnpn = CURL_HTTP_VERSION_1_1;
02324         }
02325       }
02326       else
02327         infof(data, "ALPN, server did not agree to a protocol\n");
02328     }
02329 #endif
02330 
02331     return CURLE_OK;
02332   }
02333 }
02334 
02335 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
02336 {
02337   int i, ilen;
02338 
02339   ilen = (int)len;
02340   if(ilen < 0)
02341     return 1; /* buffer too big */
02342 
02343   i = i2t_ASN1_OBJECT(buf, ilen, a);
02344 
02345   if(i >= ilen)
02346     return 1; /* buffer too small */
02347 
02348   return 0;
02349 }
02350 
02351 #define push_certinfo(_label, _num) \
02352 do {                              \
02353   long info_len = BIO_get_mem_data(mem, &ptr); \
02354   Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
02355   if(1!=BIO_reset(mem))                                          \
02356     break;                                                       \
02357 } WHILE_FALSE
02358 
02359 static void pubkey_show(struct Curl_easy *data,
02360                         BIO *mem,
02361                         int num,
02362                         const char *type,
02363                         const char *name,
02364 #ifdef HAVE_OPAQUE_RSA_DSA_DH
02365                         const
02366 #endif
02367                         BIGNUM *bn)
02368 {
02369   char *ptr;
02370   char namebuf[32];
02371 
02372   snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
02373 
02374   if(bn)
02375     BN_print(mem, bn);
02376   push_certinfo(namebuf, num);
02377 }
02378 
02379 #ifdef HAVE_OPAQUE_RSA_DSA_DH
02380 #define print_pubkey_BN(_type, _name, _num)              \
02381   pubkey_show(data, mem, _num, #_type, #_name, _name)
02382 
02383 #else
02384 #define print_pubkey_BN(_type, _name, _num)    \
02385 do {                              \
02386   if(_type->_name) { \
02387     pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
02388   } \
02389 } WHILE_FALSE
02390 #endif
02391 
02392 static int X509V3_ext(struct Curl_easy *data,
02393                       int certnum,
02394                       CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
02395 {
02396   int i;
02397   size_t j;
02398 
02399   if((int)sk_X509_EXTENSION_num(exts) <= 0)
02400     /* no extensions, bail out */
02401     return 1;
02402 
02403   for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
02404     ASN1_OBJECT *obj;
02405     X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
02406     BUF_MEM *biomem;
02407     char buf[512];
02408     char *ptr=buf;
02409     char namebuf[128];
02410     BIO *bio_out = BIO_new(BIO_s_mem());
02411 
02412     if(!bio_out)
02413       return 1;
02414 
02415     obj = X509_EXTENSION_get_object(ext);
02416 
02417     asn1_object_dump(obj, namebuf, sizeof(namebuf));
02418 
02419     if(!X509V3_EXT_print(bio_out, ext, 0, 0))
02420       ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
02421 
02422     BIO_get_mem_ptr(bio_out, &biomem);
02423 
02424     for(j = 0; j < (size_t)biomem->length; j++) {
02425       const char *sep="";
02426       if(biomem->data[j] == '\n') {
02427         sep=", ";
02428         j++; /* skip the newline */
02429       };
02430       while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
02431         j++;
02432       if(j<(size_t)biomem->length)
02433         ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
02434                       biomem->data[j]);
02435     }
02436 
02437     Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
02438 
02439     BIO_free(bio_out);
02440 
02441   }
02442   return 0; /* all is fine */
02443 }
02444 
02445 static CURLcode get_cert_chain(struct connectdata *conn,
02446                                struct ssl_connect_data *connssl)
02447 
02448 {
02449   CURLcode result;
02450   STACK_OF(X509) *sk;
02451   int i;
02452   struct Curl_easy *data = conn->data;
02453   int numcerts;
02454   BIO *mem;
02455 
02456   sk = SSL_get_peer_cert_chain(connssl->handle);
02457   if(!sk) {
02458     return CURLE_OUT_OF_MEMORY;
02459   }
02460 
02461   numcerts = sk_X509_num(sk);
02462 
02463   result = Curl_ssl_init_certinfo(data, numcerts);
02464   if(result) {
02465     return result;
02466   }
02467 
02468   mem = BIO_new(BIO_s_mem());
02469 
02470   for(i = 0; i < numcerts; i++) {
02471     ASN1_INTEGER *num;
02472     X509 *x = sk_X509_value(sk, i);
02473     EVP_PKEY *pubkey=NULL;
02474     int j;
02475     char *ptr;
02476     CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
02477 
02478     X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
02479     push_certinfo("Subject", i);
02480 
02481     X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
02482     push_certinfo("Issuer", i);
02483 
02484     BIO_printf(mem, "%lx", X509_get_version(x));
02485     push_certinfo("Version", i);
02486 
02487     num = X509_get_serialNumber(x);
02488     if(num->type == V_ASN1_NEG_INTEGER)
02489       BIO_puts(mem, "-");
02490     for(j = 0; j < num->length; j++)
02491       BIO_printf(mem, "%02x", num->data[j]);
02492     push_certinfo("Serial Number", i);
02493 
02494 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
02495     {
02496       const X509_ALGOR *palg = NULL;
02497       ASN1_STRING *a = ASN1_STRING_new();
02498       if(a) {
02499         X509_get0_signature(&psig, &palg, x);
02500         X509_signature_print(mem, palg, a);
02501         ASN1_STRING_free(a);
02502 
02503         if(palg) {
02504           i2a_ASN1_OBJECT(mem, palg->algorithm);
02505           push_certinfo("Public Key Algorithm", i);
02506         }
02507       }
02508       X509V3_ext(data, i, X509_get0_extensions(x));
02509     }
02510 #else
02511     {
02512       /* before OpenSSL 1.0.2 */
02513       X509_CINF *cinf = x->cert_info;
02514 
02515       i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
02516       push_certinfo("Signature Algorithm", i);
02517 
02518       i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
02519       push_certinfo("Public Key Algorithm", i);
02520 
02521       X509V3_ext(data, i, cinf->extensions);
02522 
02523       psig = x->signature;
02524     }
02525 #endif
02526 
02527     ASN1_TIME_print(mem, X509_get0_notBefore(x));
02528     push_certinfo("Start date", i);
02529 
02530     ASN1_TIME_print(mem, X509_get0_notAfter(x));
02531     push_certinfo("Expire date", i);
02532 
02533     pubkey = X509_get_pubkey(x);
02534     if(!pubkey)
02535       infof(data, "   Unable to load public key\n");
02536     else {
02537       int pktype;
02538 #ifdef HAVE_OPAQUE_EVP_PKEY
02539       pktype = EVP_PKEY_id(pubkey);
02540 #else
02541       pktype = pubkey->type;
02542 #endif
02543       switch(pktype) {
02544       case EVP_PKEY_RSA:
02545       {
02546         RSA *rsa;
02547 #ifdef HAVE_OPAQUE_EVP_PKEY
02548         rsa = EVP_PKEY_get0_RSA(pubkey);
02549 #else
02550         rsa = pubkey->pkey.rsa;
02551 #endif
02552 
02553 #ifdef HAVE_OPAQUE_RSA_DSA_DH
02554         {
02555           const BIGNUM *n;
02556           const BIGNUM *e;
02557           const BIGNUM *d;
02558           const BIGNUM *p;
02559           const BIGNUM *q;
02560           const BIGNUM *dmp1;
02561           const BIGNUM *dmq1;
02562           const BIGNUM *iqmp;
02563 
02564           RSA_get0_key(rsa, &n, &e, &d);
02565           RSA_get0_factors(rsa, &p, &q);
02566           RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
02567           BN_print(mem, n);
02568           push_certinfo("RSA Public Key", i);
02569           print_pubkey_BN(rsa, n, i);
02570           print_pubkey_BN(rsa, e, i);
02571           print_pubkey_BN(rsa, d, i);
02572           print_pubkey_BN(rsa, p, i);
02573           print_pubkey_BN(rsa, q, i);
02574           print_pubkey_BN(rsa, dmp1, i);
02575           print_pubkey_BN(rsa, dmq1, i);
02576           print_pubkey_BN(rsa, iqmp, i);
02577         }
02578 #else
02579         BIO_printf(mem, "%d", BN_num_bits(rsa->n));
02580         push_certinfo("RSA Public Key", i);
02581         print_pubkey_BN(rsa, n, i);
02582         print_pubkey_BN(rsa, e, i);
02583         print_pubkey_BN(rsa, d, i);
02584         print_pubkey_BN(rsa, p, i);
02585         print_pubkey_BN(rsa, q, i);
02586         print_pubkey_BN(rsa, dmp1, i);
02587         print_pubkey_BN(rsa, dmq1, i);
02588         print_pubkey_BN(rsa, iqmp, i);
02589 #endif
02590 
02591         break;
02592       }
02593       case EVP_PKEY_DSA:
02594       {
02595         DSA *dsa;
02596 #ifdef HAVE_OPAQUE_EVP_PKEY
02597         dsa = EVP_PKEY_get0_DSA(pubkey);
02598 #else
02599         dsa = pubkey->pkey.dsa;
02600 #endif
02601 #ifdef HAVE_OPAQUE_RSA_DSA_DH
02602         {
02603           const BIGNUM *p;
02604           const BIGNUM *q;
02605           const BIGNUM *g;
02606           const BIGNUM *priv_key;
02607           const BIGNUM *pub_key;
02608 
02609           DSA_get0_pqg(dsa, &p, &q, &g);
02610           DSA_get0_key(dsa, &pub_key, &priv_key);
02611 
02612           print_pubkey_BN(dsa, p, i);
02613           print_pubkey_BN(dsa, q, i);
02614           print_pubkey_BN(dsa, g, i);
02615           print_pubkey_BN(dsa, priv_key, i);
02616           print_pubkey_BN(dsa, pub_key, i);
02617         }
02618 #else
02619         print_pubkey_BN(dsa, p, i);
02620         print_pubkey_BN(dsa, q, i);
02621         print_pubkey_BN(dsa, g, i);
02622         print_pubkey_BN(dsa, priv_key, i);
02623         print_pubkey_BN(dsa, pub_key, i);
02624 #endif
02625         break;
02626       }
02627       case EVP_PKEY_DH:
02628       {
02629         DH *dh;
02630 #ifdef HAVE_OPAQUE_EVP_PKEY
02631         dh = EVP_PKEY_get0_DH(pubkey);
02632 #else
02633         dh = pubkey->pkey.dh;
02634 #endif
02635 #ifdef HAVE_OPAQUE_RSA_DSA_DH
02636         {
02637           const BIGNUM *p;
02638           const BIGNUM *q;
02639           const BIGNUM *g;
02640           const BIGNUM *priv_key;
02641           const BIGNUM *pub_key;
02642           DH_get0_pqg(dh, &p, &q, &g);
02643           DH_get0_key(dh, &pub_key, &priv_key);
02644           print_pubkey_BN(dh, p, i);
02645           print_pubkey_BN(dh, q, i);
02646           print_pubkey_BN(dh, g, i);
02647           print_pubkey_BN(dh, priv_key, i);
02648           print_pubkey_BN(dh, pub_key, i);
02649        }
02650 #else
02651         print_pubkey_BN(dh, p, i);
02652         print_pubkey_BN(dh, g, i);
02653         print_pubkey_BN(dh, priv_key, i);
02654         print_pubkey_BN(dh, pub_key, i);
02655 #endif
02656         break;
02657       }
02658 #if 0
02659       case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
02660         /* left TODO */
02661         break;
02662 #endif
02663       }
02664       EVP_PKEY_free(pubkey);
02665     }
02666 
02667     if(psig) {
02668       for(j = 0; j < psig->length; j++)
02669         BIO_printf(mem, "%02x:", psig->data[j]);
02670       push_certinfo("Signature", i);
02671     }
02672 
02673     PEM_write_bio_X509(mem, x);
02674     push_certinfo("Cert", i);
02675   }
02676 
02677   BIO_free(mem);
02678 
02679   return CURLE_OK;
02680 }
02681 
02682 /*
02683  * Heavily modified from:
02684  * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
02685  */
02686 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
02687                                     const char *pinnedpubkey)
02688 {
02689   /* Scratch */
02690   int len1 = 0, len2 = 0;
02691   unsigned char *buff1 = NULL, *temp = NULL;
02692 
02693   /* Result is returned to caller */
02694   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
02695 
02696   /* if a path wasn't specified, don't pin */
02697   if(!pinnedpubkey)
02698     return CURLE_OK;
02699 
02700   if(!cert)
02701     return result;
02702 
02703   do {
02704     /* Begin Gyrations to get the subjectPublicKeyInfo     */
02705     /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
02706 
02707     /* https://groups.google.com/group/mailing.openssl.users/browse_thread
02708      /thread/d61858dae102c6c7 */
02709     len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
02710     if(len1 < 1)
02711       break; /* failed */
02712 
02713     /* https://www.openssl.org/docs/crypto/buffer.html */
02714     buff1 = temp = malloc(len1);
02715     if(!buff1)
02716       break; /* failed */
02717 
02718     /* https://www.openssl.org/docs/crypto/d2i_X509.html */
02719     len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
02720 
02721     /*
02722      * These checks are verifying we got back the same values as when we
02723      * sized the buffer. It's pretty weak since they should always be the
02724      * same. But it gives us something to test.
02725      */
02726     if((len1 != len2) || !temp || ((temp - buff1) != len1))
02727       break; /* failed */
02728 
02729     /* End Gyrations */
02730 
02731     /* The one good exit point */
02732     result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
02733   } while(0);
02734 
02735   /* https://www.openssl.org/docs/crypto/buffer.html */
02736   if(buff1)
02737     free(buff1);
02738 
02739   return result;
02740 }
02741 
02742 /*
02743  * Get the server cert, verify it and show it etc, only call failf() if the
02744  * 'strict' argument is TRUE as otherwise all this is for informational
02745  * purposes only!
02746  *
02747  * We check certificates to authenticate the server; otherwise we risk
02748  * man-in-the-middle attack.
02749  */
02750 static CURLcode servercert(struct connectdata *conn,
02751                            struct ssl_connect_data *connssl,
02752                            bool strict)
02753 {
02754   CURLcode result = CURLE_OK;
02755   int rc;
02756   long lerr, len;
02757   struct Curl_easy *data = conn->data;
02758   X509 *issuer;
02759   FILE *fp;
02760   char *buffer = data->state.buffer;
02761   const char *ptr;
02762   long * const certverifyresult = SSL_IS_PROXY() ?
02763     &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
02764   BIO *mem = BIO_new(BIO_s_mem());
02765 
02766   if(data->set.ssl.certinfo)
02767     /* we've been asked to gather certificate info! */
02768     (void)get_cert_chain(conn, connssl);
02769 
02770   connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
02771   if(!connssl->server_cert) {
02772     if(!strict)
02773       return CURLE_OK;
02774 
02775     failf(data, "SSL: couldn't get peer certificate!");
02776     return CURLE_PEER_FAILED_VERIFICATION;
02777   }
02778 
02779   infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
02780 
02781   rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
02782                          buffer, BUFSIZE);
02783   infof(data, " subject: %s\n", rc?"[NONE]":buffer);
02784 
02785   ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
02786   len = BIO_get_mem_data(mem, (char **) &ptr);
02787   infof(data, " start date: %.*s\n", len, ptr);
02788   rc = BIO_reset(mem);
02789 
02790   ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
02791   len = BIO_get_mem_data(mem, (char **) &ptr);
02792   infof(data, " expire date: %.*s\n", len, ptr);
02793   rc = BIO_reset(mem);
02794 
02795   BIO_free(mem);
02796 
02797   if(SSL_CONN_CONFIG(verifyhost)) {
02798     result = verifyhost(conn, connssl->server_cert);
02799     if(result) {
02800       X509_free(connssl->server_cert);
02801       connssl->server_cert = NULL;
02802       return result;
02803     }
02804   }
02805 
02806   rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
02807                          buffer, BUFSIZE);
02808   if(rc) {
02809     if(strict)
02810       failf(data, "SSL: couldn't get X509-issuer name!");
02811     result = CURLE_SSL_CONNECT_ERROR;
02812   }
02813   else {
02814     infof(data, " issuer: %s\n", buffer);
02815 
02816     /* We could do all sorts of certificate verification stuff here before
02817        deallocating the certificate. */
02818 
02819     /* e.g. match issuer name with provided issuer certificate */
02820     if(SSL_SET_OPTION(issuercert)) {
02821       fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
02822       if(!fp) {
02823         if(strict)
02824           failf(data, "SSL: Unable to open issuer cert (%s)",
02825                 SSL_SET_OPTION(issuercert));
02826         X509_free(connssl->server_cert);
02827         connssl->server_cert = NULL;
02828         return CURLE_SSL_ISSUER_ERROR;
02829       }
02830 
02831       issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
02832       if(!issuer) {
02833         if(strict)
02834           failf(data, "SSL: Unable to read issuer cert (%s)",
02835                 SSL_SET_OPTION(issuercert));
02836         X509_free(connssl->server_cert);
02837         X509_free(issuer);
02838         fclose(fp);
02839         return CURLE_SSL_ISSUER_ERROR;
02840       }
02841 
02842       fclose(fp);
02843 
02844       if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
02845         if(strict)
02846           failf(data, "SSL: Certificate issuer check failed (%s)",
02847                 SSL_SET_OPTION(issuercert));
02848         X509_free(connssl->server_cert);
02849         X509_free(issuer);
02850         connssl->server_cert = NULL;
02851         return CURLE_SSL_ISSUER_ERROR;
02852       }
02853 
02854       infof(data, " SSL certificate issuer check ok (%s)\n",
02855             SSL_SET_OPTION(issuercert));
02856       X509_free(issuer);
02857     }
02858 
02859     lerr = *certverifyresult = SSL_get_verify_result(connssl->handle);
02860 
02861     if(*certverifyresult != X509_V_OK) {
02862       if(SSL_CONN_CONFIG(verifypeer)) {
02863         /* We probably never reach this, because SSL_connect() will fail
02864            and we return earlier if verifypeer is set? */
02865         if(strict)
02866           failf(data, "SSL certificate verify result: %s (%ld)",
02867                 X509_verify_cert_error_string(lerr), lerr);
02868         result = CURLE_PEER_FAILED_VERIFICATION;
02869       }
02870       else
02871         infof(data, " SSL certificate verify result: %s (%ld),"
02872               " continuing anyway.\n",
02873               X509_verify_cert_error_string(lerr), lerr);
02874     }
02875     else
02876       infof(data, " SSL certificate verify ok.\n");
02877   }
02878 
02879 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
02880     !defined(OPENSSL_NO_OCSP)
02881   if(SSL_CONN_CONFIG(verifystatus)) {
02882     result = verifystatus(conn, connssl);
02883     if(result) {
02884       X509_free(connssl->server_cert);
02885       connssl->server_cert = NULL;
02886       return result;
02887     }
02888   }
02889 #endif
02890 
02891   if(!strict)
02892     /* when not strict, we don't bother about the verify cert problems */
02893     result = CURLE_OK;
02894 
02895   ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
02896                          data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
02897   if(!result && ptr) {
02898     result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
02899     if(result)
02900       failf(data, "SSL: public key does not match pinned public key!");
02901   }
02902 
02903   X509_free(connssl->server_cert);
02904   connssl->server_cert = NULL;
02905   connssl->connecting_state = ssl_connect_done;
02906 
02907   return result;
02908 }
02909 
02910 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
02911 {
02912   CURLcode result = CURLE_OK;
02913   struct Curl_easy *data = conn->data;
02914   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
02915 
02916   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
02917 
02918   if(data->set.general_ssl.sessionid) {
02919     bool incache;
02920     SSL_SESSION *our_ssl_sessionid;
02921     void *old_ssl_sessionid = NULL;
02922 
02923     our_ssl_sessionid = SSL_get1_session(connssl->handle);
02924 
02925     /* SSL_get1_session() will increment the reference count and the session
02926         will stay in memory until explicitly freed with SSL_SESSION_free(3),
02927         regardless of its state. */
02928 
02929     Curl_ssl_sessionid_lock(conn);
02930     incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
02931                                       sockindex));
02932     if(incache) {
02933       if(old_ssl_sessionid != our_ssl_sessionid) {
02934         infof(data, "old SSL session ID is stale, removing\n");
02935         Curl_ssl_delsessionid(conn, old_ssl_sessionid);
02936         incache = FALSE;
02937       }
02938     }
02939 
02940     if(!incache) {
02941       result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
02942                                       0 /* unknown size */, sockindex);
02943       if(result) {
02944         Curl_ssl_sessionid_unlock(conn);
02945         failf(data, "failed to store ssl session");
02946         return result;
02947       }
02948     }
02949     else {
02950       /* Session was incache, so refcount already incremented earlier.
02951         * Avoid further increments with each SSL_get1_session() call.
02952         * This does not free the session as refcount remains > 0
02953         */
02954       SSL_SESSION_free(our_ssl_sessionid);
02955     }
02956     Curl_ssl_sessionid_unlock(conn);
02957   }
02958 
02959   /*
02960    * We check certificates to authenticate the server; otherwise we risk
02961    * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
02962    * verify the peer ignore faults and failures from the server cert
02963    * operations.
02964    */
02965 
02966   result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
02967                                       SSL_CONN_CONFIG(verifyhost)));
02968 
02969   if(!result)
02970     connssl->connecting_state = ssl_connect_done;
02971 
02972   return result;
02973 }
02974 
02975 static Curl_recv ossl_recv;
02976 static Curl_send ossl_send;
02977 
02978 static CURLcode ossl_connect_common(struct connectdata *conn,
02979                                     int sockindex,
02980                                     bool nonblocking,
02981                                     bool *done)
02982 {
02983   CURLcode result;
02984   struct Curl_easy *data = conn->data;
02985   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
02986   curl_socket_t sockfd = conn->sock[sockindex];
02987   time_t timeout_ms;
02988   int what;
02989 
02990   /* check if the connection has already been established */
02991   if(ssl_connection_complete == connssl->state) {
02992     *done = TRUE;
02993     return CURLE_OK;
02994   }
02995 
02996   if(ssl_connect_1 == connssl->connecting_state) {
02997     /* Find out how much more time we're allowed */
02998     timeout_ms = Curl_timeleft(data, NULL, TRUE);
02999 
03000     if(timeout_ms < 0) {
03001       /* no need to continue if time already is up */
03002       failf(data, "SSL connection timeout");
03003       return CURLE_OPERATION_TIMEDOUT;
03004     }
03005 
03006     result = ossl_connect_step1(conn, sockindex);
03007     if(result)
03008       return result;
03009   }
03010 
03011   while(ssl_connect_2 == connssl->connecting_state ||
03012         ssl_connect_2_reading == connssl->connecting_state ||
03013         ssl_connect_2_writing == connssl->connecting_state) {
03014 
03015     /* check allowed time left */
03016     timeout_ms = Curl_timeleft(data, NULL, TRUE);
03017 
03018     if(timeout_ms < 0) {
03019       /* no need to continue if time already is up */
03020       failf(data, "SSL connection timeout");
03021       return CURLE_OPERATION_TIMEDOUT;
03022     }
03023 
03024     /* if ssl is expecting something, check if it's available. */
03025     if(connssl->connecting_state == ssl_connect_2_reading ||
03026        connssl->connecting_state == ssl_connect_2_writing) {
03027 
03028       curl_socket_t writefd = ssl_connect_2_writing==
03029         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
03030       curl_socket_t readfd = ssl_connect_2_reading==
03031         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
03032 
03033       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
03034                                nonblocking?0:timeout_ms);
03035       if(what < 0) {
03036         /* fatal error */
03037         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
03038         return CURLE_SSL_CONNECT_ERROR;
03039       }
03040       else if(0 == what) {
03041         if(nonblocking) {
03042           *done = FALSE;
03043           return CURLE_OK;
03044         }
03045         else {
03046           /* timeout */
03047           failf(data, "SSL connection timeout");
03048           return CURLE_OPERATION_TIMEDOUT;
03049         }
03050       }
03051       /* socket is readable or writable */
03052     }
03053 
03054     /* Run transaction, and return to the caller if it failed or if this
03055      * connection is done nonblocking and this loop would execute again. This
03056      * permits the owner of a multi handle to abort a connection attempt
03057      * before step2 has completed while ensuring that a client using select()
03058      * or epoll() will always have a valid fdset to wait on.
03059      */
03060     result = ossl_connect_step2(conn, sockindex);
03061     if(result || (nonblocking &&
03062                   (ssl_connect_2 == connssl->connecting_state ||
03063                    ssl_connect_2_reading == connssl->connecting_state ||
03064                    ssl_connect_2_writing == connssl->connecting_state)))
03065       return result;
03066 
03067   } /* repeat step2 until all transactions are done. */
03068 
03069   if(ssl_connect_3 == connssl->connecting_state) {
03070     result = ossl_connect_step3(conn, sockindex);
03071     if(result)
03072       return result;
03073   }
03074 
03075   if(ssl_connect_done == connssl->connecting_state) {
03076     connssl->state = ssl_connection_complete;
03077     conn->recv[sockindex] = ossl_recv;
03078     conn->send[sockindex] = ossl_send;
03079     *done = TRUE;
03080   }
03081   else
03082     *done = FALSE;
03083 
03084   /* Reset our connect state machine */
03085   connssl->connecting_state = ssl_connect_1;
03086 
03087   return CURLE_OK;
03088 }
03089 
03090 CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
03091                                        int sockindex,
03092                                        bool *done)
03093 {
03094   return ossl_connect_common(conn, sockindex, TRUE, done);
03095 }
03096 
03097 CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
03098 {
03099   CURLcode result;
03100   bool done = FALSE;
03101 
03102   result = ossl_connect_common(conn, sockindex, FALSE, &done);
03103   if(result)
03104     return result;
03105 
03106   DEBUGASSERT(done);
03107 
03108   return CURLE_OK;
03109 }
03110 
03111 bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
03112 {
03113   if(conn->ssl[connindex].handle)
03114     /* SSL is in use */
03115     return (0 != SSL_pending(conn->ssl[connindex].handle) ||
03116            (conn->proxy_ssl[connindex].handle &&
03117             0 != SSL_pending(conn->proxy_ssl[connindex].handle))) ?
03118            TRUE : FALSE;
03119   else
03120     return FALSE;
03121 }
03122 
03123 static ssize_t ossl_send(struct connectdata *conn,
03124                          int sockindex,
03125                          const void *mem,
03126                          size_t len,
03127                          CURLcode *curlcode)
03128 {
03129   /* SSL_write() is said to return 'int' while write() and send() returns
03130      'size_t' */
03131   int err;
03132   char error_buffer[256]; /* OpenSSL documents that this must be at least 256
03133                              bytes long. */
03134   unsigned long sslerror;
03135   int memlen;
03136   int rc;
03137 
03138   ERR_clear_error();
03139 
03140   memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
03141   rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
03142 
03143   if(rc <= 0) {
03144     err = SSL_get_error(conn->ssl[sockindex].handle, rc);
03145 
03146     switch(err) {
03147     case SSL_ERROR_WANT_READ:
03148     case SSL_ERROR_WANT_WRITE:
03149       /* The operation did not complete; the same TLS/SSL I/O function
03150          should be called again later. This is basically an EWOULDBLOCK
03151          equivalent. */
03152       *curlcode = CURLE_AGAIN;
03153       return -1;
03154     case SSL_ERROR_SYSCALL:
03155       failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
03156             SOCKERRNO);
03157       *curlcode = CURLE_SEND_ERROR;
03158       return -1;
03159     case SSL_ERROR_SSL:
03160       /*  A failure in the SSL library occurred, usually a protocol error.
03161           The OpenSSL error queue contains more information on the error. */
03162       sslerror = ERR_get_error();
03163       if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
03164          ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
03165          conn->ssl[sockindex].state == ssl_connection_complete &&
03166          conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
03167         char ver[120];
03168         Curl_ossl_version(ver, 120);
03169         failf(conn->data, "Error: %s does not support double SSL tunneling.",
03170               ver);
03171       }
03172       else
03173         failf(conn->data, "SSL_write() error: %s",
03174               ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
03175       *curlcode = CURLE_SEND_ERROR;
03176       return -1;
03177     }
03178     /* a true error */
03179     failf(conn->data, "SSL_write() return error %d", err);
03180     *curlcode = CURLE_SEND_ERROR;
03181     return -1;
03182   }
03183   *curlcode = CURLE_OK;
03184   return (ssize_t)rc; /* number of bytes */
03185 }
03186 
03187 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
03188                          int num,                  /* socketindex */
03189                          char *buf,                /* store read data here */
03190                          size_t buffersize,        /* max amount to read */
03191                          CURLcode *curlcode)
03192 {
03193   char error_buffer[256]; /* OpenSSL documents that this must be at
03194                              least 256 bytes long. */
03195   unsigned long sslerror;
03196   ssize_t nread;
03197   int buffsize;
03198 
03199   ERR_clear_error();
03200 
03201   buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
03202   nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
03203   if(nread <= 0) {
03204     /* failed SSL_read */
03205     int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
03206 
03207     switch(err) {
03208     case SSL_ERROR_NONE: /* this is not an error */
03209     case SSL_ERROR_ZERO_RETURN: /* no more data */
03210       break;
03211     case SSL_ERROR_WANT_READ:
03212     case SSL_ERROR_WANT_WRITE:
03213       /* there's data pending, re-invoke SSL_read() */
03214       *curlcode = CURLE_AGAIN;
03215       return -1;
03216     default:
03217       /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
03218          value/errno" */
03219       /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
03220       sslerror = ERR_get_error();
03221       if((nread < 0) || sslerror) {
03222         /* If the return code was negative or there actually is an error in the
03223            queue */
03224         failf(conn->data, "SSL read: %s, errno %d",
03225               ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)),
03226               SOCKERRNO);
03227         *curlcode = CURLE_RECV_ERROR;
03228         return -1;
03229       }
03230     }
03231   }
03232   return nread;
03233 }
03234 
03235 size_t Curl_ossl_version(char *buffer, size_t size)
03236 {
03237 #ifdef OPENSSL_IS_BORINGSSL
03238   return snprintf(buffer, size, OSSL_PACKAGE);
03239 #else /* OPENSSL_IS_BORINGSSL */
03240   char sub[3];
03241   unsigned long ssleay_value;
03242   sub[2]='\0';
03243   sub[1]='\0';
03244   ssleay_value=OpenSSL_version_num();
03245   if(ssleay_value < 0x906000) {
03246     ssleay_value=SSLEAY_VERSION_NUMBER;
03247     sub[0]='\0';
03248   }
03249   else {
03250     if(ssleay_value&0xff0) {
03251       int minor_ver = (ssleay_value >> 4) & 0xff;
03252       if(minor_ver > 26) {
03253         /* handle extended version introduced for 0.9.8za */
03254         sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
03255         sub[0] = 'z';
03256       }
03257       else {
03258         sub[0] = (char) (minor_ver + 'a' - 1);
03259       }
03260     }
03261     else
03262       sub[0]='\0';
03263   }
03264 
03265   return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
03266                   OSSL_PACKAGE,
03267                   (ssleay_value>>28)&0xf,
03268                   (ssleay_value>>20)&0xff,
03269                   (ssleay_value>>12)&0xff,
03270                   sub);
03271 #endif /* OPENSSL_IS_BORINGSSL */
03272 }
03273 
03274 /* can be called with data == NULL */
03275 int Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
03276                      size_t length)
03277 {
03278   if(data) {
03279     if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
03280       return 1; /* couldn't seed for some reason */
03281   }
03282   else {
03283     if(!rand_enough())
03284       return 1;
03285   }
03286   RAND_bytes(entropy, curlx_uztosi(length));
03287   return 0; /* 0 as in no problem */
03288 }
03289 
03290 void Curl_ossl_md5sum(unsigned char *tmp, /* input */
03291                       size_t tmplen,
03292                       unsigned char *md5sum /* output */,
03293                       size_t unused)
03294 {
03295   MD5_CTX MD5pw;
03296   (void)unused;
03297   MD5_Init(&MD5pw);
03298   MD5_Update(&MD5pw, tmp, tmplen);
03299   MD5_Final(md5sum, &MD5pw);
03300 }
03301 
03302 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
03303 void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
03304                       size_t tmplen,
03305                       unsigned char *sha256sum /* output */,
03306                       size_t unused)
03307 {
03308   SHA256_CTX SHA256pw;
03309   (void)unused;
03310   SHA256_Init(&SHA256pw);
03311   SHA256_Update(&SHA256pw, tmp, tmplen);
03312   SHA256_Final(sha256sum, &SHA256pw);
03313 }
03314 #endif
03315 
03316 bool Curl_ossl_cert_status_request(void)
03317 {
03318 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
03319     !defined(OPENSSL_NO_OCSP)
03320   return TRUE;
03321 #else
03322   return FALSE;
03323 #endif
03324 }
03325 #endif /* USE_OPENSSL */


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:05