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