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