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