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