1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, 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 ***************************************************************************/
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.
29 * The original SSLeay-using code for curl was written by Linas Vepstas and
30 * Sampo Kellomaki 1998.
41 #ifdef HAVE_SYS_SOCKET_H
42 #include <sys/socket.h>
47 #include "formdata.h" /* for the boundary function */
48 #include "url.h" /* for the ssl config check function */
49 #include "inet_pton.h"
57 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
58 #include <curl/mprintf.h>
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>
73 #include "curl_memory.h"
74 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
76 /* The last #include file should be: */
79 #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
80 #define HAVE_SSL_GET1_SESSION 1
82 #undef HAVE_SSL_GET1_SESSION
85 #if OPENSSL_VERSION_NUMBER >= 0x00904100L
86 #define HAVE_USERDATA_IN_PWD_CALLBACK 1
88 #undef HAVE_USERDATA_IN_PWD_CALLBACK
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>
96 /* ENGINE_load_private_key() takes three arguments */
97 #undef HAVE_ENGINE_LOAD_FOUR_ARGS
100 #if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
101 /* OpenSSL has PKCS 12 support */
102 #define HAVE_PKCS12_SUPPORT
104 /* OpenSSL/SSLEay does not have PKCS12 support */
105 #undef HAVE_PKCS12_SUPPORT
108 #if OPENSSL_VERSION_NUMBER >= 0x00906001L
109 #define HAVE_ERR_ERROR_STRING_N 1
112 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
113 #define SSL_METHOD_QUAL const
115 #define SSL_METHOD_QUAL
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
122 #define X509_STORE_set_flags(x,y)
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.
131 #define RAND_LOAD_LENGTH 1024
133 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
134 static char global_passwd[64];
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()
142 , void *global_passwd
147 fprintf(stderr, "%s\n", buf);
149 if(num > (int)strlen((char *)global_passwd)) {
150 strcpy(buf, global_passwd);
151 return (int)strlen(buf);
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.
164 #ifdef HAVE_RAND_STATUS
165 #define seed_enough(x) rand_enough()
166 static bool rand_enough(void)
168 return (bool)(0 != RAND_status());
171 #define seed_enough(x) rand_enough(x)
172 static bool rand_enough(int nread)
174 /* this is a very silly decision to make */
175 return (bool)(nread > 500);
179 static int ossl_seed(struct SessionHandle *data)
181 char *buf = data->state.buffer; /* point to the big buffer */
184 /* Q: should we add support for a random file name as a libcurl option?
185 A: Yes, it is here */
188 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
190 if(data->set.ssl.random_file)
191 #define RANDOM_FILE "" /* doesn't matter won't be used */
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]:
199 if(seed_enough(nread))
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 */
207 /* If we don't have the define set, we only do this if the egd-option
209 if(data->set.str[STRING_SSL_EGDSOCKET])
210 #define EGD_SOCKET "" /* doesn't matter won't be used */
213 /* If there's an option and a define, the option overrides the
215 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
216 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
219 if(seed_enough(nread))
225 /* If we get here, it means we need to seed the PRNG using a "silly"
227 #ifdef HAVE_RAND_SCREEN
228 /* if RAND_screen() is present, it was called during global init */
229 nread = 100; /* just a value */
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.
242 area = Curl_FormBoundary();
244 return 3; /* out of memory */
246 len = (int)strlen(area);
247 RAND_add(area, len, (len >> 1));
249 free(area); /* now remove the random junk */
250 } while(!RAND_status());
254 /* generates a default path for the random seed file */
255 buf[0]=0; /* blank it first */
256 RAND_file_name(buf, BUFSIZE);
258 /* we got a file name to try */
259 nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
260 if(seed_enough(nread))
264 infof(data, "libcurl is now using a weak random seed!\n");
268 int Curl_ossl_seed(struct SessionHandle *data)
270 /* we have the "SSL is seeded" boolean static to prevent multiple
271 time-consuming seedings in vain */
272 static bool ssl_seeded = FALSE;
274 if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
275 data->set.str[STRING_SSL_EGDSOCKET]) {
283 #ifndef SSL_FILETYPE_ENGINE
284 #define SSL_FILETYPE_ENGINE 42
286 #ifndef SSL_FILETYPE_PKCS12
287 #define SSL_FILETYPE_PKCS12 43
289 static int do_file_type(const char *type)
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;
305 int cert_stuff(struct connectdata *conn,
308 const char *cert_type,
310 const char *key_type)
312 struct SessionHandle *data = conn->data;
314 int file_type = do_file_type(cert_type);
316 if(cert_file != NULL || file_type == SSL_FILETYPE_ENGINE) {
321 if(data->set.str[STRING_KEY_PASSWD]) {
322 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
324 * If password has been given, we store that in the global
325 * area (*shudder*) for a while:
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);
332 * We set the password in the callback userdata
334 SSL_CTX_set_default_passwd_cb_userdata(ctx,
335 data->set.str[STRING_KEY_PASSWD]);
337 /* Set passwd callback: */
338 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
342 #define SSL_CLIENT_CERT_ERR \
343 "unable to use client certificate (no key found or wrong pass phrase?)"
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,
350 failf(data, SSL_CLIENT_CERT_ERR);
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
359 if(SSL_CTX_use_certificate_file(ctx,
362 failf(data, SSL_CLIENT_CERT_ERR);
366 case SSL_FILETYPE_ENGINE:
367 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
369 if(data->state.engine) {
370 const char *cmd_name = "LOAD_CERT_CTRL";
376 params.cert_id = cert_file;
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");
386 /* Load the certificate from the engine */
387 if (!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
388 0, ¶ms, 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));
396 failf(data, "ssl engine didn't initialized the certificate "
401 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
402 failf(data, "unable to set client certificate");
403 X509_free(params.cert);
406 X509_free(params.cert); /* we don't need the handle any more... */
409 failf(data, "crypto engine not set, can't load certificate");
415 failf(data, "file type ENG for certificate not implemented");
419 case SSL_FILETYPE_PKCS12:
421 #ifdef HAVE_PKCS12_SUPPORT
425 STACK_OF(X509) *ca = NULL;
428 f = fopen(cert_file,"rb");
430 failf(data, "could not open PKCS12 file '%s'", cert_file);
433 p12 = d2i_PKCS12_fp(f, NULL);
437 failf(data, "error reading PKCS12 file '%s'", cert_file );
443 if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509,
446 "could not parse PKCS12 file, check password, OpenSSL error %s",
447 ERR_error_string(ERR_get_error(), NULL) );
454 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
455 failf(data, SSL_CLIENT_CERT_ERR);
461 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
462 failf(data, "unable to use private key from PKCS12 file '%s'",
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);
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");
485 if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i))) {
486 failf(data, "cannot add certificate to client CA list");
499 failf(data, "file type P12 for certificate not supported");
504 failf(data, "not supported file type '%s' for certificate", cert_type);
508 file_type = do_file_type(key_type);
511 case SSL_FILETYPE_PEM:
515 /* cert & key can only be in PEM case in the same 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");
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();
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
538 data->set.str[STRING_KEY_PASSWD]);
540 failf(data, "failed to load private key from crypto engine");
543 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
544 failf(data, "unable to set private key");
545 EVP_PKEY_free(priv_key);
548 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
551 failf(data, "crypto engine not set, can't load private key");
557 failf(data, "file type ENG for private key not supported");
560 case SSL_FILETYPE_PKCS12:
562 failf(data, "file type P12 for private key not supported");
567 failf(data, "not supported file type for private key");
573 failf(data,"unable to create an SSL structure");
577 x509=SSL_get_certificate(ssl);
579 /* This version was provided by Evan Jordan and is supposed to not
580 leak memory as the previous version: */
582 EVP_PKEY *pktmp = X509_get_pubkey(x509);
583 EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
584 EVP_PKEY_free(pktmp);
589 /* If we are using DSA, we can copy the parameters from
593 /* Now we know that a key and cert have been set against
595 if(!SSL_CTX_check_private_key(ctx)) {
596 failf(data, "Private key does not match the certificate public key");
599 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
601 memset(global_passwd, 0, sizeof(global_passwd));
607 /* returns non-zero on failure */
608 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
611 return X509_NAME_oneline(a, buf, size);
613 BIO *bio_out = BIO_new(BIO_s_mem());
618 return 1; /* alloc failed! */
620 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
621 BIO_get_mem_ptr(bio_out, &biomem);
623 if((size_t)biomem->length < size)
624 size = biomem->length;
626 size--; /* don't overwrite the buffer end */
628 memcpy(buf, biomem->data, size);
638 int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
643 err_cert=X509_STORE_CTX_get_current_cert(ctx);
644 (void)x509_name_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
648 /* Return error string for last OpenSSL error
650 static char *SSL_strerror(unsigned long error, char *buf, size_t size)
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
656 ERR_error_string_n(error, buf, size);
659 ERR_error_string(error, buf);
664 #endif /* USE_SSLEAY */
670 * @retval 0 error initializing SSL
671 * @retval 1 SSL initialized successfully
673 int Curl_ossl_init(void)
675 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
676 ENGINE_load_builtin_engines();
679 /* Lets get nice error messages */
680 SSL_load_error_strings();
682 /* Init the global ciphers and digests */
683 if(!SSLeay_add_ssl_algorithms())
686 OpenSSL_add_all_algorithms();
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. */
698 #endif /* USE_SSLEAY */
703 void Curl_ossl_cleanup(void)
705 /* Free the SSL error strings */
708 /* EVP_cleanup() removes all ciphers and digests from the table. */
711 #ifdef HAVE_ENGINE_CLEANUP
715 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
716 /* this function was not present in 0.9.6b, but was added sometimes
718 CRYPTO_cleanup_all_ex_data();
723 * This function uses SSL_peek to determine connection status.
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
730 int Curl_ossl_check_cxn(struct connectdata *conn)
735 rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1);
737 return 1; /* connection still in place */
740 return 0; /* connection has been closed */
742 return -1; /* connection status unknown */
745 /* Selects an OpenSSL crypto engine
747 CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
749 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
752 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
753 e = ENGINE_by_id(engine);
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))
764 failf(data, "SSL Engine '%s' not found", engine);
765 return CURLE_SSL_ENGINE_NOTFOUND;
768 if(data->state.engine) {
769 ENGINE_finish(data->state.engine);
770 ENGINE_free(data->state.engine);
771 data->state.engine = NULL;
773 if(!ENGINE_init(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;
781 data->state.engine = e;
785 failf(data, "SSL Engine not supported");
786 return CURLE_SSL_ENGINE_NOTFOUND;
790 /* Sets engine as default for all SSL operations
792 CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
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));
800 failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine));
801 return CURLE_SSL_ENGINE_SETFAILED;
810 /* Return list of OpenSSL crypto engine names.
812 struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
814 struct curl_slist *list = NULL;
815 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
816 struct curl_slist *beg = NULL;
819 for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
820 list = curl_slist_append(list, ENGINE_get_id(e));
822 curl_slist_free_all(beg);
825 else if(beg == NULL) {
836 * This function is called when an SSL connection is closed.
838 void Curl_ossl_close(struct connectdata *conn, int sockindex)
840 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
842 if(connssl->handle) {
843 (void)SSL_shutdown(connssl->handle);
844 SSL_set_connect_state(connssl->handle);
846 SSL_free (connssl->handle);
847 connssl->handle = NULL;
850 SSL_CTX_free (connssl->ctx);
856 * This function is called to shut down the SSL layer but keep the
857 * socket open (CCC - Clear Command Channel)
859 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
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;
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... */
877 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
878 (void)SSL_shutdown(connssl->handle);
880 if(connssl->handle) {
881 buffsize = (int)sizeof(buf);
883 int what = Curl_socket_ready(conn->sock[sockindex],
884 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
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,
892 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
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 */
901 case SSL_ERROR_WANT_READ:
902 /* there's data pending, re-invoke SSL_read() */
903 infof(data, "SSL_ERROR_WANT_READ\n");
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");
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),
922 failf(data, "SSL shutdown timeout");
926 /* anything that gets here is fatally bad */
927 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
931 } /* while()-loop for the select() */
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");
939 case SSL_RECEIVED_SHUTDOWN:
940 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
942 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
943 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
944 "SSL_RECEIVED__SHUTDOWN\n");
950 SSL_free (connssl->handle);
951 connssl->handle = NULL;
956 void Curl_ossl_session_free(void *ptr)
959 SSL_SESSION_free(ptr);
963 * This function is called when the 'data' struct is going away. Close
964 * down everything and free all resources!
966 int Curl_ossl_close_all(struct SessionHandle *data)
969 ERR_remove_state() frees the error queue associated with
970 thread pid. If pid == 0, the current thread will have its
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.
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;
991 static int asn1_output(const ASN1_UTCTIME *tm,
995 const char *asn1_string;
998 int year=0,month=0,day=0,hour=0,minute=0,second=0;
1001 asn1_string=(const char *)tm->data;
1005 if(asn1_string[i-1] == 'Z')
1007 for (i=0; i<10; i++)
1008 if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
1011 year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
1015 month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
1016 if((month > 12) || (month < 1))
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');
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');
1027 snprintf(buf, sizeofbuf,
1028 "%04d-%02d-%02d %02d:%02d:%02d %s",
1029 year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
1034 /* ====================================================== */
1037 * Match a hostname against a wildcard pattern.
1039 * "foo.host.com" matches "*.host.com".
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).
1044 * "abc.def.domain.com" should strickly not match "*.domain.com", but we
1045 * don't consider "." to be important in CERT checking.
1047 #define HOST_NOMATCH 0
1048 #define HOST_MATCH 1
1050 static int hostmatch(const char *hostname, const char *pattern)
1053 char c = *pattern++;
1056 return (*hostname ? HOST_NOMATCH : HOST_MATCH);
1060 if(c == '\0') /* "*\0" matches anything remaining */
1064 /* The only recursive function in libcurl! */
1065 if(hostmatch(hostname++,pattern) == HOST_MATCH)
1071 if(Curl_raw_toupper(c) != Curl_raw_toupper(*hostname++))
1074 return HOST_NOMATCH;
1078 cert_hostcheck(const char *match_pattern, const char *hostname)
1080 if(!match_pattern || !*match_pattern ||
1081 !hostname || !*hostname) /* sanity check */
1084 if(Curl_raw_equal(hostname, match_pattern)) /* trivial case */
1087 if(hostmatch(hostname,match_pattern) == HOST_MATCH)
1092 /* Quote from RFC2818 section 3.1 "Server Identity"
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.
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.
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.
1113 static CURLcode verifyhost(struct connectdata *conn,
1116 int matched = -1; /* -1 is no alternative match yet, 1 means match and 0
1118 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1120 struct SessionHandle *data = conn->data;
1121 STACK_OF(GENERAL_NAME) *altnames;
1123 struct in6_addr addr;
1125 struct in_addr addr;
1127 CURLcode res = CURLE_OK;
1130 if(conn->bits.ipv6_ip &&
1131 Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
1133 addrlen = sizeof(struct in6_addr);
1137 if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
1139 addrlen = sizeof(struct in_addr);
1142 /* get a "list" of alternative names */
1143 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
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);
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);
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);
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"
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."
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))
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))
1196 GENERAL_NAMES_free(altnames);
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
1205 infof(data, "\t subjectAltName does not match %s\n", conn->host.dispname);
1206 res = CURLE_PEER_FAILED_VERIFICATION;
1209 /* we have to look to the last occurence of a commonName in the
1210 distinguished one to get the most significant one. */
1213 /* The following is done because of a bug in 0.9.6b */
1215 unsigned char *nulstr = (unsigned char *)"";
1216 unsigned char *peer_CN = nulstr;
1218 X509_NAME *name = X509_get_subject_name(server_cert) ;
1220 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
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,
1228 ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
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. */
1236 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1237 j = ASN1_STRING_length(tmp);
1239 peer_CN = OPENSSL_malloc(j+1);
1241 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
1246 else /* not a UTF8 name */
1247 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
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;
1258 if(peer_CN == nulstr)
1260 #ifdef CURL_DOES_CONVERSIONS
1262 /* convert peer_CN from UTF8 */
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);
1271 #endif /* CURL_DOES_CONVERSIONS */
1274 /* error already detected, pass through */
1278 "SSL: unable to obtain common name from peer certificate");
1279 res = CURLE_PEER_FAILED_VERIFICATION;
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;
1288 infof(data, "\t common name: %s (does not match '%s')\n",
1289 peer_CN, conn->host.dispname);
1292 infof(data, "\t common name: %s (matched)\n", peer_CN);
1295 OPENSSL_free(peer_CN);
1299 #endif /* USE_SSLEAY */
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
1305 static const char *ssl_msg_type(int ssl_ver, int msg)
1307 if(ssl_ver == SSL2_VERSION_MAJOR) {
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";
1329 else if(ssl_ver == SSL3_VERSION_MAJOR) {
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:
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:
1356 static const char *tls_rt_type(int type)
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, " :
1368 * Our callback from the SSL/TLS layers.
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)
1374 struct SessionHandle *data;
1375 const char *msg_name, *tls_rt_name;
1377 int ver, msg_type, txt_len;
1379 if(!conn || !conn->data || !conn->data->set.fdebug ||
1380 (direction != 0 && direction != 1))
1385 ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
1386 ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
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
1392 if(ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
1393 tls_rt_name = tls_rt_type(content_type);
1397 msg_type = *(char*)buf;
1398 msg_name = ssl_msg_type(ssl_ver, msg_type);
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);
1404 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1405 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1411 /* ====================================================== */
1413 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1414 # define use_sni(x) sni = (x)
1416 # define use_sni(x) do { } while (0)
1420 ossl_connect_step1(struct connectdata *conn,
1423 CURLcode retcode = CURLE_OK;
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
1434 struct in6_addr addr;
1436 struct in_addr addr;
1440 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
1442 /* Make funny stuff to get random input */
1443 Curl_ossl_seed(data);
1445 /* check to see if we've been told to use an explicit SSL/TLS version */
1446 switch(data->set.ssl.version) {
1448 case CURL_SSLVERSION_DEFAULT:
1449 /* we try to figure out version */
1450 req_method = SSLv23_client_method();
1453 case CURL_SSLVERSION_TLSv1:
1454 req_method = TLSv1_client_method();
1457 case CURL_SSLVERSION_SSLv2:
1458 req_method = SSLv2_client_method();
1461 case CURL_SSLVERSION_SSLv3:
1462 req_method = SSLv3_client_method();
1468 SSL_CTX_free(connssl->ctx);
1469 connssl->ctx = SSL_CTX_new(req_method);
1472 failf(data, "SSL: couldn't create a context!");
1473 return CURLE_OUT_OF_MEMORY;
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");
1484 else if(!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0,
1486 infof(data, "SSL: couldn't set callback argument!\n");
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."
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
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).
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.
1511 #ifdef SSL_OP_NO_TICKET
1512 /* expect older openssl releases to not have this define so only use it if
1514 #define CURL_CTX_OPTIONS SSL_OP_ALL|SSL_OP_NO_TICKET
1516 #define CURL_CTX_OPTIONS SSL_OP_ALL
1519 SSL_CTX_set_options(connssl->ctx, CURL_CTX_OPTIONS);
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);
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
1531 if(data->state.used_interface == Curl_if_multi)
1532 SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL);
1535 if(data->set.str[STRING_CERT] || data->set.str[STRING_CERT_TYPE]) {
1536 if(!cert_stuff(conn,
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;
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;
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;
1572 /* Just continue with a warning if no strict certificate verification
1574 infof(data, "error setting certificate verify locations,"
1575 " continuing anyway:\n");
1579 /* Everything is fine. */
1580 infof(data, "successfully set certificate verify locations:\n");
1585 data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]:
1587 data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]:
1591 if (data->set.str[STRING_SSL_CRLFILE]) {
1592 /* tell SSL where to find CRL file that is used to check certificate
1594 lookup=X509_STORE_add_lookup(connssl->ctx->cert_store,X509_LOOKUP_file());
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;
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);
1609 " CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ?
1610 data->set.str[STRING_SSL_CRLFILE]: "none");
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);
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);
1626 failf(data,"error signaled by ssl ctx callback");
1631 /* Lets make an SSL structure */
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;
1639 SSL_set_connect_state(connssl->handle);
1641 connssl->server_cert = 0x0;
1643 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1644 if ((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
1646 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
1649 !SSL_set_tlsext_host_name(connssl->handle, conn->host.name))
1650 infof(data, "WARNING: failed to configure server name indication (SNI) "
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;
1662 /* Informational message */
1663 infof (data, "SSL re-using session ID\n");
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;
1673 connssl->connecting_state = ssl_connect_2;
1678 ossl_connect_step2(struct connectdata *conn, int sockindex)
1680 struct SessionHandle *data = conn->data;
1682 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1684 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
1685 || ssl_connect_2_reading == connssl->connecting_state
1686 || ssl_connect_2_writing == connssl->connecting_state);
1690 err = SSL_connect(connssl->handle);
1693 0 is "not successful but was shut down controlled"
1694 <0 is "handshake was not successful, because a fatal error occurred" */
1696 int detail = SSL_get_error(connssl->handle, err);
1698 if(SSL_ERROR_WANT_READ == detail) {
1699 connssl->connecting_state = ssl_connect_2_reading;
1702 else if(SSL_ERROR_WANT_WRITE == detail) {
1703 connssl->connecting_state = ssl_connect_2_writing;
1707 /* untreated error */
1708 unsigned long errdetail;
1709 char error_buffer[256]; /* OpenSSL documents that this must be at least
1712 const char *cert_problem = NULL;
1714 connssl->connecting_state = ssl_connect_2; /* the connection failed,
1715 we're not waiting for
1718 errdetail = ERR_get_error(); /* Gets the earliest error code from the
1719 thread's error queue and removes the
1726 SSL2_SET_CERTIFICATE:
1727 certificate verify failed */
1732 SSL3_GET_SERVER_CERTIFICATE:
1733 certificate verify failed */
1734 cert_problem = "SSL certificate problem, verify that the CA cert is"
1736 rc = CURLE_SSL_CACERT;
1739 rc = CURLE_SSL_CONNECT_ERROR;
1743 /* detail is already set to the SSL error above */
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.
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);
1754 /* Could be a CERT problem */
1756 SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
1757 failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
1762 /* we have been connected fine, we're not waiting for anything else. */
1763 connssl->connecting_state = ssl_connect_3;
1765 /* Informational message */
1766 infof (data, "SSL connection using %s\n",
1767 SSL_get_cipher(connssl->handle));
1773 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
1777 if((ilen = (int)len) < 0)
1778 return 1; /* buffer too big */
1780 i = i2t_ASN1_OBJECT(buf, ilen, a);
1783 return 1; /* buffer too small */
1788 static CURLcode push_certinfo_len(struct SessionHandle *data,
1794 struct curl_certinfo *ci = &data->info.certs;
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 */
1801 output = malloc(outlen);
1803 return CURLE_OUT_OF_MEMORY;
1805 /* sprintf the label and colon */
1806 snprintf(output, outlen, "%s:", label);
1808 /* memcpy the value (it might not be zero terminated) */
1809 memcpy(&output[labellen+1], value, valuelen);
1811 /* zero terminate the output */
1812 output[labellen + 1 + valuelen] = 0;
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);
1819 curl_slist_free_all(ci->certinfo[certnum]);
1820 res = CURLE_OUT_OF_MEMORY;
1823 ci->certinfo[certnum] = nl;
1830 /* this is a convenience function for push_certinfo_len that takes a zero
1832 static CURLcode push_certinfo(struct SessionHandle *data,
1837 size_t valuelen = strlen(value);
1839 return push_certinfo_len(data, certnum, label, value, valuelen);
1842 static void pubkey_show(struct SessionHandle *data,
1850 size_t left = sizeof(buffer);
1855 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
1857 for(i=0; i< len; i++) {
1858 snprintf(ptr, left, "%02x:", raw[i]);
1862 infof(data, " %s: %s\n", namebuf, buffer);
1863 push_certinfo(data, num, namebuf, buffer);
1866 #define print_pubkey_BN(_type, _name, _num) \
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); \
1873 pubkey_show(data, _num, #_type, #_name, (unsigned char*)buf, len); \
1878 static int X509V3_ext(struct SessionHandle *data,
1880 STACK_OF(X509_EXTENSION) *exts)
1885 if(sk_X509_EXTENSION_num(exts) <= 0)
1886 /* no extensions, bail out */
1889 for (i=0; i<sk_X509_EXTENSION_num(exts); i++) {
1891 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1896 BIO *bio_out = BIO_new(BIO_s_mem());
1901 obj = X509_EXTENSION_get_object(ext);
1903 asn1_object_dump(obj, namebuf, sizeof(namebuf));
1905 infof(data, "%s: %s\n", namebuf,
1906 X509_EXTENSION_get_critical(ext)?"(critical)":"");
1908 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
1909 M_ASN1_OCTET_STRING_print(bio_out, ext->value);
1911 BIO_get_mem_ptr(bio_out, &biomem);
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
1916 for(j=0; j<(size_t)biomem->length; j++) {
1918 if(biomem->data[j] == '\n') {
1920 j++; /* skip the newline */
1922 while((biomem->data[j] == ' ') && (j<(size_t)biomem->length))
1924 if(j<(size_t)biomem->length)
1925 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep, biomem->data[j]);
1927 infof(data, " %s\n", buf);
1929 push_certinfo(data, certnum, namebuf, buf);
1934 return 0; /* all is fine */
1938 static void X509_signature(struct SessionHandle *data,
1945 for (i=0; i<sig->length; i++)
1946 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%02x:", sig->data[i]);
1948 infof(data, " Signature: %s\n", buf);
1949 push_certinfo(data, numcert, "Signature", buf);
1952 static void dumpcert(struct SessionHandle *data, X509 *x, int numcert)
1954 BIO *bio_out = BIO_new(BIO_s_mem());
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);
1961 BIO_get_mem_ptr(bio_out, &biomem);
1963 infof(data, "%s\n", biomem->data);
1965 push_certinfo_len(data, numcert, "Cert", biomem->data, biomem->length);
1972 static int init_certinfo(struct SessionHandle *data,
1975 struct curl_certinfo *ci = &data->info.certs;
1976 struct curl_slist **table;
1978 Curl_ssl_free_certinfo(data);
1980 ci->num_of_certs = num;
1981 table = calloc((size_t)num, sizeof(struct curl_slist *));
1985 ci->certinfo = table;
1989 static CURLcode get_cert_chain(struct connectdata *conn,
1990 struct ssl_connect_data *connssl)
1996 struct SessionHandle *data = conn->data;
1999 sk = SSL_get_peer_cert_chain(connssl->handle);
2002 return CURLE_OUT_OF_MEMORY;
2004 numcerts = sk_X509_num(sk);
2006 if(init_certinfo(data, numcerts))
2007 return CURLE_OUT_OF_MEMORY;
2009 infof(data, "--- Certificate chain\n");
2010 for (i=0; i<numcerts; i++) {
2013 ASN1_TIME *certdate;
2015 /* get the certs in "importance order" */
2017 X509 *x = sk_X509_value(sk, numcerts - i - 1);
2019 X509 *x = sk_X509_value(sk, i);
2023 EVP_PKEY *pubkey=NULL;
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);
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);
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 */
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);
2050 if(num->type == V_ASN1_NEG_INTEGER)
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':':'));
2060 infof(data," Serial Number: %s\n", buf);
2065 push_certinfo(data, i, "Serial Number", buf); /* hex */
2067 cinf = x->cert_info;
2069 j = asn1_object_dump(cinf->signature->algorithm, buf, sizeof(buf));
2071 infof(data, " Signature Algorithm: %s\n", buf);
2072 push_certinfo(data, i, "Signature Algorithm", buf);
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);
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);
2085 j = asn1_object_dump(cinf->key->algor->algorithm, buf, sizeof(buf));
2087 infof(data, " Public Key Algorithm: %s\n", buf);
2088 push_certinfo(data, i, "Public Key Algorithm", buf);
2091 pubkey = X509_get_pubkey(x);
2093 infof(data, " Unable to load public key\n");
2095 switch(pubkey->type) {
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);
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);
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);
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);
2125 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2130 EVP_PKEY_free(pubkey);
2133 X509V3_ext(data, i, cinf->extensions);
2135 X509_signature(data, i, x->signature);
2137 dumpcert(data, x, i);
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
2148 * We check certificates to authenticate the server; otherwise we risk
2149 * man-in-the-middle attack.
2151 static CURLcode servercert(struct connectdata *conn,
2152 struct ssl_connect_data *connssl,
2155 CURLcode retcode = CURLE_OK;
2158 ASN1_TIME *certdate;
2159 struct SessionHandle *data = conn->data;
2164 if(data->set.ssl.certinfo)
2165 /* we've been asked to gather certificate info! */
2166 (void)get_cert_chain(conn, connssl);
2168 data->set.ssl.certverifyresult = !X509_V_OK;
2170 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
2171 if(!connssl->server_cert) {
2173 failf(data, "SSL: couldn't get peer certificate!");
2174 return CURLE_PEER_FAILED_VERIFICATION;
2176 infof (data, "Server certificate:\n");
2178 rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
2179 buffer, sizeof(buffer));
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;
2187 infof(data, "\t subject: %s\n", buffer);
2189 certdate = X509_get_notBefore(connssl->server_cert);
2190 asn1_output(certdate, buffer, sizeof(buffer));
2191 infof(data, "\t start date: %s\n", buffer);
2193 certdate = X509_get_notAfter(connssl->server_cert);
2194 asn1_output(certdate, buffer, sizeof(buffer));
2195 infof(data, "\t expire date: %s\n", buffer);
2197 if(data->set.ssl.verifyhost) {
2198 retcode = verifyhost(conn, connssl->server_cert);
2200 X509_free(connssl->server_cert);
2201 connssl->server_cert = NULL;
2206 rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
2207 buffer, sizeof(buffer));
2210 failf(data, "SSL: couldn't get X509-issuer name!");
2211 retcode = CURLE_SSL_CONNECT_ERROR;
2214 infof(data, "\t issuer: %s\n", buffer);
2216 /* We could do all sorts of certificate verification stuff here before
2217 deallocating the certificate. */
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"))) {
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;
2229 issuer = PEM_read_X509(fp,NULL,ZERO_NULL,NULL);
2232 failf(data, "SSL: Unable to read issuer cert (%s)\n",
2233 data->set.str[STRING_SSL_ISSUERCERT]);
2234 X509_free(connssl->server_cert);
2237 return CURLE_SSL_ISSUER_ERROR;
2240 if (X509_check_issued(issuer,connssl->server_cert) != X509_V_OK) {
2242 failf(data, "SSL: Certificate issuer check failed (%s)\n",
2243 data->set.str[STRING_SSL_ISSUERCERT]);
2244 X509_free(connssl->server_cert);
2246 connssl->server_cert = NULL;
2247 return CURLE_SSL_ISSUER_ERROR;
2249 infof(data, "\t SSL certificate issuer check ok (%s)\n",
2250 data->set.str[STRING_SSL_ISSUERCERT]);
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? */
2261 failf(data, "SSL certificate verify result: %s (%ld)",
2262 X509_verify_cert_error_string(lerr), lerr);
2263 retcode = CURLE_PEER_FAILED_VERIFICATION;
2266 infof(data, "\t SSL certificate verify result: %s (%ld),"
2267 " continuing anyway.\n",
2268 X509_verify_cert_error_string(lerr), lerr);
2271 infof(data, "\t SSL certificate verify ok.\n");
2274 X509_free(connssl->server_cert);
2275 connssl->server_cert = NULL;
2276 connssl->connecting_state = ssl_connect_done;
2283 ossl_connect_step3(struct connectdata *conn,
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];
2291 SSL_SESSION *our_ssl_sessionid;
2293 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
2295 #ifdef HAVE_SSL_GET1_SESSION
2296 our_ssl_sessionid = SSL_get1_session(connssl->handle);
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. */
2303 our_ssl_sessionid = SSL_get_session(connssl->handle);
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.
2310 WARNING: How curl behaves if it's session is flushed is
2315 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL));
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);
2324 retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
2325 0 /* unknown size */);
2327 failf(data, "failed to store ssl session");
2331 #ifdef HAVE_SSL_GET1_SESSION
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
2337 SSL_SESSION_free(our_ssl_sessionid);
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
2348 if(!data->set.ssl.verifypeer)
2349 (void)servercert(conn, connssl, FALSE);
2351 retcode = servercert(conn, connssl, TRUE);
2353 if(CURLE_OK == retcode)
2354 connssl->connecting_state = ssl_connect_done;
2358 static Curl_recv ossl_recv;
2359 static Curl_send ossl_send;
2362 ossl_connect_common(struct connectdata *conn,
2368 struct SessionHandle *data = conn->data;
2369 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2370 curl_socket_t sockfd = conn->sock[sockindex];
2374 /* check if the connection has already been established */
2375 if(ssl_connection_complete == connssl->state) {
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);
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;
2389 retcode = ossl_connect_step1(conn, sockindex);
2394 while(ssl_connect_2 == connssl->connecting_state ||
2395 ssl_connect_2_reading == connssl->connecting_state ||
2396 ssl_connect_2_writing == connssl->connecting_state) {
2398 /* check allowed time left */
2399 timeout_ms = Curl_timeleft(conn, NULL, TRUE);
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;
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) {
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;
2416 what = Curl_socket_ready(readfd, writefd,
2417 nonblocking?0:(int)timeout_ms);
2420 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
2421 return CURLE_SSL_CONNECT_ERROR;
2423 else if(0 == what) {
2430 failf(data, "SSL connection timeout");
2431 return CURLE_OPERATION_TIMEDOUT;
2434 /* socket is readable or writable */
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.
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)))
2450 } /* repeat step2 until all transactions are done. */
2453 if(ssl_connect_3==connssl->connecting_state) {
2454 retcode = ossl_connect_step3(conn, sockindex);
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;
2468 /* Reset our connect state machine */
2469 connssl->connecting_state = ssl_connect_1;
2475 Curl_ossl_connect_nonblocking(struct connectdata *conn,
2479 return ossl_connect_common(conn, sockindex, TRUE, done);
2483 Curl_ossl_connect(struct connectdata *conn,
2489 retcode = ossl_connect_common(conn, sockindex, FALSE, &done);
2498 bool Curl_ossl_data_pending(const struct connectdata *conn,
2501 if(conn->ssl[connindex].handle)
2503 return (bool)(0 != SSL_pending(conn->ssl[connindex].handle));
2508 static ssize_t ossl_send(struct connectdata *conn,
2514 /* SSL_write() is said to return 'int' while write() and send() returns
2517 char error_buffer[120]; /* OpenSSL documents that this must be at least 120
2519 unsigned long sslerror;
2525 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
2526 rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
2529 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
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
2537 *curlcode = CURLE_AGAIN;
2539 case SSL_ERROR_SYSCALL:
2540 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
2542 *curlcode = CURLE_SEND_ERROR;
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;
2554 failf(conn->data, "SSL_write() return error %d", err);
2555 *curlcode = CURLE_SEND_ERROR;
2558 return (ssize_t)rc; /* number of bytes */
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 */
2567 char error_buffer[120]; /* OpenSSL documents that this must be at
2568 least 120 bytes long. */
2569 unsigned long sslerror;
2575 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
2576 nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
2578 /* failed SSL_read */
2579 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
2582 case SSL_ERROR_NONE: /* this is not an error */
2583 case SSL_ERROR_ZERO_RETURN: /* no more data */
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;
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),
2596 *curlcode = CURLE_RECV_ERROR;
2603 size_t Curl_ossl_version(char *buffer, size_t size)
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 */
2611 #if(SSLEAY_VERSION_NUMBER >= 0x905000)
2614 unsigned long ssleay_value;
2616 ssleay_value=SSLeay();
2617 if(ssleay_value < 0x906000) {
2618 ssleay_value=SSLEAY_VERSION_NUMBER;
2622 if(ssleay_value&0xff0) {
2623 sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
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,
2636 #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
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);
2644 #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2648 if(SSLEAY_VERSION_NUMBER&0x0f) {
2649 sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
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);
2659 #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2660 #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2662 #endif /* YASSL_VERSION */
2664 #endif /* USE_SSLEAY */