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