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