1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2007, 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.
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.
39 #ifdef HAVE_SYS_TYPES_H
40 #include <sys/types.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
48 #include "formdata.h" /* for the boundary function */
49 #include "url.h" /* for the ssl config check function */
50 #include "inet_pton.h"
52 #include "connect.h" /* Curl_sockerrno() proto */
57 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
58 #include <curl/mprintf.h>
63 #include <openssl/rand.h>
64 #include <openssl/x509v3.h>
71 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
73 /* The last #include file should be: */
77 #define min(a, b) ((a) < (b) ? (a) : (b))
80 #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
81 #define HAVE_SSL_GET1_SESSION 1
83 #undef HAVE_SSL_GET1_SESSION
86 #if OPENSSL_VERSION_NUMBER >= 0x00904100L
87 #define HAVE_USERDATA_IN_PWD_CALLBACK 1
89 #undef HAVE_USERDATA_IN_PWD_CALLBACK
92 #if OPENSSL_VERSION_NUMBER >= 0x00907001L
93 /* ENGINE_load_private_key() takes four arguments */
94 #define HAVE_ENGINE_LOAD_FOUR_ARGS
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
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];
130 static int passwd_callback(char *buf, int num, int verify
131 #if 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
140 fprintf(stderr, "%s\n", buf);
142 if(num > (int)strlen((char *)global_passwd)) {
143 strcpy(buf, global_passwd);
144 return (int)strlen(buf);
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());
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);
172 static int ossl_seed(struct SessionHandle *data)
174 char *buf = data->state.buffer; /* point to the big buffer */
177 /* Q: should we add support for a random file name as a libcurl option?
178 A: Yes, it is here */
181 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
183 if(data->set.ssl.random_file)
184 #define RANDOM_FILE "" /* doesn't matter won't be used */
187 /* let the option override the define */
188 nread += RAND_load_file((data->set.ssl.random_file?
189 data->set.ssl.random_file:RANDOM_FILE),
191 if(seed_enough(nread))
195 #if defined(HAVE_RAND_EGD)
196 /* only available in OpenSSL 0.9.5 and later */
197 /* EGD_SOCKET is set at configure time or not at all */
199 /* If we don't have the define set, we only do this if the egd-option
201 if(data->set.ssl.egdsocket)
202 #define EGD_SOCKET "" /* doesn't matter won't be used */
205 /* If there's an option and a define, the option overrides the
207 int ret = RAND_egd(data->set.ssl.egdsocket?
208 data->set.ssl.egdsocket:EGD_SOCKET);
211 if(seed_enough(nread))
217 /* If we get here, it means we need to seed the PRNG using a "silly"
219 #ifdef HAVE_RAND_SCREEN
220 /* This one gets a random value by reading the currently shown screen */
222 nread = 100; /* just a value */
228 /* Changed call to RAND_seed to use the underlying RAND_add implementation
229 * directly. Do this in a loop, with the amount of additional entropy
230 * being dependent upon the algorithm used by Curl_FormBoundary(): N bytes
231 * of a 7-bit ascii set. -- Richard Gorton, March 11 2003.
235 area = Curl_FormBoundary();
237 return 3; /* out of memory */
239 len = (int)strlen(area);
240 RAND_add(area, len, (len >> 1));
242 free(area); /* now remove the random junk */
243 } while (!RAND_status());
247 /* generates a default path for the random seed file */
248 buf[0]=0; /* blank it first */
249 RAND_file_name(buf, BUFSIZE);
251 /* we got a file name to try */
252 nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
253 if(seed_enough(nread))
257 infof(data, "libcurl is now using a weak random seed!\n");
261 int Curl_ossl_seed(struct SessionHandle *data)
263 /* we have the "SSL is seeded" boolean static to prevent multiple
264 time-consuming seedings in vain */
265 static bool ssl_seeded = FALSE;
267 if(!ssl_seeded || data->set.ssl.random_file || data->set.ssl.egdsocket) {
275 #ifndef SSL_FILETYPE_ENGINE
276 #define SSL_FILETYPE_ENGINE 42
278 #ifndef SSL_FILETYPE_PKCS12
279 #define SSL_FILETYPE_PKCS12 43
281 static int do_file_type(const char *type)
283 if(!type || !type[0])
284 return SSL_FILETYPE_PEM;
285 if(curl_strequal(type, "PEM"))
286 return SSL_FILETYPE_PEM;
287 if(curl_strequal(type, "DER"))
288 return SSL_FILETYPE_ASN1;
289 if(curl_strequal(type, "ENG"))
290 return SSL_FILETYPE_ENGINE;
291 if(curl_strequal(type, "P12"))
292 return SSL_FILETYPE_PKCS12;
297 int cert_stuff(struct connectdata *conn,
300 const char *cert_type,
302 const char *key_type)
304 struct SessionHandle *data = conn->data;
307 if(cert_file != NULL) {
312 if(data->set.key_passwd) {
313 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
315 * If password has been given, we store that in the global
316 * area (*shudder*) for a while:
318 size_t len = strlen(data->set.key_passwd);
319 if(len < sizeof(global_passwd))
320 memcpy(global_passwd, data->set.key_passwd, len+1);
323 * We set the password in the callback userdata
325 SSL_CTX_set_default_passwd_cb_userdata(ctx,
326 data->set.key_passwd);
328 /* Set passwd callback: */
329 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
332 file_type = do_file_type(cert_type);
334 #define SSL_CLIENT_CERT_ERR \
335 "unable to use client certificate (no key found or wrong pass phrase?)"
338 case SSL_FILETYPE_PEM:
339 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
340 if(SSL_CTX_use_certificate_chain_file(ctx,
342 failf(data, SSL_CLIENT_CERT_ERR);
347 case SSL_FILETYPE_ASN1:
348 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
349 we use the case above for PEM so this can only be performed with
351 if(SSL_CTX_use_certificate_file(ctx,
354 failf(data, SSL_CLIENT_CERT_ERR);
358 case SSL_FILETYPE_ENGINE:
359 failf(data, "file type ENG for certificate not implemented");
362 case SSL_FILETYPE_PKCS12:
364 #ifdef HAVE_PKCS12_SUPPORT
369 f = fopen(cert_file,"rb");
371 failf(data, "could not open PKCS12 file '%s'", cert_file);
374 p12 = d2i_PKCS12_fp(f, NULL);
379 if (!PKCS12_parse(p12, data->set.key_passwd, &pri, &x509, NULL)) {
381 "could not parse PKCS12 file, check password, OpenSSL error %s",
382 ERR_error_string(ERR_get_error(), NULL) );
388 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
389 failf(data, SSL_CLIENT_CERT_ERR);
395 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
396 failf(data, "unable to use private key from PKCS12 file '%s'",
408 failf(data, "file type P12 for certificate not supported");
413 failf(data, "not supported file type '%s' for certificate", cert_type);
417 file_type = do_file_type(key_type);
420 case SSL_FILETYPE_PEM:
424 /* cert & key can only be in PEM case in the same file */
426 case SSL_FILETYPE_ASN1:
427 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
428 failf(data, "unable to set private key file: '%s' type %s\n",
429 key_file, key_type?key_type:"PEM");
433 case SSL_FILETYPE_ENGINE:
434 #ifdef HAVE_OPENSSL_ENGINE_H
435 { /* XXXX still needs some work */
436 EVP_PKEY *priv_key = NULL;
437 if(conn && conn->data && conn->data->state.engine) {
438 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
439 UI_METHOD *ui_method = UI_OpenSSL();
441 if(!key_file || !key_file[0]) {
442 failf(data, "no key set to load from crypto engine\n");
445 /* the typecast below was added to please MinGW32 */
446 priv_key = (EVP_PKEY *)
447 ENGINE_load_private_key(conn->data->state.engine,key_file,
448 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
451 data->set.key_passwd);
453 failf(data, "failed to load private key from crypto engine\n");
456 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
457 failf(data, "unable to set private key\n");
458 EVP_PKEY_free(priv_key);
461 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
464 failf(data, "crypto engine not set, can't load private key\n");
470 failf(data, "file type ENG for private key not supported\n");
473 case SSL_FILETYPE_PKCS12:
475 failf(data, "file type P12 for private key not supported\n");
480 failf(data, "not supported file type for private key\n");
486 failf(data,"unable to create an SSL structure\n");
490 x509=SSL_get_certificate(ssl);
492 /* This version was provided by Evan Jordan and is supposed to not
493 leak memory as the previous version: */
495 EVP_PKEY *pktmp = X509_get_pubkey(x509);
496 EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
497 EVP_PKEY_free(pktmp);
502 /* If we are using DSA, we can copy the parameters from
506 /* Now we know that a key and cert have been set against
508 if(!SSL_CTX_check_private_key(ctx)) {
509 failf(data, "Private key does not match the certificate public key");
512 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
514 memset(global_passwd, 0, sizeof(global_passwd));
521 int cert_verify_callback(int ok, X509_STORE_CTX *ctx)
526 err_cert=X509_STORE_CTX_get_current_cert(ctx);
527 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
531 /* Return error string for last OpenSSL error
533 static char *SSL_strerror(unsigned long error, char *buf, size_t size)
535 #ifdef HAVE_ERR_ERROR_STRING_N
536 /* OpenSSL 0.9.6 and later has a function named
537 ERRO_error_string_n() that takes the size of the buffer as a
539 ERR_error_string_n(error, buf, size);
542 ERR_error_string(error, buf);
547 #endif /* USE_SSLEAY */
553 * @retval 0 error initializing SSL
554 * @retval 1 SSL initialized successfully
556 int Curl_ossl_init(void)
558 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
559 ENGINE_load_builtin_engines();
562 /* Lets get nice error messages */
563 SSL_load_error_strings();
565 /* Setup all the global SSL stuff */
566 if (!SSLeay_add_ssl_algorithms())
572 #endif /* USE_SSLEAY */
577 void Curl_ossl_cleanup(void)
579 /* Free the SSL error strings */
582 /* EVP_cleanup() removes all ciphers and digests from the
586 #ifdef HAVE_ENGINE_cleanup
590 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
591 /* this function was not present in 0.9.6b, but was added sometimes
593 CRYPTO_cleanup_all_ex_data();
598 * This function uses SSL_peek to determine connection status.
601 * 1 means the connection is still in place
602 * 0 means the connection has been closed
603 * -1 means the connection status is unknown
605 int Curl_ossl_check_cxn(struct connectdata *conn)
610 rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1);
612 return 1; /* connection still in place */
615 return 0; /* connection has been closed */
617 return -1; /* connection status unknown */
620 #endif /* USE_SSLEAY */
622 /* Selects an OpenSSL crypto engine
624 CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
626 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
627 ENGINE *e = ENGINE_by_id(engine);
630 failf(data, "SSL Engine '%s' not found", engine);
631 return (CURLE_SSL_ENGINE_NOTFOUND);
634 if (data->state.engine) {
635 ENGINE_finish(data->state.engine);
636 ENGINE_free(data->state.engine);
637 data->state.engine = NULL;
639 if (!ENGINE_init(e)) {
643 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
644 engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
645 return (CURLE_SSL_ENGINE_INITFAILED);
647 data->state.engine = e;
651 failf(data, "SSL Engine not supported");
652 return (CURLE_SSL_ENGINE_NOTFOUND);
657 /* Sets engine as default for all SSL operations
659 CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
661 #ifdef HAVE_OPENSSL_ENGINE_H
662 if (data->state.engine) {
663 if (ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
664 infof(data,"set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine));
667 failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine));
668 return CURLE_SSL_ENGINE_SETFAILED;
676 #endif /* USE_SSLEAY */
678 /* Return list of OpenSSL crypto engine names.
680 struct curl_slist *Curl_ossl_engines_list(struct SessionHandle *data)
682 struct curl_slist *list = NULL;
683 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
686 for (e = ENGINE_get_first(); e; e = ENGINE_get_next(e))
687 list = curl_slist_append(list, ENGINE_get_id(e));
697 * This function is called when an SSL connection is closed.
699 void Curl_ossl_close(struct connectdata *conn)
703 ERR_remove_state() frees the error queue associated with
704 thread pid. If pid == 0, the current thread will have its
707 Since error queue data structures are allocated
708 automatically for new threads, they must be freed when
709 threads are terminated in oder to avoid memory leaks.
714 struct ssl_connect_data *connssl = &conn->ssl[i];
716 if(connssl->handle) {
717 (void)SSL_shutdown(connssl->handle);
718 SSL_set_connect_state(connssl->handle);
720 SSL_free (connssl->handle);
721 connssl->handle = NULL;
724 SSL_CTX_free (connssl->ctx);
727 connssl->use = FALSE; /* get back to ordinary socket usage */
732 * This function is called to shut down the SSL layer but keep the
733 * socket open (CCC - Clear Command Channel)
735 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
738 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
739 struct SessionHandle *data = conn->data;
740 char buf[120]; /* We will use this for the OpenSSL error buffer, so it has
741 to be at least 120 bytes long. */
742 unsigned long sslerror;
747 /* This has only been tested on the proftpd server, and the mod_tls code
748 sends a close notify alert without waiting for a close notify alert in
749 response. Thus we wait for a close notify alert from the server, but
750 we do not send one. Let's hope other servers do the same... */
752 if(connssl->handle) {
754 int what = Curl_select(conn->sock[sockindex],
755 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
757 /* Something to read, let's do it and hope that it is the close
758 notify alert from the server */
759 nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
761 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
764 case SSL_ERROR_NONE: /* this is not an error */
765 case SSL_ERROR_ZERO_RETURN: /* no more data */
766 /* This is the expected response. There was no data but only
767 the close notify alert */
770 case SSL_ERROR_WANT_READ:
771 /* there's data pending, re-invoke SSL_read() */
772 infof(data, "SSL_ERROR_WANT_READ\n");
774 case SSL_ERROR_WANT_WRITE:
775 /* SSL wants a write. Really odd. Let's bail out. */
776 infof(data, "SSL_ERROR_WANT_WRITE\n");
780 /* openssl/ssl.h says "look at error stack/return value/errno" */
781 sslerror = ERR_get_error();
782 failf(conn->data, "SSL read: %s, errno %d",
783 ERR_error_string(sslerror, buf),
791 failf(data, "SSL shutdown timeout");
796 /* anything that gets here is fatally bad */
797 failf(data, "select on SSL socket, errno: %d", Curl_sockerrno());
801 } /* while()-loop for the select() */
803 if(data->set.verbose) {
804 switch(SSL_get_shutdown(connssl->handle)) {
805 case SSL_SENT_SHUTDOWN:
806 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
808 case SSL_RECEIVED_SHUTDOWN:
809 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
811 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
812 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
813 "SSL_RECEIVED__SHUTDOWN\n");
818 connssl->use = FALSE; /* get back to ordinary socket usage */
820 SSL_free (connssl->handle);
821 connssl->handle = NULL;
826 void Curl_ossl_session_free(void *ptr)
829 SSL_SESSION_free(ptr);
833 * This function is called when the 'data' struct is going away. Close
834 * down everything and free all resources!
836 int Curl_ossl_close_all(struct SessionHandle *data)
838 #ifdef HAVE_OPENSSL_ENGINE_H
839 if(data->state.engine) {
840 ENGINE_finish(data->state.engine);
841 ENGINE_free(data->state.engine);
842 data->state.engine = NULL;
850 static int Curl_ASN1_UTCTIME_output(struct connectdata *conn,
857 int year=0,month=0,day=0,hour=0,minute=0,second=0;
858 struct SessionHandle *data = conn->data;
860 if(!data->set.verbose)
864 asn1_string=(char *)tm->data;
868 if(asn1_string[i-1] == 'Z')
871 if((asn1_string[i] > '9') || (asn1_string[i] < '0'))
874 year= (asn1_string[0]-'0')*10+(asn1_string[1]-'0');
878 month= (asn1_string[2]-'0')*10+(asn1_string[3]-'0');
879 if((month > 12) || (month < 1))
882 day= (asn1_string[4]-'0')*10+(asn1_string[5]-'0');
883 hour= (asn1_string[6]-'0')*10+(asn1_string[7]-'0');
884 minute= (asn1_string[8]-'0')*10+(asn1_string[9]-'0');
886 if((asn1_string[10] >= '0') && (asn1_string[10] <= '9') &&
887 (asn1_string[11] >= '0') && (asn1_string[11] <= '9'))
888 second= (asn1_string[10]-'0')*10+(asn1_string[11]-'0');
891 "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
892 prefix, year+1900, month, day, hour, minute, second, (gmt?"GMT":""));
899 /* ====================================================== */
903 * Match a hostname against a wildcard pattern.
905 * "foo.host.com" matches "*.host.com".
907 * We are a bit more liberal than RFC2818 describes in that we
908 * accept multiple "*" in pattern (similar to what some other browsers do).
910 * "abc.def.domain.com" should strickly not match "*.domain.com", but we
911 * don't consider "." to be important in CERT checking.
913 #define HOST_NOMATCH 0
916 static int hostmatch(const char *hostname, const char *pattern)
922 return (*hostname ? HOST_NOMATCH : HOST_MATCH);
926 if (c == '\0') /* "*\0" matches anything remaining */
930 /* The only recursive function in libcurl! */
931 if (hostmatch(hostname++,pattern) == HOST_MATCH)
937 if (toupper(c) != toupper(*hostname++))
944 cert_hostcheck(const char *match_pattern, const char *hostname)
946 if (!match_pattern || !*match_pattern ||
947 !hostname || !*hostname) /* sanity check */
950 if(curl_strequal(hostname,match_pattern)) /* trivial case */
953 if (hostmatch(hostname,match_pattern) == HOST_MATCH)
958 /* Quote from RFC2818 section 3.1 "Server Identity"
960 If a subjectAltName extension of type dNSName is present, that MUST
961 be used as the identity. Otherwise, the (most specific) Common Name
962 field in the Subject field of the certificate MUST be used. Although
963 the use of the Common Name is existing practice, it is deprecated and
964 Certification Authorities are encouraged to use the dNSName instead.
966 Matching is performed using the matching rules specified by
967 [RFC2459]. If more than one identity of a given type is present in
968 the certificate (e.g., more than one dNSName name, a match in any one
969 of the set is considered acceptable.) Names may contain the wildcard
970 character * which is considered to match any single domain name
971 component or component fragment. E.g., *.a.com matches foo.a.com but
972 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
974 In some cases, the URI is specified as an IP address rather than a
975 hostname. In this case, the iPAddress subjectAltName must be present
976 in the certificate and must exactly match the IP in the URI.
979 static CURLcode verifyhost(struct connectdata *conn,
982 bool matched = FALSE; /* no alternative match yet */
983 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
985 struct SessionHandle *data = conn->data;
986 STACK_OF(GENERAL_NAME) *altnames;
988 struct in6_addr addr;
992 CURLcode res = CURLE_OK;
995 if(conn->bits.ipv6_ip &&
996 Curl_inet_pton(AF_INET6, conn->host.name, &addr)) {
998 addrlen = sizeof(struct in6_addr);
1002 if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) {
1004 addrlen = sizeof(struct in_addr);
1007 /* get a "list" of alternative names */
1008 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1014 /* get amount of alternatives, RFC2459 claims there MUST be at least
1015 one, but we don't depend on it... */
1016 numalts = sk_GENERAL_NAME_num(altnames);
1018 /* loop through all alternatives while none has matched */
1019 for (i=0; (i<numalts) && !matched; i++) {
1020 /* get a handle to alternative name number i */
1021 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1023 /* only check alternatives of the same type the target is */
1024 if(check->type == target) {
1025 /* get data and length */
1026 const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
1030 case GEN_DNS: /* name/pattern comparison */
1031 /* The OpenSSL man page explicitly says: "In general it cannot be
1032 assumed that the data returned by ASN1_STRING_data() is null
1033 terminated or does not contain embedded nulls." But also that
1034 "The actual format of the data will depend on the actual string
1035 type itself: for example for and IA5String the data will be ASCII"
1037 Gisle researched the OpenSSL sources:
1038 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1039 it always 0-terminates an IA5String."
1041 if (cert_hostcheck(altptr, conn->host.name))
1045 case GEN_IPADD: /* IP address comparison */
1046 /* compare alternative IP address if the data chunk is the same size
1047 our server IP address is */
1048 altlen = ASN1_STRING_length(check->d.ia5);
1049 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen))
1055 GENERAL_NAMES_free(altnames);
1059 /* an alternative name matched the server hostname */
1060 infof(data, "\t subjectAltName: %s matched\n", conn->host.dispname);
1062 /* we have to look to the last occurence of a commonName in the
1063 distinguished one to get the most significant one. */
1066 /* The following is done because of a bug in 0.9.6b */
1068 unsigned char *nulstr = (unsigned char *)"";
1069 unsigned char *peer_CN = nulstr;
1071 X509_NAME *name = X509_get_subject_name(server_cert) ;
1073 while ((j=X509_NAME_get_index_by_NID(name,NID_commonName,i))>=0)
1076 /* we have the name entry and we will now convert this to a string
1077 that we can use for comparison. Doing this we support BMPstring,
1081 ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
1083 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1084 is already UTF-8 encoded. We check for this case and copy the raw
1085 string manually to avoid the problem. This code can be made
1086 conditional in the future when OpenSSL has been fixed. Work-around
1087 brought by Alexis S. L. Carvalho. */
1088 if (tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1089 j = ASN1_STRING_length(tmp);
1091 peer_CN = OPENSSL_malloc(j+1);
1093 memcpy(peer_CN, ASN1_STRING_data(tmp), j);
1098 else /* not a UTF8 name */
1099 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1102 if (peer_CN == nulstr)
1104 #ifdef CURL_DOES_CONVERSIONS
1106 /* convert peer_CN from UTF8 */
1108 rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
1109 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1110 if (rc != CURLE_OK) {
1114 #endif /* CURL_DOES_CONVERSIONS */
1117 if(data->set.ssl.verifyhost > 1) {
1119 "SSL: unable to obtain common name from peer certificate");
1120 return CURLE_SSL_PEER_CERTIFICATE;
1123 /* Consider verifyhost == 1 as an "OK" for a missing CN field, but we
1124 output a note about the situation */
1125 infof(data, "\t common name: WARNING couldn't obtain\n");
1128 else if(!cert_hostcheck((const char *)peer_CN, conn->host.name)) {
1129 if(data->set.ssl.verifyhost > 1) {
1130 failf(data, "SSL: certificate subject name '%s' does not match "
1131 "target host name '%s'", peer_CN, conn->host.dispname);
1132 res = CURLE_SSL_PEER_CERTIFICATE;
1135 infof(data, "\t common name: %s (does not match '%s')\n",
1136 peer_CN, conn->host.dispname);
1139 infof(data, "\t common name: %s (matched)\n", peer_CN);
1142 OPENSSL_free(peer_CN);
1148 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1149 and thus this cannot be done there. */
1150 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1152 static const char *ssl_msg_type(int ssl_ver, int msg)
1154 if (ssl_ver == SSL2_VERSION_MAJOR) {
1158 case SSL2_MT_CLIENT_HELLO:
1159 return "Client hello";
1160 case SSL2_MT_CLIENT_MASTER_KEY:
1161 return "Client key";
1162 case SSL2_MT_CLIENT_FINISHED:
1163 return "Client finished";
1164 case SSL2_MT_SERVER_HELLO:
1165 return "Server hello";
1166 case SSL2_MT_SERVER_VERIFY:
1167 return "Server verify";
1168 case SSL2_MT_SERVER_FINISHED:
1169 return "Server finished";
1170 case SSL2_MT_REQUEST_CERTIFICATE:
1171 return "Request CERT";
1172 case SSL2_MT_CLIENT_CERTIFICATE:
1173 return "Client CERT";
1176 else if (ssl_ver == SSL3_VERSION_MAJOR) {
1178 case SSL3_MT_HELLO_REQUEST:
1179 return "Hello request";
1180 case SSL3_MT_CLIENT_HELLO:
1181 return "Client hello";
1182 case SSL3_MT_SERVER_HELLO:
1183 return "Server hello";
1184 case SSL3_MT_CERTIFICATE:
1186 case SSL3_MT_SERVER_KEY_EXCHANGE:
1187 return "Server key exchange";
1188 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1189 return "Client key exchange";
1190 case SSL3_MT_CERTIFICATE_REQUEST:
1191 return "Request CERT";
1192 case SSL3_MT_SERVER_DONE:
1193 return "Server finished";
1194 case SSL3_MT_CERTIFICATE_VERIFY:
1195 return "CERT verify";
1196 case SSL3_MT_FINISHED:
1203 static const char *tls_rt_type(int type)
1206 type == SSL3_RT_CHANGE_CIPHER_SPEC ? "TLS change cipher, " :
1207 type == SSL3_RT_ALERT ? "TLS alert, " :
1208 type == SSL3_RT_HANDSHAKE ? "TLS handshake, " :
1209 type == SSL3_RT_APPLICATION_DATA ? "TLS app data, " :
1215 * Our callback from the SSL/TLS layers.
1217 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1218 const void *buf, size_t len, const SSL *ssl,
1219 struct connectdata *conn)
1221 struct SessionHandle *data;
1222 const char *msg_name, *tls_rt_name;
1224 int ver, msg_type, txt_len;
1226 if (!conn || !conn->data || !conn->data->set.fdebug ||
1227 (direction != 0 && direction != 1))
1232 ver = (ssl_ver == SSL2_VERSION_MAJOR ? '2' :
1233 ssl_ver == SSL3_VERSION_MAJOR ? '3' : '?');
1235 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1236 * always pass-up content-type as 0. But the interesting message-type
1239 if (ssl_ver == SSL3_VERSION_MAJOR && content_type != 0)
1240 tls_rt_name = tls_rt_type(content_type);
1244 msg_type = *(char*)buf;
1245 msg_name = ssl_msg_type(ssl_ver, msg_type);
1247 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "SSLv%c, %s%s (%d):\n",
1248 ver, tls_rt_name, msg_name, msg_type);
1249 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1251 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1252 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1258 /* ====================================================== */
1261 Curl_ossl_connect_step1(struct connectdata *conn,
1264 CURLcode retcode = CURLE_OK;
1266 struct SessionHandle *data = conn->data;
1267 SSL_METHOD_QUAL SSL_METHOD *req_method=NULL;
1268 void *ssl_sessionid=NULL;
1269 curl_socket_t sockfd = conn->sock[sockindex];
1270 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1272 curlassert(ssl_connect_1 == connssl->connecting_state);
1274 /* Make funny stuff to get random input */
1275 Curl_ossl_seed(data);
1277 /* check to see if we've been told to use an explicit SSL/TLS version */
1278 switch(data->set.ssl.version) {
1280 case CURL_SSLVERSION_DEFAULT:
1281 /* we try to figure out version */
1282 req_method = SSLv23_client_method();
1284 case CURL_SSLVERSION_TLSv1:
1285 req_method = TLSv1_client_method();
1287 case CURL_SSLVERSION_SSLv2:
1288 #ifdef OPENSSL_NO_SSL2
1289 failf(data, "OpenSSL was built without SSLv2 support");
1290 return CURLE_NOT_BUILT_IN;
1292 req_method = SSLv2_client_method();
1295 case CURL_SSLVERSION_SSLv3:
1296 req_method = SSLv3_client_method();
1301 SSL_CTX_free(connssl->ctx);
1302 connssl->ctx = SSL_CTX_new(req_method);
1305 failf(data, "SSL: couldn't create a context!");
1306 return CURLE_OUT_OF_MEMORY;
1309 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1310 if (data->set.fdebug && data->set.verbose) {
1311 /* the SSL trace callback is only used for verbose logging so we only
1312 inform about failures of setting it */
1313 if (!SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK,
1314 (void (*)(void))ssl_tls_trace)) {
1315 infof(data, "SSL: couldn't set callback!\n");
1317 else if (!SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0,
1319 infof(data, "SSL: couldn't set callback argument!\n");
1324 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1325 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1326 work-arounds. The man page for this option states that SSL_OP_ALL enables
1327 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1328 enable the bug workaround options if compatibility with somewhat broken
1329 implementations is desired."
1332 SSL_CTX_set_options(connssl->ctx, SSL_OP_ALL);
1336 * Not sure it's needed to tell SSL_connect() that socket is
1337 * non-blocking. It doesn't seem to care, but just return with
1340 if (data->state.used_interface == Curl_if_multi)
1341 SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL);
1344 if(data->set.cert) {
1345 if(!cert_stuff(conn,
1348 data->set.cert_type,
1350 data->set.key_type)) {
1351 /* failf() is already done in cert_stuff() */
1352 return CURLE_SSL_CERTPROBLEM;
1356 if(data->set.ssl.cipher_list) {
1357 if(!SSL_CTX_set_cipher_list(connssl->ctx,
1358 data->set.ssl.cipher_list)) {
1359 failf(data, "failed setting cipher list");
1360 return CURLE_SSL_CIPHER;
1364 if (data->set.ssl.CAfile || data->set.ssl.CApath) {
1365 /* tell SSL where to find CA certificates that are used to verify
1366 the servers certificate. */
1367 if (!SSL_CTX_load_verify_locations(connssl->ctx, data->set.ssl.CAfile,
1368 data->set.ssl.CApath)) {
1369 if (data->set.ssl.verifypeer) {
1370 /* Fail if we insist on successfully verifying the server. */
1371 failf(data,"error setting certificate verify locations:\n"
1372 " CAfile: %s\n CApath: %s\n",
1373 data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
1374 data->set.ssl.CApath ? data->set.ssl.CApath : "none");
1375 return CURLE_SSL_CACERT_BADFILE;
1378 /* Just continue with a warning if no strict certificate verification
1380 infof(data, "error setting certificate verify locations,"
1381 " continuing anyway:\n");
1385 /* Everything is fine. */
1386 infof(data, "successfully set certificate verify locations:\n");
1391 data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
1392 data->set.ssl.CApath ? data->set.ssl.CApath : "none");
1394 /* SSL always tries to verify the peer, this only says whether it should
1395 * fail to connect if the verification fails, or if it should continue
1396 * anyway. In the latter case the result of the verification is checked with
1397 * SSL_get_verify_result() below. */
1398 SSL_CTX_set_verify(connssl->ctx,
1399 data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE,
1400 cert_verify_callback);
1402 /* give application a chance to interfere with SSL set up. */
1403 if(data->set.ssl.fsslctx) {
1404 retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx,
1405 data->set.ssl.fsslctxp);
1407 failf(data,"error signaled by ssl ctx callback");
1412 /* Lets make an SSL structure */
1413 if (connssl->handle)
1414 SSL_free(connssl->handle);
1415 connssl->handle = SSL_new(connssl->ctx);
1416 if (!connssl->handle) {
1417 failf(data, "SSL: couldn't create a context (handle)!");
1418 return CURLE_OUT_OF_MEMORY;
1420 SSL_set_connect_state(connssl->handle);
1422 connssl->server_cert = 0x0;
1424 /* Check if there's a cached ID we can/should use here! */
1425 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
1426 /* we got a session id, use it! */
1427 if (!SSL_set_session(connssl->handle, ssl_sessionid)) {
1428 failf(data, "SSL: SSL_set_session failed: %s",
1429 ERR_error_string(ERR_get_error(),NULL));
1430 return CURLE_SSL_CONNECT_ERROR;
1432 /* Informational message */
1433 infof (data, "SSL re-using session ID\n");
1436 /* pass the raw socket into the SSL layers */
1437 if (!SSL_set_fd(connssl->handle, sockfd)) {
1438 failf(data, "SSL: SSL_set_fd failed: %s",
1439 ERR_error_string(ERR_get_error(),NULL));
1440 return CURLE_SSL_CONNECT_ERROR;
1443 connssl->connecting_state = ssl_connect_2;
1448 Curl_ossl_connect_step2(struct connectdata *conn,
1449 int sockindex, long *timeout_ms)
1451 struct SessionHandle *data = conn->data;
1454 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1456 curlassert(ssl_connect_2 == connssl->connecting_state
1457 || ssl_connect_2_reading == connssl->connecting_state
1458 || ssl_connect_2_writing == connssl->connecting_state);
1460 /* Find out if any timeout is set. If not, use 300 seconds.
1461 Otherwise, figure out the most strict timeout of the two possible one
1462 and then how much time that has elapsed to know how much time we
1463 allow for the connect call */
1464 if(data->set.timeout && data->set.connecttimeout) {
1465 /* get the most strict timeout of the ones converted to milliseconds */
1466 if(data->set.timeout<data->set.connecttimeout)
1467 *timeout_ms = data->set.timeout*1000;
1469 *timeout_ms = data->set.connecttimeout*1000;
1471 else if(data->set.timeout)
1472 *timeout_ms = data->set.timeout*1000;
1473 else if(data->set.connecttimeout)
1474 *timeout_ms = data->set.connecttimeout*1000;
1476 /* no particular time-out has been set */
1477 *timeout_ms= DEFAULT_CONNECT_TIMEOUT;
1479 /* Evaluate in milliseconds how much time that has passed */
1480 has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle);
1482 /* subtract the passed time */
1483 *timeout_ms -= has_passed;
1485 if(*timeout_ms < 0) {
1486 /* a precaution, no need to continue if time already is up */
1487 failf(data, "SSL connection timeout");
1488 return CURLE_OPERATION_TIMEOUTED;
1491 err = SSL_connect(connssl->handle);
1494 0 is "not successful but was shut down controlled"
1495 <0 is "handshake was not successful, because a fatal error occurred" */
1497 int detail = SSL_get_error(connssl->handle, err);
1499 if(SSL_ERROR_WANT_READ == detail) {
1500 connssl->connecting_state = ssl_connect_2_reading;
1503 else if(SSL_ERROR_WANT_WRITE == detail) {
1504 connssl->connecting_state = ssl_connect_2_writing;
1508 /* untreated error */
1509 unsigned long errdetail;
1510 char error_buffer[256]; /* OpenSSL documents that this must be at least
1513 const char *cert_problem = NULL;
1515 connssl->connecting_state = ssl_connect_2; /* the connection failed,
1516 we're not waiting for
1519 errdetail = ERR_get_error(); /* Gets the earliest error code from the
1520 thread's error queue and removes the
1527 SSL2_SET_CERTIFICATE:
1528 certificate verify failed */
1533 SSL3_GET_SERVER_CERTIFICATE:
1534 certificate verify failed */
1535 cert_problem = "SSL certificate problem, verify that the CA cert is"
1537 rc = CURLE_SSL_CACERT;
1540 rc = CURLE_SSL_CONNECT_ERROR;
1544 /* detail is already set to the SSL error above */
1546 /* If we e.g. use SSLv2 request-method and the server doesn't like us
1547 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
1548 * the SO_ERROR is also lost.
1550 if (CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) {
1551 failf(data, "Unknown SSL protocol error in connection to %s:%d ",
1552 conn->host.name, conn->port);
1555 /* Could be a CERT problem */
1557 SSL_strerror(errdetail, error_buffer, sizeof(error_buffer));
1558 failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer);
1563 /* we have been connected fine, we're not waiting for anything else. */
1564 connssl->connecting_state = ssl_connect_3;
1566 /* Informational message */
1567 infof (data, "SSL connection using %s\n",
1568 SSL_get_cipher(connssl->handle));
1575 Curl_ossl_connect_step3(struct connectdata *conn,
1578 CURLcode retcode = CURLE_OK;
1581 ASN1_TIME *certdate;
1582 void *ssl_sessionid=NULL;
1583 struct SessionHandle *data = conn->data;
1584 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1586 curlassert(ssl_connect_3 == connssl->connecting_state);
1588 if(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL)) {
1589 /* Since this is not a cached session ID, then we want to stach this one
1591 SSL_SESSION *our_ssl_sessionid;
1592 #ifdef HAVE_SSL_GET1_SESSION
1593 our_ssl_sessionid = SSL_get1_session(connssl->handle);
1595 /* SSL_get1_session() will increment the reference
1596 count and the session will stay in memory until explicitly freed with
1597 SSL_SESSION_free(3), regardless of its state.
1598 This function was introduced in openssl 0.9.5a. */
1600 our_ssl_sessionid = SSL_get_session(connssl->handle);
1602 /* if SSL_get1_session() is unavailable, use SSL_get_session().
1603 This is an inferior option because the session can be flushed
1604 at any time by openssl. It is included only so curl compiles
1605 under versions of openssl < 0.9.5a.
1607 WARNING: How curl behaves if it's session is flushed is
1611 retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
1612 0 /* unknown size */);
1614 failf(data, "failed to store ssl session");
1620 /* Get server's certificate (note: beware of dynamic allocation) - opt */
1621 /* major serious hack alert -- we should check certificates
1622 * to authenticate the server; otherwise we risk man-in-the-middle
1626 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
1627 if(!connssl->server_cert) {
1628 failf(data, "SSL: couldn't get peer certificate!");
1629 return CURLE_SSL_PEER_CERTIFICATE;
1631 infof (data, "Server certificate:\n");
1633 str = X509_NAME_oneline(X509_get_subject_name(connssl->server_cert),
1636 failf(data, "SSL: couldn't get X509-subject!");
1637 X509_free(connssl->server_cert);
1638 connssl->server_cert = NULL;
1639 return CURLE_SSL_CONNECT_ERROR;
1641 infof(data, "\t subject: %s\n", str);
1644 certdate = X509_get_notBefore(connssl->server_cert);
1645 Curl_ASN1_UTCTIME_output(conn, "\t start date: ", certdate);
1647 certdate = X509_get_notAfter(connssl->server_cert);
1648 Curl_ASN1_UTCTIME_output(conn, "\t expire date: ", certdate);
1650 if(data->set.ssl.verifyhost) {
1651 retcode = verifyhost(conn, connssl->server_cert);
1653 X509_free(connssl->server_cert);
1654 connssl->server_cert = NULL;
1659 str = X509_NAME_oneline(X509_get_issuer_name(connssl->server_cert),
1662 failf(data, "SSL: couldn't get X509-issuer name!");
1663 retcode = CURLE_SSL_CONNECT_ERROR;
1666 infof(data, "\t issuer: %s\n", str);
1669 /* We could do all sorts of certificate verification stuff here before
1670 deallocating the certificate. */
1672 lerr = data->set.ssl.certverifyresult=
1673 SSL_get_verify_result(connssl->handle);
1674 if(data->set.ssl.certverifyresult != X509_V_OK) {
1675 if(data->set.ssl.verifypeer) {
1676 /* We probably never reach this, because SSL_connect() will fail
1677 and we return earlyer if verifypeer is set? */
1678 failf(data, "SSL certificate verify result: %s (%ld)",
1679 X509_verify_cert_error_string(lerr), lerr);
1680 retcode = CURLE_SSL_PEER_CERTIFICATE;
1683 infof(data, "SSL certificate verify result: %s (%ld),"
1684 " continuing anyway.\n",
1685 X509_verify_cert_error_string(lerr), lerr);
1688 infof(data, "SSL certificate verify ok.\n");
1691 X509_free(connssl->server_cert);
1692 connssl->server_cert = NULL;
1693 connssl->connecting_state = ssl_connect_done;
1698 Curl_ossl_connect_common(struct connectdata *conn,
1704 struct SessionHandle *data = conn->data;
1705 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1706 curl_socket_t sockfd = conn->sock[sockindex];
1709 if (ssl_connect_1==connssl->connecting_state) {
1710 retcode = Curl_ossl_connect_step1(conn, sockindex);
1716 while (ssl_connect_2 == connssl->connecting_state ||
1717 ssl_connect_2_reading == connssl->connecting_state ||
1718 ssl_connect_2_writing == connssl->connecting_state) {
1720 /* if ssl is expecting something, check if it's available. */
1721 if (connssl->connecting_state == ssl_connect_2_reading
1722 || connssl->connecting_state == ssl_connect_2_writing) {
1724 int writefd = ssl_connect_2_writing==
1725 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
1726 int readfd = ssl_connect_2_reading==
1727 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
1730 int what = Curl_select(readfd, writefd, nonblocking?0:(int)timeout_ms);
1732 /* readable or writable, go loop in the outer loop */
1734 else if(0 == what) {
1741 failf(data, "SSL connection timeout");
1742 return CURLE_OPERATION_TIMEDOUT;
1746 /* anything that gets here is fatally bad */
1747 failf(data, "select on SSL socket, errno: %d", Curl_sockerrno());
1748 return CURLE_SSL_CONNECT_ERROR;
1750 } /* while()-loop for the select() */
1753 /* get the timeout from step2 to avoid computing it twice. */
1754 retcode = Curl_ossl_connect_step2(conn, sockindex, &timeout_ms);
1758 } /* repeat step2 until all transactions are done. */
1761 if (ssl_connect_3==connssl->connecting_state) {
1762 retcode = Curl_ossl_connect_step3(conn, sockindex);
1767 if (ssl_connect_done==connssl->connecting_state) {
1774 /* Reset our connect state machine */
1775 connssl->connecting_state = ssl_connect_1;
1781 Curl_ossl_connect_nonblocking(struct connectdata *conn,
1785 return Curl_ossl_connect_common(conn, sockindex, TRUE, done);
1789 Curl_ossl_connect(struct connectdata *conn,
1795 retcode = Curl_ossl_connect_common(conn, sockindex, FALSE, &done);
1804 /* return number of sent (non-SSL) bytes */
1805 ssize_t Curl_ossl_send(struct connectdata *conn,
1810 /* SSL_write() is said to return 'int' while write() and send() returns
1813 char error_buffer[120]; /* OpenSSL documents that this must be at least 120
1815 unsigned long sslerror;
1816 int rc = SSL_write(conn->ssl[sockindex].handle, mem, (int)len);
1819 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
1822 case SSL_ERROR_WANT_READ:
1823 case SSL_ERROR_WANT_WRITE:
1824 /* The operation did not complete; the same TLS/SSL I/O function
1825 should be called again later. This is basicly an EWOULDBLOCK
1828 case SSL_ERROR_SYSCALL:
1829 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d\n",
1833 /* A failure in the SSL library occurred, usually a protocol error.
1834 The OpenSSL error queue contains more information on the error. */
1835 sslerror = ERR_get_error();
1836 failf(conn->data, "SSL_write() error: %s\n",
1837 ERR_error_string(sslerror, error_buffer));
1841 failf(conn->data, "SSL_write() return error %d\n", err);
1844 return (ssize_t)rc; /* number of bytes */
1848 * If the read would block we return -1 and set 'wouldblock' to TRUE.
1849 * Otherwise we return the amount of data read. Other errors should return -1
1850 * and set 'wouldblock' to FALSE.
1852 ssize_t Curl_ossl_recv(struct connectdata *conn, /* connection data */
1853 int num, /* socketindex */
1854 char *buf, /* store read data here */
1855 size_t buffersize, /* max amount to read */
1858 char error_buffer[120]; /* OpenSSL documents that this must be at
1859 least 120 bytes long. */
1860 unsigned long sslerror;
1861 ssize_t nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf,
1863 *wouldblock = FALSE;
1865 /* failed SSL_read */
1866 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
1869 case SSL_ERROR_NONE: /* this is not an error */
1870 case SSL_ERROR_ZERO_RETURN: /* no more data */
1872 case SSL_ERROR_WANT_READ:
1873 case SSL_ERROR_WANT_WRITE:
1874 /* there's data pending, re-invoke SSL_read() */
1876 return -1; /* basically EWOULDBLOCK */
1878 /* openssl/ssl.h says "look at error stack/return value/errno" */
1879 sslerror = ERR_get_error();
1880 failf(conn->data, "SSL read: %s, errno %d",
1881 ERR_error_string(sslerror, error_buffer),
1889 size_t Curl_ossl_version(char *buffer, size_t size)
1891 #ifdef YASSL_VERSION
1892 /* yassl provides an OpenSSL API compatiblity layer so it looks identical
1893 to OpenSSL in all other aspects */
1894 return snprintf(buffer, size, " yassl/%s", YASSL_VERSION);
1895 #else /* YASSL_VERSION */
1897 #if (SSLEAY_VERSION_NUMBER >= 0x905000)
1900 unsigned long ssleay_value;
1902 ssleay_value=SSLeay();
1903 if(ssleay_value < 0x906000) {
1904 ssleay_value=SSLEAY_VERSION_NUMBER;
1908 if(ssleay_value&0xff0) {
1909 sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1);
1915 return snprintf(buffer, size, " OpenSSL/%lx.%lx.%lx%s",
1916 (ssleay_value>>28)&0xf,
1917 (ssleay_value>>20)&0xff,
1918 (ssleay_value>>12)&0xff,
1922 #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
1924 #if (SSLEAY_VERSION_NUMBER >= 0x900000)
1925 return snprintf(buffer, size, " OpenSSL/%lx.%lx.%lx",
1926 (SSLEAY_VERSION_NUMBER>>28)&0xff,
1927 (SSLEAY_VERSION_NUMBER>>20)&0xff,
1928 (SSLEAY_VERSION_NUMBER>>12)&0xf);
1930 #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
1934 if(SSLEAY_VERSION_NUMBER&0x0f) {
1935 sub[0]=(SSLEAY_VERSION_NUMBER&0x0f) + 'a' -1;
1940 return snprintf(buffer, size, " SSL/%x.%x.%x%s",
1941 (SSLEAY_VERSION_NUMBER>>12)&0xff,
1942 (SSLEAY_VERSION_NUMBER>>8)&0xf,
1943 (SSLEAY_VERSION_NUMBER>>4)&0xf, sub);
1945 #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
1946 #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
1948 #endif /* YASSL_VERSION */
1950 #endif /* USE_SSLEAY */