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