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