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