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