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