Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Utilities / cmcurl-7.19.0 / lib / ssluse.c
blob2cc4a148bb9d1e0433853bdb385c730b006fd127
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 * $Id: ssluse.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
22 ***************************************************************************/
25 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
26 * but sslgen.c should ever call or use these functions.
30 * The original SSLeay-using code for curl was written by Linas Vepstas and
31 * Sampo Kellomaki 1998.
34 #include "setup.h"
36 #include <string.h>
37 #include <stdlib.h>
38 #include <ctype.h>
39 #ifdef HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
43 #include "urldata.h"
44 #include "sendf.h"
45 #include "formdata.h" /* for the boundary function */
46 #include "url.h" /* for the ssl config check function */
47 #include "inet_pton.h"
48 #include "ssluse.h"
49 #include "connect.h"
50 #include "strequal.h"
51 #include "select.h"
52 #include "sslgen.h"
54 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
55 #include <curl/mprintf.h>
57 #ifdef USE_SSLEAY
59 #ifdef USE_OPENSSL
60 #include <openssl/rand.h>
61 #include <openssl/x509v3.h>
62 #else
63 #include <rand.h>
64 #include <x509v3.h>
65 #endif
67 #include "memory.h"
68 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
70 /* The last #include file should be: */
71 #include "memdebug.h"
73 #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
74 #define HAVE_SSL_GET1_SESSION 1
75 #else
76 #undef HAVE_SSL_GET1_SESSION
77 #endif
79 #if OPENSSL_VERSION_NUMBER >= 0x00904100L
80 #define HAVE_USERDATA_IN_PWD_CALLBACK 1
81 #else
82 #undef HAVE_USERDATA_IN_PWD_CALLBACK
83 #endif
85 #if OPENSSL_VERSION_NUMBER >= 0x00907001L
86 /* ENGINE_load_private_key() takes four arguments */
87 #define HAVE_ENGINE_LOAD_FOUR_ARGS
88 #else
89 /* ENGINE_load_private_key() takes three arguments */
90 #undef HAVE_ENGINE_LOAD_FOUR_ARGS
91 #endif
93 #if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
94 /* OpenSSL has PKCS 12 support */
95 #define HAVE_PKCS12_SUPPORT
96 #else
97 /* OpenSSL/SSLEay does not have PKCS12 support */
98 #undef HAVE_PKCS12_SUPPORT
99 #endif
101 #if OPENSSL_VERSION_NUMBER >= 0x00906001L
102 #define HAVE_ERR_ERROR_STRING_N 1
103 #endif
105 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
106 #define SSL_METHOD_QUAL const
107 #else
108 #define SSL_METHOD_QUAL
109 #endif
111 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
112 /* 0.9.6 didn't have X509_STORE_set_flags() */
113 #define HAVE_X509_STORE_SET_FLAGS 1
114 #else
115 #define X509_STORE_set_flags(x,y)
116 #endif
119 * Number of bytes to read from the random number seed file. This must be
120 * a finite value (because some entropy "files" like /dev/urandom have
121 * an infinite length), but must be large enough to provide enough
122 * entopy to properly seed OpenSSL's PRNG.
124 #define RAND_LOAD_LENGTH 1024
126 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
127 static char global_passwd[64];
128 #endif
130 static int passwd_callback(char *buf, int num, int verify
131 #ifdef HAVE_USERDATA_IN_PWD_CALLBACK
132 /* This was introduced in 0.9.4, we can set this
133 using SSL_CTX_set_default_passwd_cb_userdata()
135 , void *global_passwd
136 #endif
139 if(verify)
140 fprintf(stderr, "%s\n", buf);
141 else {
142 if(num > (int)strlen((char *)global_passwd)) {
143 strcpy(buf, global_passwd);
144 return (int)strlen(buf);
147 return 0;
151 * rand_enough() is a function that returns TRUE if we have seeded the random
152 * engine properly. We use some preprocessor magic to provide a seed_enough()
153 * macro to use, just to prevent a compiler warning on this function if we
154 * pass in an argument that is never used.
157 #ifdef HAVE_RAND_STATUS
158 #define seed_enough(x) rand_enough()
159 static bool rand_enough(void)
161 return (bool)(0 != RAND_status());
163 #else
164 #define seed_enough(x) rand_enough(x)
165 static bool rand_enough(int nread)
167 /* this is a very silly decision to make */
168 return (bool)(nread > 500);
170 #endif
172 static int ossl_seed(struct SessionHandle *data)
174 char *buf = data->state.buffer; /* point to the big buffer */
175 int nread=0;
177 /* Q: should we add support for a random file name as a libcurl option?
178 A: Yes, it is here */
180 #ifndef RANDOM_FILE
181 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
182 us to! */
183 if(data->set.ssl.random_file)
184 #define RANDOM_FILE "" /* doesn't matter won't be used */
185 #endif
187 /* let the option override the define */
188 nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
189 data->set.str[STRING_SSL_RANDOM_FILE]:
190 RANDOM_FILE),
191 RAND_LOAD_LENGTH);
192 if(seed_enough(nread))
193 return nread;
196 #if defined(HAVE_RAND_EGD)
197 /* only available in OpenSSL 0.9.5 and later */
198 /* EGD_SOCKET is set at configure time or not at all */
199 #ifndef EGD_SOCKET
200 /* If we don't have the define set, we only do this if the egd-option
201 is set */
202 if(data->set.str[STRING_SSL_EGDSOCKET])
203 #define EGD_SOCKET "" /* doesn't matter won't be used */
204 #endif
206 /* If there's an option and a define, the option overrides the
207 define */
208 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
209 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
210 if(-1 != ret) {
211 nread += ret;
212 if(seed_enough(nread))
213 return nread;
216 #endif
218 /* If we get here, it means we need to seed the PRNG using a "silly"
219 approach! */
220 #ifdef HAVE_RAND_SCREEN
221 /* This one gets a random value by reading the currently shown screen */
222 RAND_screen();
223 nread = 100; /* just a value */
224 #else
226 int len;
227 char *area;
229 /* Changed call to RAND_seed to use the underlying RAND_add implementation
230 * directly. Do this in a loop, with the amount of additional entropy
231 * being dependent upon the algorithm used by Curl_FormBoundary(): N bytes
232 * of a 7-bit ascii set. -- Richard Gorton, March 11 2003.
235 do {
236 area = Curl_FormBoundary();
237 if(!area)
238 return 3; /* out of memory */
240 len = (int)strlen(area);
241 RAND_add(area, len, (len >> 1));
243 free(area); /* now remove the random junk */
244 } while(!RAND_status());
246 #endif
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;
258 infof(data, "libcurl is now using a weak random seed!\n");
259 return nread;
262 int Curl_ossl_seed(struct SessionHandle *data)
264 /* we have the "SSL is seeded" boolean static to prevent multiple
265 time-consuming seedings in vain */
266 static bool ssl_seeded = FALSE;
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;
273 return 0;
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)
285 if(!type || !type[0])
286 return SSL_FILETYPE_PEM;
287 if(curl_strequal(type, "PEM"))
288 return SSL_FILETYPE_PEM;
289 if(curl_strequal(type, "DER"))
290 return SSL_FILETYPE_ASN1;
291 if(curl_strequal(type, "ENG"))
292 return SSL_FILETYPE_ENGINE;
293 if(curl_strequal(type, "P12"))
294 return SSL_FILETYPE_PKCS12;
295 return -1;
298 static
299 int cert_stuff(struct connectdata *conn,
300 SSL_CTX* ctx,
301 char *cert_file,
302 const char *cert_type,
303 char *key_file,
304 const char *key_type)
306 struct SessionHandle *data = conn->data;
307 int file_type;
309 if(cert_file != NULL) {
310 SSL *ssl;
311 X509 *x509;
312 int cert_done = 0;
314 if(data->set.str[STRING_KEY_PASSWD]) {
315 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
317 * If password has been given, we store that in the global
318 * area (*shudder*) for a while:
320 size_t len = strlen(data->set.key_passwd);
321 if(len < sizeof(global_passwd))
322 memcpy(global_passwd, data->set.key_passwd, len+1);
323 #else
325 * We set the password in the callback userdata
327 SSL_CTX_set_default_passwd_cb_userdata(ctx,
328 data->set.str[STRING_KEY_PASSWD]);
329 #endif
330 /* Set passwd callback: */
331 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
334 file_type = do_file_type(cert_type);
336 #define SSL_CLIENT_CERT_ERR \
337 "unable to use client certificate (no key found or wrong pass phrase?)"
339 switch(file_type) {
340 case SSL_FILETYPE_PEM:
341 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
342 if(SSL_CTX_use_certificate_chain_file(ctx,
343 cert_file) != 1) {
344 failf(data, SSL_CLIENT_CERT_ERR);
345 return 0;
347 break;
349 case SSL_FILETYPE_ASN1:
350 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
351 we use the case above for PEM so this can only be performed with
352 ASN1 files. */
353 if(SSL_CTX_use_certificate_file(ctx,
354 cert_file,
355 file_type) != 1) {
356 failf(data, SSL_CLIENT_CERT_ERR);
357 return 0;
359 break;
360 case SSL_FILETYPE_ENGINE:
361 failf(data, "file type ENG for certificate not implemented");
362 return 0;
364 case SSL_FILETYPE_PKCS12:
366 #ifdef HAVE_PKCS12_SUPPORT
367 FILE *f;
368 PKCS12 *p12;
369 EVP_PKEY *pri;
370 STACK_OF(X509) *ca = NULL;
371 int i;
373 f = fopen(cert_file,"rb");
374 if(!f) {
375 failf(data, "could not open PKCS12 file '%s'", cert_file);
376 return 0;
378 p12 = d2i_PKCS12_fp(f, NULL);
379 fclose(f);
381 if(!p12) {
382 failf(data, "error reading PKCS12 file '%s'", cert_file );
383 return 0;
386 PKCS12_PBE_add();
388 if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509,
389 &ca)) {
390 failf(data,
391 "could not parse PKCS12 file, check password, OpenSSL error %s",
392 ERR_error_string(ERR_get_error(), NULL) );
393 PKCS12_free(p12);
394 return 0;
397 PKCS12_free(p12);
399 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
400 failf(data, SSL_CLIENT_CERT_ERR);
401 EVP_PKEY_free(pri);
402 X509_free(x509);
403 return 0;
406 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
407 failf(data, "unable to use private key from PKCS12 file '%s'",
408 cert_file);
409 EVP_PKEY_free(pri);
410 X509_free(x509);
411 return 0;
414 if (!SSL_CTX_check_private_key (ctx)) {
415 failf(data, "private key from PKCS12 file '%s' "
416 "does not match certificate in same file", cert_file);
417 EVP_PKEY_free(pri);
418 X509_free(x509);
419 return 0;
421 /* Set Certificate Verification chain */
422 if (ca && sk_num(ca)) {
423 for (i = 0; i < sk_X509_num(ca); i++) {
424 if (!SSL_CTX_add_extra_chain_cert(ctx,sk_X509_value(ca, i))) {
425 failf(data, "cannot add certificate to certificate chain");
426 EVP_PKEY_free(pri);
427 X509_free(x509);
428 return 0;
430 if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i))) {
431 failf(data, "cannot add certificate to client CA list",
432 cert_file);
433 EVP_PKEY_free(pri);
434 X509_free(x509);
435 return 0;
440 EVP_PKEY_free(pri);
441 X509_free(x509);
442 cert_done = 1;
443 break;
444 #else
445 failf(data, "file type P12 for certificate not supported");
446 return 0;
447 #endif
449 default:
450 failf(data, "not supported file type '%s' for certificate", cert_type);
451 return 0;
454 file_type = do_file_type(key_type);
456 switch(file_type) {
457 case SSL_FILETYPE_PEM:
458 if(cert_done)
459 break;
460 if(key_file == NULL)
461 /* cert & key can only be in PEM case in the same file */
462 key_file=cert_file;
463 case SSL_FILETYPE_ASN1:
464 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
465 failf(data, "unable to set private key file: '%s' type %s",
466 key_file, key_type?key_type:"PEM");
467 return 0;
469 break;
470 case SSL_FILETYPE_ENGINE:
471 #ifdef HAVE_OPENSSL_ENGINE_H
472 { /* XXXX still needs some work */
473 EVP_PKEY *priv_key = NULL;
474 if(data->state.engine) {
475 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
476 UI_METHOD *ui_method = UI_OpenSSL();
477 #endif
478 if(!key_file || !key_file[0]) {
479 failf(data, "no key set to load from crypto engine");
480 return 0;
482 /* the typecast below was added to please mingw32 */
483 priv_key = (EVP_PKEY *)
484 ENGINE_load_private_key(data->state.engine,key_file,
485 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
486 ui_method,
487 #endif
488 data->set.str[STRING_KEY_PASSWD]);
489 if(!priv_key) {
490 failf(data, "failed to load private key from crypto engine");
491 return 0;
493 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
494 failf(data, "unable to set private key");
495 EVP_PKEY_free(priv_key);
496 return 0;
498 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
500 else {
501 failf(data, "crypto engine not set, can't load private key");
502 return 0;
505 break;
506 #else
507 failf(data, "file type ENG for private key not supported");
508 return 0;
509 #endif
510 case SSL_FILETYPE_PKCS12:
511 if(!cert_done) {
512 failf(data, "file type P12 for private key not supported");
513 return 0;
515 break;
516 default:
517 failf(data, "not supported file type for private key");
518 return 0;
521 ssl=SSL_new(ctx);
522 if(NULL == ssl) {
523 failf(data,"unable to create an SSL structure");
524 return 0;
527 x509=SSL_get_certificate(ssl);
529 /* This version was provided by Evan Jordan and is supposed to not
530 leak memory as the previous version: */
531 if(x509 != NULL) {
532 EVP_PKEY *pktmp = X509_get_pubkey(x509);
533 EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
534 EVP_PKEY_free(pktmp);
537 SSL_free(ssl);
539 /* If we are using DSA, we can copy the parameters from
540 * the private key */
543 /* Now we know that a key and cert have been set against
544 * the SSL context */
545 if(!SSL_CTX_check_private_key(ctx)) {
546 failf(data, "Private key does not match the certificate public key");
547 return(0);
549 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
550 /* erase it now */
551 memset(global_passwd, 0, sizeof(global_passwd));
552 #endif
554 return(1);
557 static
558 int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
560 X509 *err_cert;
561 char buf[256];
563 err_cert=X509_STORE_CTX_get_current_cert(ctx);
564 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
565 return ok;
568 /* Return error string for last OpenSSL error
570 static char *SSL_strerror(unsigned long error, char *buf, size_t size)
572 #ifdef HAVE_ERR_ERROR_STRING_N
573 /* OpenSSL 0.9.6 and later has a function named
574 ERRO_error_string_n() that takes the size of the buffer as a
575 third argument */
576 ERR_error_string_n(error, buf, size);
577 #else
578 (void) size;
579 ERR_error_string(error, buf);
580 #endif
581 return (buf);
584 #endif /* USE_SSLEAY */
586 #ifdef USE_SSLEAY
588 * Global SSL init
590 * @retval 0 error initializing SSL
591 * @retval 1 SSL initialized successfully
593 int Curl_ossl_init(void)
595 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
596 ENGINE_load_builtin_engines();
597 #endif
599 /* Lets get nice error messages */
600 SSL_load_error_strings();
602 /* Setup all the global SSL stuff */
603 if(!SSLeay_add_ssl_algorithms())
604 return 0;
606 return 1;
609 #endif /* USE_SSLEAY */
611 #ifdef USE_SSLEAY
613 /* Global cleanup */
614 void Curl_ossl_cleanup(void)
616 /* Free the SSL error strings */
617 ERR_free_strings();
619 /* EVP_cleanup() removes all ciphers and digests from the
620 table. */
621 EVP_cleanup();
623 #ifdef HAVE_ENGINE_cleanup
624 ENGINE_cleanup();
625 #endif
627 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
628 /* this function was not present in 0.9.6b, but was added sometimes
629 later */
630 CRYPTO_cleanup_all_ex_data();
631 #endif
635 * This function uses SSL_peek to determine connection status.
637 * Return codes:
638 * 1 means the connection is still in place
639 * 0 means the connection has been closed
640 * -1 means the connection status is unknown
642 int Curl_ossl_check_cxn(struct connectdata *conn)
644 int rc;
645 char buf;
647 rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1);
648 if(rc > 0)
649 return 1; /* connection still in place */
651 if(rc == 0)
652 return 0; /* connection has been closed */
654 return -1; /* connection status unknown */
657 /* Selects an OpenSSL crypto engine
659 CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
661 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
662 ENGINE *e = ENGINE_by_id(engine);
664 if(!e) {
665 failf(data, "SSL Engine '%s' not found", engine);
666 return (CURLE_SSL_ENGINE_NOTFOUND);
669 if(data->state.engine) {
670 ENGINE_finish(data->state.engine);
671 ENGINE_free(data->state.engine);
672 data->state.engine = NULL;
674 if(!ENGINE_init(e)) {
675 char buf[256];
677 ENGINE_free(e);
678 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
679 engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
680 return (CURLE_SSL_ENGINE_INITFAILED);
682 data->state.engine = e;
683 return (CURLE_OK);
684 #else
685 (void)engine;
686 failf(data, "SSL Engine not supported");
687 return (CURLE_SSL_ENGINE_NOTFOUND);
688 #endif
691 /* Sets engine as default for all SSL operations
693 CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
695 #ifdef HAVE_OPENSSL_ENGINE_H
696 if(data->state.engine) {
697 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
698 infof(data,"set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine));
700 else {
701 failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine));
702 return CURLE_SSL_ENGINE_SETFAILED;
705 #else
706 (void) data;
707 #endif
708 return CURLE_OK;
711 /* Return list of OpenSSL crypto engine names.
713 struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
715 struct curl_slist *list = NULL;
716 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
717 struct curl_slist *beg = NULL;
718 ENGINE *e;
720 for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
721 list = curl_slist_append(list, ENGINE_get_id(e));
722 if(list == NULL) {
723 curl_slist_free_all(beg);
724 return NULL;
726 else if(beg == NULL) {
727 beg = list;
730 #endif
731 (void) data;
732 return (list);
737 * This function is called when an SSL connection is closed.
739 void Curl_ossl_close(struct connectdata *conn, int sockindex)
741 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
743 if(connssl->handle) {
744 (void)SSL_shutdown(connssl->handle);
745 SSL_set_connect_state(connssl->handle);
747 SSL_free (connssl->handle);
748 connssl->handle = NULL;
750 if(connssl->ctx) {
751 SSL_CTX_free (connssl->ctx);
752 connssl->ctx = NULL;
757 * This function is called to shut down the SSL layer but keep the
758 * socket open (CCC - Clear Command Channel)
760 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
762 int retval = 0;
763 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
764 struct SessionHandle *data = conn->data;
765 char buf[120]; /* We will use this for the OpenSSL error buffer, so it has
766 to be at least 120 bytes long. */
767 unsigned long sslerror;
768 ssize_t nread;
769 int err;
770 int done = 0;
772 /* This has only been tested on the proftpd server, and the mod_tls code
773 sends a close notify alert without waiting for a close notify alert in
774 response. Thus we wait for a close notify alert from the server, but
775 we do not send one. Let's hope other servers do the same... */
777 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
778 (void)SSL_shutdown(connssl->handle);
780 if(connssl->handle) {
781 while(!done) {
782 int what = Curl_socket_ready(conn->sock[sockindex],
783 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
784 if(what > 0) {
785 /* Something to read, let's do it and hope that it is the close
786 notify alert from the server */
787 nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
788 sizeof(buf));
789 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
791 switch(err) {
792 case SSL_ERROR_NONE: /* this is not an error */
793 case SSL_ERROR_ZERO_RETURN: /* no more data */
794 /* This is the expected response. There was no data but only
795 the close notify alert */
796 done = 1;
797 break;
798 case SSL_ERROR_WANT_READ:
799 /* there's data pending, re-invoke SSL_read() */
800 infof(data, "SSL_ERROR_WANT_READ\n");
801 break;
802 case SSL_ERROR_WANT_WRITE:
803 /* SSL wants a write. Really odd. Let's bail out. */
804 infof(data, "SSL_ERROR_WANT_WRITE\n");
805 done = 1;
806 break;
807 default:
808 /* openssl/ssl.h says "look at error stack/return value/errno" */
809 sslerror = ERR_get_error();
810 failf(conn->data, "SSL read: %s, errno %d",
811 ERR_error_string(sslerror, buf),
812 SOCKERRNO);
813 done = 1;
814 break;
817 else if(0 == what) {
818 /* timeout */
819 failf(data, "SSL shutdown timeout");
820 done = 1;
821 break;
823 else {
824 /* anything that gets here is fatally bad */
825 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
826 retval = -1;
827 done = 1;
829 } /* while()-loop for the select() */
831 if(data->set.verbose) {
832 #ifdef HAVE_SSL_GET_SHUTDOWN
833 switch(SSL_get_shutdown(connssl->handle)) {
834 case SSL_SENT_SHUTDOWN:
835 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
836 break;
837 case SSL_RECEIVED_SHUTDOWN:
838 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
839 break;
840 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
841 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
842 "SSL_RECEIVED__SHUTDOWN\n");
843 break;
845 #endif
848 SSL_free (connssl->handle);
849 connssl->handle = NULL;
851 return retval;
854 void Curl_ossl_session_free(void *ptr)
856 /* free the ID */
857 SSL_SESSION_free(ptr);
861 * This function is called when the 'data' struct is going away. Close
862 * down everything and free all resources!
864 int Curl_ossl_close_all(struct SessionHandle *data)
867 ERR_remove_state() frees the error queue associated with
868 thread pid. If pid == 0, the current thread will have its
869 error queue removed.
871 Since error queue data structures are allocated
872 automatically for new threads, they must be freed when
873 threads are terminated in oder to avoid memory leaks.
875 ERR_remove_state(0);
877 #ifdef HAVE_OPENSSL_ENGINE_H
878 if(data->state.engine) {
879 ENGINE_finish(data->state.engine);
880 ENGINE_free(data->state.engine);
881 data->state.engine = NULL;
883 #else
884 (void)data;
885 #endif
886 return 0;
889 static int asn1_output(struct connectdata *conn,
890 const char *prefix,
891 const ASN1_UTCTIME *tm)
893 const char *asn1_string;
894 int gmt=FALSE;
895 int i;
896 int year=0,month=0,day=0,hour=0,minute=0,second=0;
897 struct SessionHandle *data = conn->data;
899 #ifdef CURL_DISABLE_VERBOSE_STRINGS
900 (void)prefix;
901 #endif
903 if(!data->set.verbose)
904 return 0;
906 i=tm->length;
907 asn1_string=(const char *)tm->data;
909 if(i < 10)
910 return 1;
911 if(asn1_string[i-1] == 'Z')
912 gmt=TRUE;
913 for (i=0; i<10; i++)
914 if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
915 return 2;
917 year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
918 if(year < 50)
919 year+=100;
921 month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
922 if((month > 12) || (month < 1))
923 return 3;
925 day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
926 hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
927 minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
929 if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
930 (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
931 second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
933 infof(data,
934 "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
935 prefix, year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
937 return 0;
940 /* ====================================================== */
943 * Match a hostname against a wildcard pattern.
944 * E.g.
945 * "foo.host.com" matches "*.host.com".
947 * We are a bit more liberal than RFC2818 describes in that we
948 * accept multiple "*" in pattern (similar to what some other browsers do).
949 * E.g.
950 * "abc.def.domain.com" should strickly not match "*.domain.com", but we
951 * don't consider "." to be important in CERT checking.
953 #define HOST_NOMATCH 0
954 #define HOST_MATCH 1
956 static int hostmatch(const char *hostname, const char *pattern)
958 while(1) {
959 char c = *pattern++;
961 if(c == '\0')
962 return (*hostname ? HOST_NOMATCH : HOST_MATCH);
964 if(c == '*') {
965 c = *pattern;
966 if(c == '\0') /* "*\0" matches anything remaining */
967 return HOST_MATCH;
969 while(*hostname) {
970 /* The only recursive function in libcurl! */
971 if(hostmatch(hostname++,pattern) == HOST_MATCH)
972 return HOST_MATCH;
974 break;
977 if(toupper(c) != toupper(*hostname++))
978 break;
980 return HOST_NOMATCH;
983 static int
984 cert_hostcheck(const char *match_pattern, const char *hostname)
986 if(!match_pattern || !*match_pattern ||
987 !hostname || !*hostname) /* sanity check */
988 return 0;
990 if(curl_strequal(hostname,match_pattern)) /* trivial case */
991 return 1;
993 if(hostmatch(hostname,match_pattern) == HOST_MATCH)
994 return 1;
995 return 0;
998 /* Quote from RFC2818 section 3.1 "Server Identity"
1000 If a subjectAltName extension of type dNSName is present, that MUST
1001 be used as the identity. Otherwise, the (most specific) Common Name
1002 field in the Subject field of the certificate MUST be used. Although
1003 the use of the Common Name is existing practice, it is deprecated and
1004 Certification Authorities are encouraged to use the dNSName instead.
1006 Matching is performed using the matching rules specified by
1007 [RFC2459]. If more than one identity of a given type is present in
1008 the certificate (e.g., more than one dNSName name, a match in any one
1009 of the set is considered acceptable.) Names may contain the wildcard
1010 character * which is considered to match any single domain name
1011 component or component fragment. E.g., *.a.com matches foo.a.com but
1012 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1014 In some cases, the URI is specified as an IP address rather than a
1015 hostname. In this case, the iPAddress subjectAltName must be present
1016 in the certificate and must exactly match the IP in the URI.
1019 static CURLcode verifyhost(struct connectdata *conn,
1020 X509 *server_cert)
1022 bool matched = FALSE; /* no alternative match yet */
1023 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1024 int addrlen = 0;
1025 struct SessionHandle *data = conn->data;
1026 STACK_OF(GENERAL_NAME) *altnames;
1027 #ifdef ENABLE_IPV6
1028 struct in6_addr addr;
1029 #else
1030 struct in_addr addr;
1031 #endif
1032 CURLcode res = CURLE_OK;
1034 #ifdef ENABLE_IPV6
1035 if(conn->bits.ipv6_ip &&
1036 Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
1037 target = GEN_IPADD;
1038 addrlen = sizeof(struct in6_addr);
1040 else
1041 #endif
1042 if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
1043 target = GEN_IPADD;
1044 addrlen = sizeof(struct in_addr);
1047 /* get a "list" of alternative names */
1048 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1050 if(altnames) {
1051 int numalts;
1052 int i;
1054 /* get amount of alternatives, RFC2459 claims there MUST be at least
1055 one, but we don't depend on it... */
1056 numalts = sk_GENERAL_NAME_num(altnames);
1058 /* loop through all alternatives while none has matched */
1059 for (i=0; (i<numalts) && !matched; i++) {
1060 /* get a handle to alternative name number i */
1061 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1063 /* only check alternatives of the same type the target is */
1064 if(check->type == target) {
1065 /* get data and length */
1066 const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
1067 int altlen;
1069 switch(target) {
1070 case GEN_DNS: /* name/pattern comparison */
1071 /* The OpenSSL man page explicitly says: "In general it cannot be
1072 assumed that the data returned by ASN1_STRING_data() is null
1073 terminated or does not contain embedded nulls." But also that
1074 "The actual format of the data will depend on the actual string
1075 type itself: for example for and IA5String the data will be ASCII"
1077 Gisle researched the OpenSSL sources:
1078 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1079 it always 0-terminates an IA5String."
1081 if(cert_hostcheck(altptr, conn->host.name))
1082 matched = TRUE;
1083 break;
1085 case GEN_IPADD: /* IP address comparison */
1086 /* compare alternative IP address if the data chunk is the same size
1087 our server IP address is */
1088 altlen = ASN1_STRING_length(check->d.ia5);
1089 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen))
1090 matched = TRUE;
1091 break;
1095 GENERAL_NAMES_free(altnames);
1098 if(matched)
1099 /* an alternative name matched the server hostname */
1100 infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
1101 else {
1102 /* we have to look to the last occurence of a commonName in the
1103 distinguished one to get the most significant one. */
1104 int j,i=-1 ;
1106 /* The following is done because of a bug in 0.9.6b */
1108 unsigned char *nulstr = (unsigned char *)"";
1109 unsigned char *peer_CN = nulstr;
1111 X509_NAME *name = X509_get_subject_name(server_cert) ;
1112 if(name)
1113 while((j=X509_NAME_get_index_by_NID(name,NID_commonName,i))>=0)
1114 i=j;
1116 /* we have the name entry and we will now convert this to a string
1117 that we can use for comparison. Doing this we support BMPstring,
1118 UTF8 etc. */
1120 if(i>=0) {
1121 ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
1123 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1124 is already UTF-8 encoded. We check for this case and copy the raw
1125 string manually to avoid the problem. This code can be made
1126 conditional in the future when OpenSSL has been fixed. Work-around
1127 brought by Alexis S. L. Carvalho. */
1128 if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1129 j = ASN1_STRING_length(tmp);
1130 if(j >= 0) {
1131 peer_CN = OPENSSL_malloc(j+1);
1132 if(peer_CN) {
1133 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
1134 peer_CN[j] = '\0';
1138 else /* not a UTF8 name */
1139 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1142 if(peer_CN == nulstr)
1143 peer_CN = NULL;
1144 #ifdef CURL_DOES_CONVERSIONS
1145 else {
1146 /* convert peer_CN from UTF8 */
1147 size_t rc;
1148 rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
1149 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1150 if(rc != CURLE_OK) {
1151 OPENSSL_free(peer_CN);
1152 return rc;
1155 #endif /* CURL_DOES_CONVERSIONS */
1157 if(!peer_CN) {
1158 failf(data,
1159 "SSL: unable to obtain common name from peer certificate");
1160 return CURLE_PEER_FAILED_VERIFICATION;
1162 else if(!cert_hostcheck((const char *)peer_CN, conn->host.name)) {
1163 if(data->set.ssl.verifyhost > 1) {
1164 failf(data, "SSL: certificate subject name '%s' does not match "
1165 "target host name '%s'", peer_CN, conn->host.dispname);
1166 res = CURLE_PEER_FAILED_VERIFICATION;
1168 else
1169 infof(data, "\t common name: %s (does not match '%s')\n",
1170 peer_CN, conn->host.dispname);
1172 else {
1173 infof(data, "\t common name: %s (matched)\n", peer_CN);
1175 if(peer_CN)
1176 OPENSSL_free(peer_CN);
1178 return res;
1180 #endif /* USE_SSLEAY */
1182 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1183 and thus this cannot be done there. */
1184 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1186 static const char *ssl_msg_type(int ssl_ver, int msg)
1188 if(ssl_ver == SSL2_VERSION_MAJOR) {
1189 switch (msg) {
1190 case SSL2_MT_ERROR:
1191 return "Error";
1192 case SSL2_MT_CLIENT_HELLO:
1193 return "Client hello";
1194 case SSL2_MT_CLIENT_MASTER_KEY:
1195 return "Client key";
1196 case SSL2_MT_CLIENT_FINISHED:
1197 return "Client finished";
1198 case SSL2_MT_SERVER_HELLO:
1199 return "Server hello";
1200 case SSL2_MT_SERVER_VERIFY:
1201 return "Server verify";
1202 case SSL2_MT_SERVER_FINISHED:
1203 return "Server finished";
1204 case SSL2_MT_REQUEST_CERTIFICATE:
1205 return "Request CERT";
1206 case SSL2_MT_CLIENT_CERTIFICATE:
1207 return "Client CERT";
1210 else if(ssl_ver == SSL3_VERSION_MAJOR) {
1211 switch (msg) {
1212 case SSL3_MT_HELLO_REQUEST:
1213 return "Hello request";
1214 case SSL3_MT_CLIENT_HELLO:
1215 return "Client hello";
1216 case SSL3_MT_SERVER_HELLO:
1217 return "Server hello";
1218 case SSL3_MT_CERTIFICATE:
1219 return "CERT";
1220 case SSL3_MT_SERVER_KEY_EXCHANGE:
1221 return "Server key exchange";
1222 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1223 return "Client key exchange";
1224 case SSL3_MT_CERTIFICATE_REQUEST:
1225 return "Request CERT";
1226 case SSL3_MT_SERVER_DONE:
1227 return "Server finished";
1228 case SSL3_MT_CERTIFICATE_VERIFY:
1229 return "CERT verify";
1230 case SSL3_MT_FINISHED:
1231 return "Finished";
1234 return "Unknown";
1237 static const char *tls_rt_type(int type)
1239 return (
1240 type == SSL3_RT_CHANGE_CIPHER_SPEC ? "TLS change cipher, " :
1241 type == SSL3_RT_ALERT ? "TLS alert, " :
1242 type == SSL3_RT_HANDSHAKE ? "TLS handshake, " :
1243 type == SSL3_RT_APPLICATION_DATA ? "TLS app data, " :
1244 "TLS Unknown, ");
1249 * Our callback from the SSL/TLS layers.
1251 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1252 const void *buf, size_t len, const SSL *ssl,
1253 struct connectdata *conn)
1255 struct SessionHandle *data;
1256 const char *msg_name, *tls_rt_name;
1257 char ssl_buf[1024];
1258 int ver, msg_type, txt_len;
1260 if(!conn || !conn->data || !conn->data->set.fdebug ||
1261 (direction != 0 && direction != 1))
1262 return;
1264 data = conn->data;
1265 ssl_ver >>= 8;
1266 ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
1267 ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
1269 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1270 * always pass-up content-type as 0. But the interesting message-type
1271 * is at 'buf[0]'.
1273 if(ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
1274 tls_rt_name = tls_rt_type(content_type);
1275 else
1276 tls_rt_name = "";
1278 msg_type = *(char*)buf;
1279 msg_name = ssl_msg_type(ssl_ver, msg_type);
1281 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n",
1282 ver, tls_rt_name, msg_name, msg_type);
1283 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1285 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1286 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1287 (void) ssl;
1289 #endif
1291 #ifdef USE_SSLEAY
1292 /* ====================================================== */
1294 static CURLcode
1295 ossl_connect_step1(struct connectdata *conn,
1296 int sockindex)
1298 CURLcode retcode = CURLE_OK;
1300 struct SessionHandle *data = conn->data;
1301 SSL_METHOD_QUAL SSL_METHOD *req_method=NULL;
1302 void *ssl_sessionid=NULL;
1303 X509_LOOKUP *lookup=NULL;
1304 curl_socket_t sockfd = conn->sock[sockindex];
1305 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1306 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1307 #ifdef ENABLE_IPV6
1308 struct in6_addr addr;
1309 #else
1310 struct in_addr addr;
1311 #endif
1312 #endif
1314 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
1316 /* Make funny stuff to get random input */
1317 Curl_ossl_seed(data);
1319 /* check to see if we've been told to use an explicit SSL/TLS version */
1320 switch(data->set.ssl.version) {
1321 default:
1322 case CURL_SSLVERSION_DEFAULT:
1323 /* we try to figure out version */
1324 req_method = SSLv23_client_method();
1325 break;
1326 case CURL_SSLVERSION_TLSv1:
1327 req_method = TLSv1_client_method();
1328 break;
1329 case CURL_SSLVERSION_SSLv2:
1330 req_method = SSLv2_client_method();
1331 break;
1332 case CURL_SSLVERSION_SSLv3:
1333 req_method = SSLv3_client_method();
1334 break;
1337 if(connssl->ctx)
1338 SSL_CTX_free(connssl->ctx);
1339 connssl->ctx = SSL_CTX_new(req_method);
1341 if(!connssl->ctx) {
1342 failf(data, "SSL: couldn't create a context!");
1343 return CURLE_OUT_OF_MEMORY;
1346 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1347 if(data->set.fdebug && data->set.verbose) {
1348 /* the SSL trace callback is only used for verbose logging so we only
1349 inform about failures of setting it */
1350 if(!SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK,
1351 (void (*)(void))ssl_tls_trace)) {
1352 infof(data, "SSL: couldn't set callback!\n");
1354 else if(!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0,
1355 conn)) {
1356 infof(data, "SSL: couldn't set callback argument!\n");
1359 #endif
1361 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1362 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1363 work-arounds. The man page for this option states that SSL_OP_ALL enables
1364 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1365 enable the bug workaround options if compatibility with somewhat broken
1366 implementations is desired."
1369 SSL_CTX_set_options(connssl->ctx, SSL_OP_ALL);
1371 /* disable SSLv2 in the default case (i.e. allow SSLv3 and TLSv1) */
1372 if(data->set.ssl.version == CURL_SSLVERSION_DEFAULT)
1373 SSL_CTX_set_options(connssl->ctx, SSL_OP_NO_SSLv2);
1375 #if 0
1377 * Not sure it's needed to tell SSL_connect() that socket is
1378 * non-blocking. It doesn't seem to care, but just return with
1379 * SSL_ERROR_WANT_x.
1381 if(data->state.used_interface == Curl_if_multi)
1382 SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL);
1383 #endif
1385 if(data->set.str[STRING_CERT]) {
1386 if(!cert_stuff(conn,
1387 connssl->ctx,
1388 data->set.str[STRING_CERT],
1389 data->set.str[STRING_CERT_TYPE],
1390 data->set.str[STRING_KEY],
1391 data->set.str[STRING_KEY_TYPE])) {
1392 /* failf() is already done in cert_stuff() */
1393 return CURLE_SSL_CERTPROBLEM;
1397 if(data->set.str[STRING_SSL_CIPHER_LIST]) {
1398 if(!SSL_CTX_set_cipher_list(connssl->ctx,
1399 data->set.str[STRING_SSL_CIPHER_LIST])) {
1400 failf(data, "failed setting cipher list");
1401 return CURLE_SSL_CIPHER;
1405 if(data->set.str[STRING_SSL_CAFILE] || data->set.str[STRING_SSL_CAPATH]) {
1406 /* tell SSL where to find CA certificates that are used to verify
1407 the servers certificate. */
1408 if(!SSL_CTX_load_verify_locations(connssl->ctx,
1409 data->set.str[STRING_SSL_CAFILE],
1410 data->set.str[STRING_SSL_CAPATH])) {
1411 if(data->set.ssl.verifypeer) {
1412 /* Fail if we insist on successfully verifying the server. */
1413 failf(data,"error setting certificate verify locations:\n"
1414 " CAfile: %s\n CApath: %s\n",
1415 data->set.str[STRING_SSL_CAFILE]?
1416 data->set.str[STRING_SSL_CAFILE]: "none",
1417 data->set.str[STRING_SSL_CAPATH]?
1418 data->set.str[STRING_SSL_CAPATH] : "none");
1419 return CURLE_SSL_CACERT_BADFILE;
1421 else {
1422 /* Just continue with a warning if no strict certificate verification
1423 is required. */
1424 infof(data, "error setting certificate verify locations,"
1425 " continuing anyway:\n");
1428 else {
1429 /* Everything is fine. */
1430 infof(data, "successfully set certificate verify locations:\n");
1432 infof(data,
1433 " CAfile: %s\n"
1434 " CApath: %s\n",
1435 data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]:
1436 "none",
1437 data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]:
1438 "none");
1441 if (data->set.str[STRING_SSL_CRLFILE]) {
1442 /* tell SSL where to find CRL file that is used to check certificate
1443 * revocation */
1444 lookup=X509_STORE_add_lookup(connssl->ctx->cert_store,X509_LOOKUP_file());
1445 if ( !lookup ||
1446 (X509_load_crl_file(lookup,data->set.str[STRING_SSL_CRLFILE],
1447 X509_FILETYPE_PEM)!=1) ) {
1448 failf(data,"error loading CRL file :\n"
1449 " CRLfile: %s\n",
1450 data->set.str[STRING_SSL_CRLFILE]?
1451 data->set.str[STRING_SSL_CRLFILE]: "none");
1452 return CURLE_SSL_CRL_BADFILE;
1454 else {
1455 /* Everything is fine. */
1456 infof(data, "successfully load CRL file:\n");
1457 X509_STORE_set_flags(connssl->ctx->cert_store,
1458 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1460 infof(data,
1461 " CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ?
1462 data->set.str[STRING_SSL_CRLFILE]: "none");
1465 /* SSL always tries to verify the peer, this only says whether it should
1466 * fail to connect if the verification fails, or if it should continue
1467 * anyway. In the latter case the result of the verification is checked with
1468 * SSL_get_verify_result() below. */
1469 SSL_CTX_set_verify(connssl->ctx,
1470 data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
1471 cert_verify_callback);
1473 /* give application a chance to interfere with SSL set up. */
1474 if(data->set.ssl.fsslctx) {
1475 retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx,
1476 data->set.ssl.fsslctxp);
1477 if(retcode) {
1478 failf(data,"error signaled by ssl ctx callback");
1479 return retcode;
1483 /* Lets make an SSL structure */
1484 if(connssl->handle)
1485 SSL_free(connssl->handle);
1486 connssl->handle = SSL_new(connssl->ctx);
1487 if(!connssl->handle) {
1488 failf(data, "SSL: couldn't create a context (handle)!");
1489 return CURLE_OUT_OF_MEMORY;
1491 SSL_set_connect_state(connssl->handle);
1493 connssl->server_cert = 0x0;
1495 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1496 if ((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
1497 #ifdef ENABLE_IPV6
1498 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
1499 #endif
1500 !SSL_set_tlsext_host_name(connssl->handle, conn->host.name))
1501 infof(data, "WARNING: failed to configure server name indication (SNI) "
1502 "TLS extension\n");
1503 #endif
1505 /* Check if there's a cached ID we can/should use here! */
1506 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
1507 /* we got a session id, use it! */
1508 if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
1509 failf(data, "SSL: SSL_set_session failed: %s",
1510 ERR_error_string(ERR_get_error(),NULL));
1511 return CURLE_SSL_CONNECT_ERROR;
1513 /* Informational message */
1514 infof (data, "SSL re-using session ID\n");
1517 /* pass the raw socket into the SSL layers */
1518 if(!SSL_set_fd(connssl->handle, sockfd)) {
1519 failf(data, "SSL: SSL_set_fd failed: %s",
1520 ERR_error_string(ERR_get_error(),NULL));
1521 return CURLE_SSL_CONNECT_ERROR;
1524 connssl->connecting_state = ssl_connect_2;
1525 return CURLE_OK;
1528 static CURLcode
1529 ossl_connect_step2(struct connectdata *conn, int sockindex)
1531 struct SessionHandle *data = conn->data;
1532 int err;
1533 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1535 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
1536 || ssl_connect_2_reading == connssl->connecting_state
1537 || ssl_connect_2_writing == connssl->connecting_state);
1539 err = SSL_connect(connssl->handle);
1541 /* 1 is fine
1542 0 is "not successful but was shut down controlled"
1543 <0 is "handshake was not successful, because a fatal error occurred" */
1544 if(1 != err) {
1545 int detail = SSL_get_error(connssl->handle, err);
1547 if(SSL_ERROR_WANT_READ == detail) {
1548 connssl->connecting_state = ssl_connect_2_reading;
1549 return CURLE_OK;
1551 else if(SSL_ERROR_WANT_WRITE == detail) {
1552 connssl->connecting_state = ssl_connect_2_writing;
1553 return CURLE_OK;
1555 else {
1556 /* untreated error */
1557 unsigned long errdetail;
1558 char error_buffer[256]; /* OpenSSL documents that this must be at least
1559 256 bytes long. */
1560 CURLcode rc;
1561 const char *cert_problem = NULL;
1563 connssl->connecting_state = ssl_connect_2; /* the connection failed,
1564 we're not waiting for
1565 anything else. */
1567 errdetail = ERR_get_error(); /* Gets the earliest error code from the
1568 thread's error queue and removes the
1569 entry. */
1571 switch(errdetail) {
1572 case 0x1407E086:
1573 /* 1407E086:
1574 SSL routines:
1575 SSL2_SET_CERTIFICATE:
1576 certificate verify failed */
1577 /* fall-through */
1578 case 0x14090086:
1579 /* 14090086:
1580 SSL routines:
1581 SSL3_GET_SERVER_CERTIFICATE:
1582 certificate verify failed */
1583 cert_problem = "SSL certificate problem, verify that the CA cert is"
1584 " OK. Details:\n";
1585 rc = CURLE_SSL_CACERT;
1586 break;
1587 default:
1588 rc = CURLE_SSL_CONNECT_ERROR;
1589 break;
1592 /* detail is already set to the SSL error above */
1594 /* If we e.g. use SSLv2 request-method and the server doesn't like us
1595 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
1596 * the SO_ERROR is also lost.
1598 if(CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) {
1599 failf(data, "Unknown SSL protocol error in connection to %s:%d ",
1600 conn->host.name, conn->port);
1601 return rc;
1603 /* Could be a CERT problem */
1605 SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
1606 failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
1607 return rc;
1610 else {
1611 /* we have been connected fine, we're not waiting for anything else. */
1612 connssl->connecting_state = ssl_connect_3;
1614 /* Informational message */
1615 infof (data, "SSL connection using %s\n",
1616 SSL_get_cipher(connssl->handle));
1618 return CURLE_OK;
1623 * Get the server cert, verify it and show it etc, only call failf() if the
1624 * 'strict' argument is TRUE as otherwise all this is for informational
1625 * purposes only!
1627 * We check certificates to authenticate the server; otherwise we risk
1628 * man-in-the-middle attack.
1630 static CURLcode servercert(struct connectdata *conn,
1631 struct ssl_connect_data *connssl,
1632 bool strict)
1634 CURLcode retcode = CURLE_OK;
1635 char *str;
1636 long lerr;
1637 ASN1_TIME *certdate;
1638 struct SessionHandle *data = conn->data;
1639 X509 *issuer;
1640 FILE *fp;
1642 data->set.ssl.certverifyresult = !X509_V_OK;
1644 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
1645 if(!connssl->server_cert) {
1646 if(strict)
1647 failf(data, "SSL: couldn't get peer certificate!");
1648 return CURLE_PEER_FAILED_VERIFICATION;
1650 infof (data, "Server certificate:\n");
1652 str = X509_NAME_oneline(X509_get_subject_name(connssl->server_cert),
1653 NULL, 0);
1654 if(!str) {
1655 if(strict)
1656 failf(data, "SSL: couldn't get X509-subject!");
1657 X509_free(connssl->server_cert);
1658 connssl->server_cert = NULL;
1659 return CURLE_SSL_CONNECT_ERROR;
1661 infof(data, "\t subject: %s\n", str);
1662 CRYPTO_free(str);
1664 certdate = X509_get_notBefore(connssl->server_cert);
1665 asn1_output(conn, "\t start date: ", certdate);
1667 certdate = X509_get_notAfter(connssl->server_cert);
1668 asn1_output(conn, "\t expire date: ", certdate);
1670 if(data->set.ssl.verifyhost) {
1671 retcode = verifyhost(conn, connssl->server_cert);
1672 if(retcode) {
1673 X509_free(connssl->server_cert);
1674 connssl->server_cert = NULL;
1675 return retcode;
1679 str = X509_NAME_oneline(X509_get_issuer_name(connssl->server_cert),
1680 NULL, 0);
1681 if(!str) {
1682 if(strict)
1683 failf(data, "SSL: couldn't get X509-issuer name!");
1684 retcode = CURLE_SSL_CONNECT_ERROR;
1686 else {
1687 infof(data, "\t issuer: %s\n", str);
1688 CRYPTO_free(str);
1690 /* We could do all sorts of certificate verification stuff here before
1691 deallocating the certificate. */
1693 /* e.g. match issuer name with provided issuer certificate */
1694 if (data->set.str[STRING_SSL_ISSUERCERT]) {
1695 if (! (fp=fopen(data->set.str[STRING_SSL_ISSUERCERT],"r"))) {
1696 if (strict)
1697 failf(data, "SSL: Unable to open issuer cert (%s)\n",
1698 data->set.str[STRING_SSL_ISSUERCERT]);
1699 X509_free(connssl->server_cert);
1700 connssl->server_cert = NULL;
1701 return CURLE_SSL_ISSUER_ERROR;
1703 issuer = PEM_read_X509(fp,NULL,ZERO_NULL,NULL);
1704 if (!issuer) {
1705 if (strict)
1706 failf(data, "SSL: Unable to read issuer cert (%s)\n",
1707 data->set.str[STRING_SSL_ISSUERCERT]);
1708 X509_free(connssl->server_cert);
1709 X509_free(issuer);
1710 fclose(fp);
1711 return CURLE_SSL_ISSUER_ERROR;
1713 fclose(fp);
1714 if (X509_check_issued(issuer,connssl->server_cert) != X509_V_OK) {
1715 if (strict)
1716 failf(data, "SSL: Certificate issuer check failed (%s)\n",
1717 data->set.str[STRING_SSL_ISSUERCERT]);
1718 X509_free(connssl->server_cert);
1719 X509_free(issuer);
1720 connssl->server_cert = NULL;
1721 return CURLE_SSL_ISSUER_ERROR;
1723 infof(data, "\t SSL certificate issuer check ok (%s)\n",
1724 data->set.str[STRING_SSL_ISSUERCERT]);
1725 X509_free(issuer);
1728 lerr = data->set.ssl.certverifyresult=
1729 SSL_get_verify_result(connssl->handle);
1730 if(data->set.ssl.certverifyresult != X509_V_OK) {
1731 if(data->set.ssl.verifypeer) {
1732 /* We probably never reach this, because SSL_connect() will fail
1733 and we return earlier if verifypeer is set? */
1734 if(strict)
1735 failf(data, "SSL certificate verify result: %s (%ld)",
1736 X509_verify_cert_error_string(lerr), lerr);
1737 retcode = CURLE_PEER_FAILED_VERIFICATION;
1739 else
1740 infof(data, "\t SSL certificate verify result: %s (%ld),"
1741 " continuing anyway.\n",
1742 X509_verify_cert_error_string(lerr), lerr);
1744 else
1745 infof(data, "\t SSL certificate verify ok.\n");
1748 X509_free(connssl->server_cert);
1749 connssl->server_cert = NULL;
1750 connssl->connecting_state = ssl_connect_done;
1752 return retcode;
1756 static CURLcode
1757 ossl_connect_step3(struct connectdata *conn,
1758 int sockindex)
1760 CURLcode retcode = CURLE_OK;
1761 void *ssl_sessionid=NULL;
1762 struct SessionHandle *data = conn->data;
1763 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1765 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
1767 if(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
1768 /* Since this is not a cached session ID, then we want to stach this one
1769 in the cache! */
1770 SSL_SESSION *our_ssl_sessionid;
1771 #ifdef HAVE_SSL_GET1_SESSION
1772 our_ssl_sessionid = SSL_get1_session(connssl->handle);
1774 /* SSL_get1_session() will increment the reference
1775 count and the session will stay in memory until explicitly freed with
1776 SSL_SESSION_free(3), regardless of its state.
1777 This function was introduced in openssl 0.9.5a. */
1778 #else
1779 our_ssl_sessionid = SSL_get_session(connssl->handle);
1781 /* if SSL_get1_session() is unavailable, use SSL_get_session().
1782 This is an inferior option because the session can be flushed
1783 at any time by openssl. It is included only so curl compiles
1784 under versions of openssl < 0.9.5a.
1786 WARNING: How curl behaves if it's session is flushed is
1787 untested.
1789 #endif
1790 retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
1791 0 /* unknown size */);
1792 if(retcode) {
1793 failf(data, "failed to store ssl session");
1794 return retcode;
1800 * We check certificates to authenticate the server; otherwise we risk
1801 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
1802 * verify the peer ignore faults and failures from the server cert
1803 * operations.
1806 if(!data->set.ssl.verifypeer)
1807 (void)servercert(conn, connssl, FALSE);
1808 else
1809 retcode = servercert(conn, connssl, TRUE);
1811 if(CURLE_OK == retcode)
1812 connssl->connecting_state = ssl_connect_done;
1813 return retcode;
1816 static CURLcode
1817 ossl_connect_common(struct connectdata *conn,
1818 int sockindex,
1819 bool nonblocking,
1820 bool *done)
1822 CURLcode retcode;
1823 struct SessionHandle *data = conn->data;
1824 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1825 curl_socket_t sockfd = conn->sock[sockindex];
1826 long timeout_ms;
1828 if(ssl_connect_1==connssl->connecting_state) {
1829 /* Find out how much more time we're allowed */
1830 timeout_ms = Curl_timeleft(conn, NULL, TRUE);
1832 if(timeout_ms < 0) {
1833 /* no need to continue if time already is up */
1834 failf(data, "SSL connection timeout");
1835 return CURLE_OPERATION_TIMEDOUT;
1837 retcode = ossl_connect_step1(conn, sockindex);
1838 if(retcode)
1839 return retcode;
1842 timeout_ms = 0;
1843 while(ssl_connect_2 == connssl->connecting_state ||
1844 ssl_connect_2_reading == connssl->connecting_state ||
1845 ssl_connect_2_writing == connssl->connecting_state) {
1847 /* check allowed time left */
1848 timeout_ms = Curl_timeleft(conn, NULL, TRUE);
1850 if(timeout_ms < 0) {
1851 /* no need to continue if time already is up */
1852 failf(data, "SSL connection timeout");
1853 return CURLE_OPERATION_TIMEDOUT;
1856 /* if ssl is expecting something, check if it's available. */
1857 if(connssl->connecting_state == ssl_connect_2_reading
1858 || connssl->connecting_state == ssl_connect_2_writing) {
1860 int writefd = ssl_connect_2_writing==
1861 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
1862 int readfd = ssl_connect_2_reading==
1863 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
1865 while(1) {
1866 int what = Curl_socket_ready(readfd, writefd,
1867 nonblocking?0:(int)timeout_ms);
1868 if(what > 0)
1869 /* readable or writable, go loop in the outer loop */
1870 break;
1871 else if(0 == what) {
1872 if(nonblocking) {
1873 *done = FALSE;
1874 return CURLE_OK;
1876 else {
1877 /* timeout */
1878 failf(data, "SSL connection timeout");
1879 return CURLE_OPERATION_TIMEDOUT;
1882 else {
1883 /* anything that gets here is fatally bad */
1884 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1885 return CURLE_SSL_CONNECT_ERROR;
1887 } /* while()-loop for the select() */
1890 /* get the timeout from step2 to avoid computing it twice. */
1891 retcode = ossl_connect_step2(conn, sockindex);
1892 if(retcode)
1893 return retcode;
1895 } /* repeat step2 until all transactions are done. */
1898 if(ssl_connect_3==connssl->connecting_state) {
1899 retcode = ossl_connect_step3(conn, sockindex);
1900 if(retcode)
1901 return retcode;
1904 if(ssl_connect_done==connssl->connecting_state) {
1905 connssl->state = ssl_connection_complete;
1906 *done = TRUE;
1908 else
1909 *done = FALSE;
1911 /* Reset our connect state machine */
1912 connssl->connecting_state = ssl_connect_1;
1914 return CURLE_OK;
1917 CURLcode
1918 Curl_ossl_connect_nonblocking(struct connectdata *conn,
1919 int sockindex,
1920 bool *done)
1922 return ossl_connect_common(conn, sockindex, TRUE, done);
1925 CURLcode
1926 Curl_ossl_connect(struct connectdata *conn,
1927 int sockindex)
1929 CURLcode retcode;
1930 bool done = FALSE;
1932 retcode = ossl_connect_common(conn, sockindex, FALSE, &done);
1933 if(retcode)
1934 return retcode;
1936 DEBUGASSERT(done);
1938 return CURLE_OK;
1941 bool Curl_ossl_data_pending(const struct connectdata *conn,
1942 int connindex)
1944 if(conn->ssl[connindex].handle)
1945 /* SSL is in use */
1946 return (bool)(0 != SSL_pending(conn->ssl[connindex].handle));
1947 else
1948 return FALSE;
1951 /* return number of sent (non-SSL) bytes */
1952 ssize_t Curl_ossl_send(struct connectdata *conn,
1953 int sockindex,
1954 const void *mem,
1955 size_t len)
1957 /* SSL_write() is said to return 'int' while write() and send() returns
1958 'size_t' */
1959 int err;
1960 char error_buffer[120]; /* OpenSSL documents that this must be at least 120
1961 bytes long. */
1962 unsigned long sslerror;
1963 int rc = SSL_write(conn->ssl[sockindex].handle, mem, (int)len);
1965 if(rc < 0) {
1966 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
1968 switch(err) {
1969 case SSL_ERROR_WANT_READ:
1970 case SSL_ERROR_WANT_WRITE:
1971 /* The operation did not complete; the same TLS/SSL I/O function
1972 should be called again later. This is basicly an EWOULDBLOCK
1973 equivalent. */
1974 return 0;
1975 case SSL_ERROR_SYSCALL:
1976 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
1977 SOCKERRNO);
1978 return -1;
1979 case SSL_ERROR_SSL:
1980 /* A failure in the SSL library occurred, usually a protocol error.
1981 The OpenSSL error queue contains more information on the error. */
1982 sslerror = ERR_get_error();
1983 failf(conn->data, "SSL_write() error: %s",
1984 ERR_error_string(sslerror, error_buffer));
1985 return -1;
1987 /* a true error */
1988 failf(conn->data, "SSL_write() return error %d", err);
1989 return -1;
1991 return (ssize_t)rc; /* number of bytes */
1995 * If the read would block we return -1 and set 'wouldblock' to TRUE.
1996 * Otherwise we return the amount of data read. Other errors should return -1
1997 * and set 'wouldblock' to FALSE.
1999 ssize_t Curl_ossl_recv(struct connectdata *conn, /* connection data */
2000 int num, /* socketindex */
2001 char *buf, /* store read data here */
2002 size_t buffersize, /* max amount to read */
2003 bool *wouldblock)
2005 char error_buffer[120]; /* OpenSSL documents that this must be at
2006 least 120 bytes long. */
2007 unsigned long sslerror;
2008 ssize_t nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf,
2009 (int)buffersize);
2010 *wouldblock = FALSE;
2011 if(nread < 0) {
2012 /* failed SSL_read */
2013 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
2015 switch(err) {
2016 case SSL_ERROR_NONE: /* this is not an error */
2017 case SSL_ERROR_ZERO_RETURN: /* no more data */
2018 break;
2019 case SSL_ERROR_WANT_READ:
2020 case SSL_ERROR_WANT_WRITE:
2021 /* there's data pending, re-invoke SSL_read() */
2022 *wouldblock = TRUE;
2023 return -1; /* basically EWOULDBLOCK */
2024 default:
2025 /* openssl/ssl.h says "look at error stack/return value/errno" */
2026 sslerror = ERR_get_error();
2027 failf(conn->data, "SSL read: %s, errno %d",
2028 ERR_error_string(sslerror, error_buffer),
2029 SOCKERRNO);
2030 return -1;
2033 return nread;
2036 size_t Curl_ossl_version(char *buffer, size_t size)
2038 #ifdef YASSL_VERSION
2039 /* yassl provides an OpenSSL API compatiblity layer so it looks identical
2040 to OpenSSL in all other aspects */
2041 return snprintf(buffer, size, "yassl/%s", YASSL_VERSION);
2042 #else /* YASSL_VERSION */
2044 #if(SSLEAY_VERSION_NUMBER >= 0x905000)
2046 char sub[2];
2047 unsigned long ssleay_value;
2048 sub[1]='\0';
2049 ssleay_value=SSLeay();
2050 if(ssleay_value < 0x906000) {
2051 ssleay_value=SSLEAY_VERSION_NUMBER;
2052 sub[0]='\0';
2054 else {
2055 if(ssleay_value&0xff0) {
2056 sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
2058 else
2059 sub[0]='\0';
2062 return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx%s",
2063 (ssleay_value>>28)&0xf,
2064 (ssleay_value>>20)&0xff,
2065 (ssleay_value>>12)&0xff,
2066 sub);
2069 #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2071 #if(SSLEAY_VERSION_NUMBER >= 0x900000)
2072 return snprintf(buffer, size, "OpenSSL/%lx.%lx.%lx",
2073 (SSLEAY_VERSION_NUMBER>>28)&0xff,
2074 (SSLEAY_VERSION_NUMBER>>20)&0xff,
2075 (SSLEAY_VERSION_NUMBER>>12)&0xf);
2077 #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2079 char sub[2];
2080 sub[1]='\0';
2081 if(SSLEAY_VERSION_NUMBER&0x0f) {
2082 sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
2084 else
2085 sub[0]='\0';
2087 return snprintf(buffer, size, "SSL/%x.%x.%x%s",
2088 (SSLEAY_VERSION_NUMBER>>12)&0xff,
2089 (SSLEAY_VERSION_NUMBER>>8)&0xf,
2090 (SSLEAY_VERSION_NUMBER>>4)&0xf, sub);
2092 #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2093 #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2095 #endif /* YASSL_VERSION */
2097 #endif /* USE_SSLEAY */