1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 * $Id: ssluse.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
22 ***************************************************************************/
25 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
26 * but sslgen.c should ever call or use these functions.
30 * The original SSLeay-using code for curl was written by Linas Vepstas and
31 * Sampo Kellomaki 1998.
39 #ifdef HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
45 #include "formdata.h" /* for the boundary function */
46 #include "url.h" /* for the ssl config check function */
47 #include "inet_pton.h"
54 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
55 #include <curl/mprintf.h>
60 #include <openssl/rand.h>
61 #include <openssl/x509v3.h>
68 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
70 /* The last #include file should be: */
73 #if OPENSSL_VERSION_NUMBER >= 0x0090581fL
74 #define HAVE_SSL_GET1_SESSION 1
76 #undef HAVE_SSL_GET1_SESSION
79 #if OPENSSL_VERSION_NUMBER >= 0x00904100L
80 #define HAVE_USERDATA_IN_PWD_CALLBACK 1
82 #undef HAVE_USERDATA_IN_PWD_CALLBACK
85 #if OPENSSL_VERSION_NUMBER >= 0x00907001L
86 /* ENGINE_load_private_key() takes four arguments */
87 #define HAVE_ENGINE_LOAD_FOUR_ARGS
89 /* ENGINE_load_private_key() takes three arguments */
90 #undef HAVE_ENGINE_LOAD_FOUR_ARGS
93 #if (OPENSSL_VERSION_NUMBER >= 0x00903001L) && defined(HAVE_OPENSSL_PKCS12_H)
94 /* OpenSSL has PKCS 12 support */
95 #define HAVE_PKCS12_SUPPORT
97 /* OpenSSL/SSLEay does not have PKCS12 support */
98 #undef HAVE_PKCS12_SUPPORT
101 #if OPENSSL_VERSION_NUMBER >= 0x00906001L
102 #define HAVE_ERR_ERROR_STRING_N 1
105 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
106 #define SSL_METHOD_QUAL const
108 #define SSL_METHOD_QUAL
111 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
112 /* 0.9.6 didn't have X509_STORE_set_flags() */
113 #define HAVE_X509_STORE_SET_FLAGS 1
115 #define X509_STORE_set_flags(x,y)
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 #ifdef HAVE_USERDATA_IN_PWD_CALLBACK
132 /* This was introduced in 0.9.4, we can set this
133 using SSL_CTX_set_default_passwd_cb_userdata()
135 , void *global_passwd
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
.str
[STRING_SSL_RANDOM_FILE
]?
189 data
->set
.str
[STRING_SSL_RANDOM_FILE
]:
192 if(seed_enough(nread
))
196 #if defined(HAVE_RAND_EGD)
197 /* only available in OpenSSL 0.9.5 and later */
198 /* EGD_SOCKET is set at configure time or not at all */
200 /* If we don't have the define set, we only do this if the egd-option
202 if(data
->set
.str
[STRING_SSL_EGDSOCKET
])
203 #define EGD_SOCKET "" /* doesn't matter won't be used */
206 /* If there's an option and a define, the option overrides the
208 int ret
= RAND_egd(data
->set
.str
[STRING_SSL_EGDSOCKET
]?
209 data
->set
.str
[STRING_SSL_EGDSOCKET
]:EGD_SOCKET
);
212 if(seed_enough(nread
))
218 /* If we get here, it means we need to seed the PRNG using a "silly"
220 #ifdef HAVE_RAND_SCREEN
221 /* This one gets a random value by reading the currently shown screen */
223 nread
= 100; /* just a value */
229 /* Changed call to RAND_seed to use the underlying RAND_add implementation
230 * directly. Do this in a loop, with the amount of additional entropy
231 * being dependent upon the algorithm used by Curl_FormBoundary(): N bytes
232 * of a 7-bit ascii set. -- Richard Gorton, March 11 2003.
236 area
= Curl_FormBoundary();
238 return 3; /* out of memory */
240 len
= (int)strlen(area
);
241 RAND_add(area
, len
, (len
>> 1));
243 free(area
); /* now remove the random junk */
244 } while(!RAND_status());
248 /* generates a default path for the random seed file */
249 buf
[0]=0; /* blank it first */
250 RAND_file_name(buf
, BUFSIZE
);
252 /* we got a file name to try */
253 nread
+= RAND_load_file(buf
, RAND_LOAD_LENGTH
);
254 if(seed_enough(nread
))
258 infof(data
, "libcurl is now using a weak random seed!\n");
262 int Curl_ossl_seed(struct SessionHandle
*data
)
264 /* we have the "SSL is seeded" boolean static to prevent multiple
265 time-consuming seedings in vain */
266 static bool ssl_seeded
= FALSE
;
268 if(!ssl_seeded
|| data
->set
.str
[STRING_SSL_RANDOM_FILE
] ||
269 data
->set
.str
[STRING_SSL_EGDSOCKET
]) {
277 #ifndef SSL_FILETYPE_ENGINE
278 #define SSL_FILETYPE_ENGINE 42
280 #ifndef SSL_FILETYPE_PKCS12
281 #define SSL_FILETYPE_PKCS12 43
283 static int do_file_type(const char *type
)
285 if(!type
|| !type
[0])
286 return SSL_FILETYPE_PEM
;
287 if(curl_strequal(type
, "PEM"))
288 return SSL_FILETYPE_PEM
;
289 if(curl_strequal(type
, "DER"))
290 return SSL_FILETYPE_ASN1
;
291 if(curl_strequal(type
, "ENG"))
292 return SSL_FILETYPE_ENGINE
;
293 if(curl_strequal(type
, "P12"))
294 return SSL_FILETYPE_PKCS12
;
299 int cert_stuff(struct connectdata
*conn
,
302 const char *cert_type
,
304 const char *key_type
)
306 struct SessionHandle
*data
= conn
->data
;
309 if(cert_file
!= NULL
) {
314 if(data
->set
.str
[STRING_KEY_PASSWD
]) {
315 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
317 * If password has been given, we store that in the global
318 * area (*shudder*) for a while:
320 size_t len
= strlen(data
->set
.key_passwd
);
321 if(len
< sizeof(global_passwd
))
322 memcpy(global_passwd
, data
->set
.key_passwd
, len
+1);
325 * We set the password in the callback userdata
327 SSL_CTX_set_default_passwd_cb_userdata(ctx
,
328 data
->set
.str
[STRING_KEY_PASSWD
]);
330 /* Set passwd callback: */
331 SSL_CTX_set_default_passwd_cb(ctx
, passwd_callback
);
334 file_type
= do_file_type(cert_type
);
336 #define SSL_CLIENT_CERT_ERR \
337 "unable to use client certificate (no key found or wrong pass phrase?)"
340 case SSL_FILETYPE_PEM
:
341 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
342 if(SSL_CTX_use_certificate_chain_file(ctx
,
344 failf(data
, SSL_CLIENT_CERT_ERR
);
349 case SSL_FILETYPE_ASN1
:
350 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
351 we use the case above for PEM so this can only be performed with
353 if(SSL_CTX_use_certificate_file(ctx
,
356 failf(data
, SSL_CLIENT_CERT_ERR
);
360 case SSL_FILETYPE_ENGINE
:
361 failf(data
, "file type ENG for certificate not implemented");
364 case SSL_FILETYPE_PKCS12
:
366 #ifdef HAVE_PKCS12_SUPPORT
370 STACK_OF(X509
) *ca
= NULL
;
373 f
= fopen(cert_file
,"rb");
375 failf(data
, "could not open PKCS12 file '%s'", cert_file
);
378 p12
= d2i_PKCS12_fp(f
, NULL
);
382 failf(data
, "error reading PKCS12 file '%s'", cert_file
);
388 if(!PKCS12_parse(p12
, data
->set
.str
[STRING_KEY_PASSWD
], &pri
, &x509
,
391 "could not parse PKCS12 file, check password, OpenSSL error %s",
392 ERR_error_string(ERR_get_error(), NULL
) );
399 if(SSL_CTX_use_certificate(ctx
, x509
) != 1) {
400 failf(data
, SSL_CLIENT_CERT_ERR
);
406 if(SSL_CTX_use_PrivateKey(ctx
, pri
) != 1) {
407 failf(data
, "unable to use private key from PKCS12 file '%s'",
414 if (!SSL_CTX_check_private_key (ctx
)) {
415 failf(data
, "private key from PKCS12 file '%s' "
416 "does not match certificate in same file", cert_file
);
421 /* Set Certificate Verification chain */
422 if (ca
&& sk_num(ca
)) {
423 for (i
= 0; i
< sk_X509_num(ca
); i
++) {
424 if (!SSL_CTX_add_extra_chain_cert(ctx
,sk_X509_value(ca
, i
))) {
425 failf(data
, "cannot add certificate to certificate chain");
430 if (!SSL_CTX_add_client_CA(ctx
, sk_X509_value(ca
, i
))) {
431 failf(data
, "cannot add certificate to client CA list",
445 failf(data
, "file type P12 for certificate not supported");
450 failf(data
, "not supported file type '%s' for certificate", cert_type
);
454 file_type
= do_file_type(key_type
);
457 case SSL_FILETYPE_PEM
:
461 /* cert & key can only be in PEM case in the same file */
463 case SSL_FILETYPE_ASN1
:
464 if(SSL_CTX_use_PrivateKey_file(ctx
, key_file
, file_type
) != 1) {
465 failf(data
, "unable to set private key file: '%s' type %s",
466 key_file
, key_type
?key_type
:"PEM");
470 case SSL_FILETYPE_ENGINE
:
471 #ifdef HAVE_OPENSSL_ENGINE_H
472 { /* XXXX still needs some work */
473 EVP_PKEY
*priv_key
= NULL
;
474 if(data
->state
.engine
) {
475 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
476 UI_METHOD
*ui_method
= UI_OpenSSL();
478 if(!key_file
|| !key_file
[0]) {
479 failf(data
, "no key set to load from crypto engine");
482 /* the typecast below was added to please mingw32 */
483 priv_key
= (EVP_PKEY
*)
484 ENGINE_load_private_key(data
->state
.engine
,key_file
,
485 #ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
488 data
->set
.str
[STRING_KEY_PASSWD
]);
490 failf(data
, "failed to load private key from crypto engine");
493 if(SSL_CTX_use_PrivateKey(ctx
, priv_key
) != 1) {
494 failf(data
, "unable to set private key");
495 EVP_PKEY_free(priv_key
);
498 EVP_PKEY_free(priv_key
); /* we don't need the handle any more... */
501 failf(data
, "crypto engine not set, can't load private key");
507 failf(data
, "file type ENG for private key not supported");
510 case SSL_FILETYPE_PKCS12
:
512 failf(data
, "file type P12 for private key not supported");
517 failf(data
, "not supported file type for private key");
523 failf(data
,"unable to create an SSL structure");
527 x509
=SSL_get_certificate(ssl
);
529 /* This version was provided by Evan Jordan and is supposed to not
530 leak memory as the previous version: */
532 EVP_PKEY
*pktmp
= X509_get_pubkey(x509
);
533 EVP_PKEY_copy_parameters(pktmp
,SSL_get_privatekey(ssl
));
534 EVP_PKEY_free(pktmp
);
539 /* If we are using DSA, we can copy the parameters from
543 /* Now we know that a key and cert have been set against
545 if(!SSL_CTX_check_private_key(ctx
)) {
546 failf(data
, "Private key does not match the certificate public key");
549 #ifndef HAVE_USERDATA_IN_PWD_CALLBACK
551 memset(global_passwd
, 0, sizeof(global_passwd
));
558 int cert_verify_callback(int ok
, X509_STORE_CTX
*ctx
)
563 err_cert
=X509_STORE_CTX_get_current_cert(ctx
);
564 X509_NAME_oneline(X509_get_subject_name(err_cert
), buf
, sizeof(buf
));
568 /* Return error string for last OpenSSL error
570 static char *SSL_strerror(unsigned long error
, char *buf
, size_t size
)
572 #ifdef HAVE_ERR_ERROR_STRING_N
573 /* OpenSSL 0.9.6 and later has a function named
574 ERRO_error_string_n() that takes the size of the buffer as a
576 ERR_error_string_n(error
, buf
, size
);
579 ERR_error_string(error
, buf
);
584 #endif /* USE_SSLEAY */
590 * @retval 0 error initializing SSL
591 * @retval 1 SSL initialized successfully
593 int Curl_ossl_init(void)
595 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
596 ENGINE_load_builtin_engines();
599 /* Lets get nice error messages */
600 SSL_load_error_strings();
602 /* Setup all the global SSL stuff */
603 if(!SSLeay_add_ssl_algorithms())
609 #endif /* USE_SSLEAY */
614 void Curl_ossl_cleanup(void)
616 /* Free the SSL error strings */
619 /* EVP_cleanup() removes all ciphers and digests from the
623 #ifdef HAVE_ENGINE_cleanup
627 #ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
628 /* this function was not present in 0.9.6b, but was added sometimes
630 CRYPTO_cleanup_all_ex_data();
635 * This function uses SSL_peek to determine connection status.
638 * 1 means the connection is still in place
639 * 0 means the connection has been closed
640 * -1 means the connection status is unknown
642 int Curl_ossl_check_cxn(struct connectdata
*conn
)
647 rc
= SSL_peek(conn
->ssl
[FIRSTSOCKET
].handle
, (void*)&buf
, 1);
649 return 1; /* connection still in place */
652 return 0; /* connection has been closed */
654 return -1; /* connection status unknown */
657 /* Selects an OpenSSL crypto engine
659 CURLcode
Curl_ossl_set_engine(struct SessionHandle
*data
, const char *engine
)
661 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
662 ENGINE
*e
= ENGINE_by_id(engine
);
665 failf(data
, "SSL Engine '%s' not found", engine
);
666 return (CURLE_SSL_ENGINE_NOTFOUND
);
669 if(data
->state
.engine
) {
670 ENGINE_finish(data
->state
.engine
);
671 ENGINE_free(data
->state
.engine
);
672 data
->state
.engine
= NULL
;
674 if(!ENGINE_init(e
)) {
678 failf(data
, "Failed to initialise SSL Engine '%s':\n%s",
679 engine
, SSL_strerror(ERR_get_error(), buf
, sizeof(buf
)));
680 return (CURLE_SSL_ENGINE_INITFAILED
);
682 data
->state
.engine
= e
;
686 failf(data
, "SSL Engine not supported");
687 return (CURLE_SSL_ENGINE_NOTFOUND
);
691 /* Sets engine as default for all SSL operations
693 CURLcode
Curl_ossl_set_engine_default(struct SessionHandle
*data
)
695 #ifdef HAVE_OPENSSL_ENGINE_H
696 if(data
->state
.engine
) {
697 if(ENGINE_set_default(data
->state
.engine
, ENGINE_METHOD_ALL
) > 0) {
698 infof(data
,"set default crypto engine '%s'\n", ENGINE_get_id(data
->state
.engine
));
701 failf(data
, "set default crypto engine '%s' failed", ENGINE_get_id(data
->state
.engine
));
702 return CURLE_SSL_ENGINE_SETFAILED
;
711 /* Return list of OpenSSL crypto engine names.
713 struct curl_slist
*Curl_ossl_engines_list(struct SessionHandle
*data
)
715 struct curl_slist
*list
= NULL
;
716 #if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
717 struct curl_slist
*beg
= NULL
;
720 for (e
= ENGINE_get_first(); e
; e
= ENGINE_get_next(e
)) {
721 list
= curl_slist_append(list
, ENGINE_get_id(e
));
723 curl_slist_free_all(beg
);
726 else if(beg
== NULL
) {
737 * This function is called when an SSL connection is closed.
739 void Curl_ossl_close(struct connectdata
*conn
, int sockindex
)
741 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
743 if(connssl
->handle
) {
744 (void)SSL_shutdown(connssl
->handle
);
745 SSL_set_connect_state(connssl
->handle
);
747 SSL_free (connssl
->handle
);
748 connssl
->handle
= NULL
;
751 SSL_CTX_free (connssl
->ctx
);
757 * This function is called to shut down the SSL layer but keep the
758 * socket open (CCC - Clear Command Channel)
760 int Curl_ossl_shutdown(struct connectdata
*conn
, int sockindex
)
763 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
764 struct SessionHandle
*data
= conn
->data
;
765 char buf
[120]; /* We will use this for the OpenSSL error buffer, so it has
766 to be at least 120 bytes long. */
767 unsigned long sslerror
;
772 /* This has only been tested on the proftpd server, and the mod_tls code
773 sends a close notify alert without waiting for a close notify alert in
774 response. Thus we wait for a close notify alert from the server, but
775 we do not send one. Let's hope other servers do the same... */
777 if(data
->set
.ftp_ccc
== CURLFTPSSL_CCC_ACTIVE
)
778 (void)SSL_shutdown(connssl
->handle
);
780 if(connssl
->handle
) {
782 int what
= Curl_socket_ready(conn
->sock
[sockindex
],
783 CURL_SOCKET_BAD
, SSL_SHUTDOWN_TIMEOUT
);
785 /* Something to read, let's do it and hope that it is the close
786 notify alert from the server */
787 nread
= (ssize_t
)SSL_read(conn
->ssl
[sockindex
].handle
, buf
,
789 err
= SSL_get_error(conn
->ssl
[sockindex
].handle
, (int)nread
);
792 case SSL_ERROR_NONE
: /* this is not an error */
793 case SSL_ERROR_ZERO_RETURN
: /* no more data */
794 /* This is the expected response. There was no data but only
795 the close notify alert */
798 case SSL_ERROR_WANT_READ
:
799 /* there's data pending, re-invoke SSL_read() */
800 infof(data
, "SSL_ERROR_WANT_READ\n");
802 case SSL_ERROR_WANT_WRITE
:
803 /* SSL wants a write. Really odd. Let's bail out. */
804 infof(data
, "SSL_ERROR_WANT_WRITE\n");
808 /* openssl/ssl.h says "look at error stack/return value/errno" */
809 sslerror
= ERR_get_error();
810 failf(conn
->data
, "SSL read: %s, errno %d",
811 ERR_error_string(sslerror
, buf
),
819 failf(data
, "SSL shutdown timeout");
824 /* anything that gets here is fatally bad */
825 failf(data
, "select/poll on SSL socket, errno: %d", SOCKERRNO
);
829 } /* while()-loop for the select() */
831 if(data
->set
.verbose
) {
832 #ifdef HAVE_SSL_GET_SHUTDOWN
833 switch(SSL_get_shutdown(connssl
->handle
)) {
834 case SSL_SENT_SHUTDOWN
:
835 infof(data
, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
837 case SSL_RECEIVED_SHUTDOWN
:
838 infof(data
, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
840 case SSL_SENT_SHUTDOWN
|SSL_RECEIVED_SHUTDOWN
:
841 infof(data
, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
842 "SSL_RECEIVED__SHUTDOWN\n");
848 SSL_free (connssl
->handle
);
849 connssl
->handle
= NULL
;
854 void Curl_ossl_session_free(void *ptr
)
857 SSL_SESSION_free(ptr
);
861 * This function is called when the 'data' struct is going away. Close
862 * down everything and free all resources!
864 int Curl_ossl_close_all(struct SessionHandle
*data
)
867 ERR_remove_state() frees the error queue associated with
868 thread pid. If pid == 0, the current thread will have its
871 Since error queue data structures are allocated
872 automatically for new threads, they must be freed when
873 threads are terminated in oder to avoid memory leaks.
877 #ifdef HAVE_OPENSSL_ENGINE_H
878 if(data
->state
.engine
) {
879 ENGINE_finish(data
->state
.engine
);
880 ENGINE_free(data
->state
.engine
);
881 data
->state
.engine
= NULL
;
889 static int asn1_output(struct connectdata
*conn
,
891 const ASN1_UTCTIME
*tm
)
893 const char *asn1_string
;
896 int year
=0,month
=0,day
=0,hour
=0,minute
=0,second
=0;
897 struct SessionHandle
*data
= conn
->data
;
899 #ifdef CURL_DISABLE_VERBOSE_STRINGS
903 if(!data
->set
.verbose
)
907 asn1_string
=(const char *)tm
->data
;
911 if(asn1_string
[i
-1] == 'Z')
914 if((asn1_string
[i
] > '9') || (asn1_string
[i
] < '0'))
917 year
= (asn1_string
[0]-'0')*10+(asn1_string
[1]-'0');
921 month
= (asn1_string
[2]-'0')*10+(asn1_string
[3]-'0');
922 if((month
> 12) || (month
< 1))
925 day
= (asn1_string
[4]-'0')*10+(asn1_string
[5]-'0');
926 hour
= (asn1_string
[6]-'0')*10+(asn1_string
[7]-'0');
927 minute
= (asn1_string
[8]-'0')*10+(asn1_string
[9]-'0');
929 if((asn1_string
[10] >= '0') && (asn1_string
[10] <= '9') &&
930 (asn1_string
[11] >= '0') && (asn1_string
[11] <= '9'))
931 second
= (asn1_string
[10]-'0')*10+(asn1_string
[11]-'0');
934 "%s%04d-%02d-%02d %02d:%02d:%02d %s\n",
935 prefix
, year
+1900, month
, day
, hour
, minute
, second
, (gmt
?"GMT":""));
940 /* ====================================================== */
943 * Match a hostname against a wildcard pattern.
945 * "foo.host.com" matches "*.host.com".
947 * We are a bit more liberal than RFC2818 describes in that we
948 * accept multiple "*" in pattern (similar to what some other browsers do).
950 * "abc.def.domain.com" should strickly not match "*.domain.com", but we
951 * don't consider "." to be important in CERT checking.
953 #define HOST_NOMATCH 0
956 static int hostmatch(const char *hostname
, const char *pattern
)
962 return (*hostname
? HOST_NOMATCH
: HOST_MATCH
);
966 if(c
== '\0') /* "*\0" matches anything remaining */
970 /* The only recursive function in libcurl! */
971 if(hostmatch(hostname
++,pattern
) == HOST_MATCH
)
977 if(toupper(c
) != toupper(*hostname
++))
984 cert_hostcheck(const char *match_pattern
, const char *hostname
)
986 if(!match_pattern
|| !*match_pattern
||
987 !hostname
|| !*hostname
) /* sanity check */
990 if(curl_strequal(hostname
,match_pattern
)) /* trivial case */
993 if(hostmatch(hostname
,match_pattern
) == HOST_MATCH
)
998 /* Quote from RFC2818 section 3.1 "Server Identity"
1000 If a subjectAltName extension of type dNSName is present, that MUST
1001 be used as the identity. Otherwise, the (most specific) Common Name
1002 field in the Subject field of the certificate MUST be used. Although
1003 the use of the Common Name is existing practice, it is deprecated and
1004 Certification Authorities are encouraged to use the dNSName instead.
1006 Matching is performed using the matching rules specified by
1007 [RFC2459]. If more than one identity of a given type is present in
1008 the certificate (e.g., more than one dNSName name, a match in any one
1009 of the set is considered acceptable.) Names may contain the wildcard
1010 character * which is considered to match any single domain name
1011 component or component fragment. E.g., *.a.com matches foo.a.com but
1012 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1014 In some cases, the URI is specified as an IP address rather than a
1015 hostname. In this case, the iPAddress subjectAltName must be present
1016 in the certificate and must exactly match the IP in the URI.
1019 static CURLcode
verifyhost(struct connectdata
*conn
,
1022 bool matched
= FALSE
; /* no alternative match yet */
1023 int target
= GEN_DNS
; /* target type, GEN_DNS or GEN_IPADD */
1025 struct SessionHandle
*data
= conn
->data
;
1026 STACK_OF(GENERAL_NAME
) *altnames
;
1028 struct in6_addr addr
;
1030 struct in_addr addr
;
1032 CURLcode res
= CURLE_OK
;
1035 if(conn
->bits
.ipv6_ip
&&
1036 Curl_inet_pton(AF_INET6
, conn
->host
.name
, &addr
)) {
1038 addrlen
= sizeof(struct in6_addr
);
1042 if(Curl_inet_pton(AF_INET
, conn
->host
.name
, &addr
)) {
1044 addrlen
= sizeof(struct in_addr
);
1047 /* get a "list" of alternative names */
1048 altnames
= X509_get_ext_d2i(server_cert
, NID_subject_alt_name
, NULL
, NULL
);
1054 /* get amount of alternatives, RFC2459 claims there MUST be at least
1055 one, but we don't depend on it... */
1056 numalts
= sk_GENERAL_NAME_num(altnames
);
1058 /* loop through all alternatives while none has matched */
1059 for (i
=0; (i
<numalts
) && !matched
; i
++) {
1060 /* get a handle to alternative name number i */
1061 const GENERAL_NAME
*check
= sk_GENERAL_NAME_value(altnames
, i
);
1063 /* only check alternatives of the same type the target is */
1064 if(check
->type
== target
) {
1065 /* get data and length */
1066 const char *altptr
= (char *)ASN1_STRING_data(check
->d
.ia5
);
1070 case GEN_DNS
: /* name/pattern comparison */
1071 /* The OpenSSL man page explicitly says: "In general it cannot be
1072 assumed that the data returned by ASN1_STRING_data() is null
1073 terminated or does not contain embedded nulls." But also that
1074 "The actual format of the data will depend on the actual string
1075 type itself: for example for and IA5String the data will be ASCII"
1077 Gisle researched the OpenSSL sources:
1078 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1079 it always 0-terminates an IA5String."
1081 if(cert_hostcheck(altptr
, conn
->host
.name
))
1085 case GEN_IPADD
: /* IP address comparison */
1086 /* compare alternative IP address if the data chunk is the same size
1087 our server IP address is */
1088 altlen
= ASN1_STRING_length(check
->d
.ia5
);
1089 if((altlen
== addrlen
) && !memcmp(altptr
, &addr
, altlen
))
1095 GENERAL_NAMES_free(altnames
);
1099 /* an alternative name matched the server hostname */
1100 infof(data
, "\t subjectAltName: %s matched\n", conn
->host
.dispname
);
1102 /* we have to look to the last occurence of a commonName in the
1103 distinguished one to get the most significant one. */
1106 /* The following is done because of a bug in 0.9.6b */
1108 unsigned char *nulstr
= (unsigned char *)"";
1109 unsigned char *peer_CN
= nulstr
;
1111 X509_NAME
*name
= X509_get_subject_name(server_cert
) ;
1113 while((j
=X509_NAME_get_index_by_NID(name
,NID_commonName
,i
))>=0)
1116 /* we have the name entry and we will now convert this to a string
1117 that we can use for comparison. Doing this we support BMPstring,
1121 ASN1_STRING
*tmp
= X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name
,i
));
1123 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1124 is already UTF-8 encoded. We check for this case and copy the raw
1125 string manually to avoid the problem. This code can be made
1126 conditional in the future when OpenSSL has been fixed. Work-around
1127 brought by Alexis S. L. Carvalho. */
1128 if(tmp
&& ASN1_STRING_type(tmp
) == V_ASN1_UTF8STRING
) {
1129 j
= ASN1_STRING_length(tmp
);
1131 peer_CN
= OPENSSL_malloc(j
+1);
1133 memcpy(peer_CN
, ASN1_STRING_data(tmp
), j
);
1138 else /* not a UTF8 name */
1139 j
= ASN1_STRING_to_UTF8(&peer_CN
, tmp
);
1142 if(peer_CN
== nulstr
)
1144 #ifdef CURL_DOES_CONVERSIONS
1146 /* convert peer_CN from UTF8 */
1148 rc
= Curl_convert_from_utf8(data
, peer_CN
, strlen(peer_CN
));
1149 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1150 if(rc
!= CURLE_OK
) {
1151 OPENSSL_free(peer_CN
);
1155 #endif /* CURL_DOES_CONVERSIONS */
1159 "SSL: unable to obtain common name from peer certificate");
1160 return CURLE_PEER_FAILED_VERIFICATION
;
1162 else if(!cert_hostcheck((const char *)peer_CN
, conn
->host
.name
)) {
1163 if(data
->set
.ssl
.verifyhost
> 1) {
1164 failf(data
, "SSL: certificate subject name '%s' does not match "
1165 "target host name '%s'", peer_CN
, conn
->host
.dispname
);
1166 res
= CURLE_PEER_FAILED_VERIFICATION
;
1169 infof(data
, "\t common name: %s (does not match '%s')\n",
1170 peer_CN
, conn
->host
.dispname
);
1173 infof(data
, "\t common name: %s (matched)\n", peer_CN
);
1176 OPENSSL_free(peer_CN
);
1180 #endif /* USE_SSLEAY */
1182 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1183 and thus this cannot be done there. */
1184 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1186 static const char *ssl_msg_type(int ssl_ver
, int msg
)
1188 if(ssl_ver
== SSL2_VERSION_MAJOR
) {
1192 case SSL2_MT_CLIENT_HELLO
:
1193 return "Client hello";
1194 case SSL2_MT_CLIENT_MASTER_KEY
:
1195 return "Client key";
1196 case SSL2_MT_CLIENT_FINISHED
:
1197 return "Client finished";
1198 case SSL2_MT_SERVER_HELLO
:
1199 return "Server hello";
1200 case SSL2_MT_SERVER_VERIFY
:
1201 return "Server verify";
1202 case SSL2_MT_SERVER_FINISHED
:
1203 return "Server finished";
1204 case SSL2_MT_REQUEST_CERTIFICATE
:
1205 return "Request CERT";
1206 case SSL2_MT_CLIENT_CERTIFICATE
:
1207 return "Client CERT";
1210 else if(ssl_ver
== SSL3_VERSION_MAJOR
) {
1212 case SSL3_MT_HELLO_REQUEST
:
1213 return "Hello request";
1214 case SSL3_MT_CLIENT_HELLO
:
1215 return "Client hello";
1216 case SSL3_MT_SERVER_HELLO
:
1217 return "Server hello";
1218 case SSL3_MT_CERTIFICATE
:
1220 case SSL3_MT_SERVER_KEY_EXCHANGE
:
1221 return "Server key exchange";
1222 case SSL3_MT_CLIENT_KEY_EXCHANGE
:
1223 return "Client key exchange";
1224 case SSL3_MT_CERTIFICATE_REQUEST
:
1225 return "Request CERT";
1226 case SSL3_MT_SERVER_DONE
:
1227 return "Server finished";
1228 case SSL3_MT_CERTIFICATE_VERIFY
:
1229 return "CERT verify";
1230 case SSL3_MT_FINISHED
:
1237 static const char *tls_rt_type(int type
)
1240 type
== SSL3_RT_CHANGE_CIPHER_SPEC
? "TLS change cipher, " :
1241 type
== SSL3_RT_ALERT
? "TLS alert, " :
1242 type
== SSL3_RT_HANDSHAKE
? "TLS handshake, " :
1243 type
== SSL3_RT_APPLICATION_DATA
? "TLS app data, " :
1249 * Our callback from the SSL/TLS layers.
1251 static void ssl_tls_trace(int direction
, int ssl_ver
, int content_type
,
1252 const void *buf
, size_t len
, const SSL
*ssl
,
1253 struct connectdata
*conn
)
1255 struct SessionHandle
*data
;
1256 const char *msg_name
, *tls_rt_name
;
1258 int ver
, msg_type
, txt_len
;
1260 if(!conn
|| !conn
->data
|| !conn
->data
->set
.fdebug
||
1261 (direction
!= 0 && direction
!= 1))
1266 ver
= (ssl_ver
== SSL2_VERSION_MAJOR
? '2' :
1267 ssl_ver
== SSL3_VERSION_MAJOR
? '3' : '?');
1269 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1270 * always pass-up content-type as 0. But the interesting message-type
1273 if(ssl_ver
== SSL3_VERSION_MAJOR
&& content_type
!= 0)
1274 tls_rt_name
= tls_rt_type(content_type
);
1278 msg_type
= *(char*)buf
;
1279 msg_name
= ssl_msg_type(ssl_ver
, msg_type
);
1281 txt_len
= snprintf(ssl_buf
, sizeof(ssl_buf
), "SSLv%c, %s%s (%d):\n",
1282 ver
, tls_rt_name
, msg_name
, msg_type
);
1283 Curl_debug(data
, CURLINFO_TEXT
, ssl_buf
, (size_t)txt_len
, NULL
);
1285 Curl_debug(data
, (direction
== 1) ? CURLINFO_SSL_DATA_OUT
:
1286 CURLINFO_SSL_DATA_IN
, (char *)buf
, len
, NULL
);
1292 /* ====================================================== */
1295 ossl_connect_step1(struct connectdata
*conn
,
1298 CURLcode retcode
= CURLE_OK
;
1300 struct SessionHandle
*data
= conn
->data
;
1301 SSL_METHOD_QUAL SSL_METHOD
*req_method
=NULL
;
1302 void *ssl_sessionid
=NULL
;
1303 X509_LOOKUP
*lookup
=NULL
;
1304 curl_socket_t sockfd
= conn
->sock
[sockindex
];
1305 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
1306 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1308 struct in6_addr addr
;
1310 struct in_addr addr
;
1314 DEBUGASSERT(ssl_connect_1
== connssl
->connecting_state
);
1316 /* Make funny stuff to get random input */
1317 Curl_ossl_seed(data
);
1319 /* check to see if we've been told to use an explicit SSL/TLS version */
1320 switch(data
->set
.ssl
.version
) {
1322 case CURL_SSLVERSION_DEFAULT
:
1323 /* we try to figure out version */
1324 req_method
= SSLv23_client_method();
1326 case CURL_SSLVERSION_TLSv1
:
1327 req_method
= TLSv1_client_method();
1329 case CURL_SSLVERSION_SSLv2
:
1330 req_method
= SSLv2_client_method();
1332 case CURL_SSLVERSION_SSLv3
:
1333 req_method
= SSLv3_client_method();
1338 SSL_CTX_free(connssl
->ctx
);
1339 connssl
->ctx
= SSL_CTX_new(req_method
);
1342 failf(data
, "SSL: couldn't create a context!");
1343 return CURLE_OUT_OF_MEMORY
;
1346 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1347 if(data
->set
.fdebug
&& data
->set
.verbose
) {
1348 /* the SSL trace callback is only used for verbose logging so we only
1349 inform about failures of setting it */
1350 if(!SSL_CTX_callback_ctrl(connssl
->ctx
, SSL_CTRL_SET_MSG_CALLBACK
,
1351 (void (*)(void))ssl_tls_trace
)) {
1352 infof(data
, "SSL: couldn't set callback!\n");
1354 else if(!SSL_CTX_ctrl(connssl
->ctx
, SSL_CTRL_SET_MSG_CALLBACK_ARG
, 0,
1356 infof(data
, "SSL: couldn't set callback argument!\n");
1361 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1362 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1363 work-arounds. The man page for this option states that SSL_OP_ALL enables
1364 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1365 enable the bug workaround options if compatibility with somewhat broken
1366 implementations is desired."
1369 SSL_CTX_set_options(connssl
->ctx
, SSL_OP_ALL
);
1371 /* disable SSLv2 in the default case (i.e. allow SSLv3 and TLSv1) */
1372 if(data
->set
.ssl
.version
== CURL_SSLVERSION_DEFAULT
)
1373 SSL_CTX_set_options(connssl
->ctx
, SSL_OP_NO_SSLv2
);
1377 * Not sure it's needed to tell SSL_connect() that socket is
1378 * non-blocking. It doesn't seem to care, but just return with
1381 if(data
->state
.used_interface
== Curl_if_multi
)
1382 SSL_CTX_ctrl(connssl
->ctx
, BIO_C_SET_NBIO
, 1, NULL
);
1385 if(data
->set
.str
[STRING_CERT
]) {
1386 if(!cert_stuff(conn
,
1388 data
->set
.str
[STRING_CERT
],
1389 data
->set
.str
[STRING_CERT_TYPE
],
1390 data
->set
.str
[STRING_KEY
],
1391 data
->set
.str
[STRING_KEY_TYPE
])) {
1392 /* failf() is already done in cert_stuff() */
1393 return CURLE_SSL_CERTPROBLEM
;
1397 if(data
->set
.str
[STRING_SSL_CIPHER_LIST
]) {
1398 if(!SSL_CTX_set_cipher_list(connssl
->ctx
,
1399 data
->set
.str
[STRING_SSL_CIPHER_LIST
])) {
1400 failf(data
, "failed setting cipher list");
1401 return CURLE_SSL_CIPHER
;
1405 if(data
->set
.str
[STRING_SSL_CAFILE
] || data
->set
.str
[STRING_SSL_CAPATH
]) {
1406 /* tell SSL where to find CA certificates that are used to verify
1407 the servers certificate. */
1408 if(!SSL_CTX_load_verify_locations(connssl
->ctx
,
1409 data
->set
.str
[STRING_SSL_CAFILE
],
1410 data
->set
.str
[STRING_SSL_CAPATH
])) {
1411 if(data
->set
.ssl
.verifypeer
) {
1412 /* Fail if we insist on successfully verifying the server. */
1413 failf(data
,"error setting certificate verify locations:\n"
1414 " CAfile: %s\n CApath: %s\n",
1415 data
->set
.str
[STRING_SSL_CAFILE
]?
1416 data
->set
.str
[STRING_SSL_CAFILE
]: "none",
1417 data
->set
.str
[STRING_SSL_CAPATH
]?
1418 data
->set
.str
[STRING_SSL_CAPATH
] : "none");
1419 return CURLE_SSL_CACERT_BADFILE
;
1422 /* Just continue with a warning if no strict certificate verification
1424 infof(data
, "error setting certificate verify locations,"
1425 " continuing anyway:\n");
1429 /* Everything is fine. */
1430 infof(data
, "successfully set certificate verify locations:\n");
1435 data
->set
.str
[STRING_SSL_CAFILE
] ? data
->set
.str
[STRING_SSL_CAFILE
]:
1437 data
->set
.str
[STRING_SSL_CAPATH
] ? data
->set
.str
[STRING_SSL_CAPATH
]:
1441 if (data
->set
.str
[STRING_SSL_CRLFILE
]) {
1442 /* tell SSL where to find CRL file that is used to check certificate
1444 lookup
=X509_STORE_add_lookup(connssl
->ctx
->cert_store
,X509_LOOKUP_file());
1446 (X509_load_crl_file(lookup
,data
->set
.str
[STRING_SSL_CRLFILE
],
1447 X509_FILETYPE_PEM
)!=1) ) {
1448 failf(data
,"error loading CRL file :\n"
1450 data
->set
.str
[STRING_SSL_CRLFILE
]?
1451 data
->set
.str
[STRING_SSL_CRLFILE
]: "none");
1452 return CURLE_SSL_CRL_BADFILE
;
1455 /* Everything is fine. */
1456 infof(data
, "successfully load CRL file:\n");
1457 X509_STORE_set_flags(connssl
->ctx
->cert_store
,
1458 X509_V_FLAG_CRL_CHECK
|X509_V_FLAG_CRL_CHECK_ALL
);
1461 " CRLfile: %s\n", data
->set
.str
[STRING_SSL_CRLFILE
] ?
1462 data
->set
.str
[STRING_SSL_CRLFILE
]: "none");
1465 /* SSL always tries to verify the peer, this only says whether it should
1466 * fail to connect if the verification fails, or if it should continue
1467 * anyway. In the latter case the result of the verification is checked with
1468 * SSL_get_verify_result() below. */
1469 SSL_CTX_set_verify(connssl
->ctx
,
1470 data
->set
.ssl
.verifypeer
?SSL_VERIFY_PEER
:SSL_VERIFY_NONE
,
1471 cert_verify_callback
);
1473 /* give application a chance to interfere with SSL set up. */
1474 if(data
->set
.ssl
.fsslctx
) {
1475 retcode
= (*data
->set
.ssl
.fsslctx
)(data
, connssl
->ctx
,
1476 data
->set
.ssl
.fsslctxp
);
1478 failf(data
,"error signaled by ssl ctx callback");
1483 /* Lets make an SSL structure */
1485 SSL_free(connssl
->handle
);
1486 connssl
->handle
= SSL_new(connssl
->ctx
);
1487 if(!connssl
->handle
) {
1488 failf(data
, "SSL: couldn't create a context (handle)!");
1489 return CURLE_OUT_OF_MEMORY
;
1491 SSL_set_connect_state(connssl
->handle
);
1493 connssl
->server_cert
= 0x0;
1495 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1496 if ((0 == Curl_inet_pton(AF_INET
, conn
->host
.name
, &addr
)) &&
1498 (0 == Curl_inet_pton(AF_INET6
, conn
->host
.name
, &addr
)) &&
1500 !SSL_set_tlsext_host_name(connssl
->handle
, conn
->host
.name
))
1501 infof(data
, "WARNING: failed to configure server name indication (SNI) "
1505 /* Check if there's a cached ID we can/should use here! */
1506 if(!Curl_ssl_getsessionid(conn
, &ssl_sessionid
, NULL
)) {
1507 /* we got a session id, use it! */
1508 if(!SSL_set_session(connssl
->handle
, ssl_sessionid
)) {
1509 failf(data
, "SSL: SSL_set_session failed: %s",
1510 ERR_error_string(ERR_get_error(),NULL
));
1511 return CURLE_SSL_CONNECT_ERROR
;
1513 /* Informational message */
1514 infof (data
, "SSL re-using session ID\n");
1517 /* pass the raw socket into the SSL layers */
1518 if(!SSL_set_fd(connssl
->handle
, sockfd
)) {
1519 failf(data
, "SSL: SSL_set_fd failed: %s",
1520 ERR_error_string(ERR_get_error(),NULL
));
1521 return CURLE_SSL_CONNECT_ERROR
;
1524 connssl
->connecting_state
= ssl_connect_2
;
1529 ossl_connect_step2(struct connectdata
*conn
, int sockindex
)
1531 struct SessionHandle
*data
= conn
->data
;
1533 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
1535 DEBUGASSERT(ssl_connect_2
== connssl
->connecting_state
1536 || ssl_connect_2_reading
== connssl
->connecting_state
1537 || ssl_connect_2_writing
== connssl
->connecting_state
);
1539 err
= SSL_connect(connssl
->handle
);
1542 0 is "not successful but was shut down controlled"
1543 <0 is "handshake was not successful, because a fatal error occurred" */
1545 int detail
= SSL_get_error(connssl
->handle
, err
);
1547 if(SSL_ERROR_WANT_READ
== detail
) {
1548 connssl
->connecting_state
= ssl_connect_2_reading
;
1551 else if(SSL_ERROR_WANT_WRITE
== detail
) {
1552 connssl
->connecting_state
= ssl_connect_2_writing
;
1556 /* untreated error */
1557 unsigned long errdetail
;
1558 char error_buffer
[256]; /* OpenSSL documents that this must be at least
1561 const char *cert_problem
= NULL
;
1563 connssl
->connecting_state
= ssl_connect_2
; /* the connection failed,
1564 we're not waiting for
1567 errdetail
= ERR_get_error(); /* Gets the earliest error code from the
1568 thread's error queue and removes the
1575 SSL2_SET_CERTIFICATE:
1576 certificate verify failed */
1581 SSL3_GET_SERVER_CERTIFICATE:
1582 certificate verify failed */
1583 cert_problem
= "SSL certificate problem, verify that the CA cert is"
1585 rc
= CURLE_SSL_CACERT
;
1588 rc
= CURLE_SSL_CONNECT_ERROR
;
1592 /* detail is already set to the SSL error above */
1594 /* If we e.g. use SSLv2 request-method and the server doesn't like us
1595 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
1596 * the SO_ERROR is also lost.
1598 if(CURLE_SSL_CONNECT_ERROR
== rc
&& errdetail
== 0) {
1599 failf(data
, "Unknown SSL protocol error in connection to %s:%d ",
1600 conn
->host
.name
, conn
->port
);
1603 /* Could be a CERT problem */
1605 SSL_strerror(errdetail
, error_buffer
, sizeof(error_buffer
));
1606 failf(data
, "%s%s", cert_problem
? cert_problem
: "", error_buffer
);
1611 /* we have been connected fine, we're not waiting for anything else. */
1612 connssl
->connecting_state
= ssl_connect_3
;
1614 /* Informational message */
1615 infof (data
, "SSL connection using %s\n",
1616 SSL_get_cipher(connssl
->handle
));
1623 * Get the server cert, verify it and show it etc, only call failf() if the
1624 * 'strict' argument is TRUE as otherwise all this is for informational
1627 * We check certificates to authenticate the server; otherwise we risk
1628 * man-in-the-middle attack.
1630 static CURLcode
servercert(struct connectdata
*conn
,
1631 struct ssl_connect_data
*connssl
,
1634 CURLcode retcode
= CURLE_OK
;
1637 ASN1_TIME
*certdate
;
1638 struct SessionHandle
*data
= conn
->data
;
1642 data
->set
.ssl
.certverifyresult
= !X509_V_OK
;
1644 connssl
->server_cert
= SSL_get_peer_certificate(connssl
->handle
);
1645 if(!connssl
->server_cert
) {
1647 failf(data
, "SSL: couldn't get peer certificate!");
1648 return CURLE_PEER_FAILED_VERIFICATION
;
1650 infof (data
, "Server certificate:\n");
1652 str
= X509_NAME_oneline(X509_get_subject_name(connssl
->server_cert
),
1656 failf(data
, "SSL: couldn't get X509-subject!");
1657 X509_free(connssl
->server_cert
);
1658 connssl
->server_cert
= NULL
;
1659 return CURLE_SSL_CONNECT_ERROR
;
1661 infof(data
, "\t subject: %s\n", str
);
1664 certdate
= X509_get_notBefore(connssl
->server_cert
);
1665 asn1_output(conn
, "\t start date: ", certdate
);
1667 certdate
= X509_get_notAfter(connssl
->server_cert
);
1668 asn1_output(conn
, "\t expire date: ", certdate
);
1670 if(data
->set
.ssl
.verifyhost
) {
1671 retcode
= verifyhost(conn
, connssl
->server_cert
);
1673 X509_free(connssl
->server_cert
);
1674 connssl
->server_cert
= NULL
;
1679 str
= X509_NAME_oneline(X509_get_issuer_name(connssl
->server_cert
),
1683 failf(data
, "SSL: couldn't get X509-issuer name!");
1684 retcode
= CURLE_SSL_CONNECT_ERROR
;
1687 infof(data
, "\t issuer: %s\n", str
);
1690 /* We could do all sorts of certificate verification stuff here before
1691 deallocating the certificate. */
1693 /* e.g. match issuer name with provided issuer certificate */
1694 if (data
->set
.str
[STRING_SSL_ISSUERCERT
]) {
1695 if (! (fp
=fopen(data
->set
.str
[STRING_SSL_ISSUERCERT
],"r"))) {
1697 failf(data
, "SSL: Unable to open issuer cert (%s)\n",
1698 data
->set
.str
[STRING_SSL_ISSUERCERT
]);
1699 X509_free(connssl
->server_cert
);
1700 connssl
->server_cert
= NULL
;
1701 return CURLE_SSL_ISSUER_ERROR
;
1703 issuer
= PEM_read_X509(fp
,NULL
,ZERO_NULL
,NULL
);
1706 failf(data
, "SSL: Unable to read issuer cert (%s)\n",
1707 data
->set
.str
[STRING_SSL_ISSUERCERT
]);
1708 X509_free(connssl
->server_cert
);
1711 return CURLE_SSL_ISSUER_ERROR
;
1714 if (X509_check_issued(issuer
,connssl
->server_cert
) != X509_V_OK
) {
1716 failf(data
, "SSL: Certificate issuer check failed (%s)\n",
1717 data
->set
.str
[STRING_SSL_ISSUERCERT
]);
1718 X509_free(connssl
->server_cert
);
1720 connssl
->server_cert
= NULL
;
1721 return CURLE_SSL_ISSUER_ERROR
;
1723 infof(data
, "\t SSL certificate issuer check ok (%s)\n",
1724 data
->set
.str
[STRING_SSL_ISSUERCERT
]);
1728 lerr
= data
->set
.ssl
.certverifyresult
=
1729 SSL_get_verify_result(connssl
->handle
);
1730 if(data
->set
.ssl
.certverifyresult
!= X509_V_OK
) {
1731 if(data
->set
.ssl
.verifypeer
) {
1732 /* We probably never reach this, because SSL_connect() will fail
1733 and we return earlier if verifypeer is set? */
1735 failf(data
, "SSL certificate verify result: %s (%ld)",
1736 X509_verify_cert_error_string(lerr
), lerr
);
1737 retcode
= CURLE_PEER_FAILED_VERIFICATION
;
1740 infof(data
, "\t SSL certificate verify result: %s (%ld),"
1741 " continuing anyway.\n",
1742 X509_verify_cert_error_string(lerr
), lerr
);
1745 infof(data
, "\t SSL certificate verify ok.\n");
1748 X509_free(connssl
->server_cert
);
1749 connssl
->server_cert
= NULL
;
1750 connssl
->connecting_state
= ssl_connect_done
;
1757 ossl_connect_step3(struct connectdata
*conn
,
1760 CURLcode retcode
= CURLE_OK
;
1761 void *ssl_sessionid
=NULL
;
1762 struct SessionHandle
*data
= conn
->data
;
1763 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
1765 DEBUGASSERT(ssl_connect_3
== connssl
->connecting_state
);
1767 if(Curl_ssl_getsessionid(conn
, &ssl_sessionid
, NULL
)) {
1768 /* Since this is not a cached session ID, then we want to stach this one
1770 SSL_SESSION
*our_ssl_sessionid
;
1771 #ifdef HAVE_SSL_GET1_SESSION
1772 our_ssl_sessionid
= SSL_get1_session(connssl
->handle
);
1774 /* SSL_get1_session() will increment the reference
1775 count and the session will stay in memory until explicitly freed with
1776 SSL_SESSION_free(3), regardless of its state.
1777 This function was introduced in openssl 0.9.5a. */
1779 our_ssl_sessionid
= SSL_get_session(connssl
->handle
);
1781 /* if SSL_get1_session() is unavailable, use SSL_get_session().
1782 This is an inferior option because the session can be flushed
1783 at any time by openssl. It is included only so curl compiles
1784 under versions of openssl < 0.9.5a.
1786 WARNING: How curl behaves if it's session is flushed is
1790 retcode
= Curl_ssl_addsessionid(conn
, our_ssl_sessionid
,
1791 0 /* unknown size */);
1793 failf(data
, "failed to store ssl session");
1800 * We check certificates to authenticate the server; otherwise we risk
1801 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
1802 * verify the peer ignore faults and failures from the server cert
1806 if(!data
->set
.ssl
.verifypeer
)
1807 (void)servercert(conn
, connssl
, FALSE
);
1809 retcode
= servercert(conn
, connssl
, TRUE
);
1811 if(CURLE_OK
== retcode
)
1812 connssl
->connecting_state
= ssl_connect_done
;
1817 ossl_connect_common(struct connectdata
*conn
,
1823 struct SessionHandle
*data
= conn
->data
;
1824 struct ssl_connect_data
*connssl
= &conn
->ssl
[sockindex
];
1825 curl_socket_t sockfd
= conn
->sock
[sockindex
];
1828 if(ssl_connect_1
==connssl
->connecting_state
) {
1829 /* Find out how much more time we're allowed */
1830 timeout_ms
= Curl_timeleft(conn
, NULL
, TRUE
);
1832 if(timeout_ms
< 0) {
1833 /* no need to continue if time already is up */
1834 failf(data
, "SSL connection timeout");
1835 return CURLE_OPERATION_TIMEDOUT
;
1837 retcode
= ossl_connect_step1(conn
, sockindex
);
1843 while(ssl_connect_2
== connssl
->connecting_state
||
1844 ssl_connect_2_reading
== connssl
->connecting_state
||
1845 ssl_connect_2_writing
== connssl
->connecting_state
) {
1847 /* check allowed time left */
1848 timeout_ms
= Curl_timeleft(conn
, NULL
, TRUE
);
1850 if(timeout_ms
< 0) {
1851 /* no need to continue if time already is up */
1852 failf(data
, "SSL connection timeout");
1853 return CURLE_OPERATION_TIMEDOUT
;
1856 /* if ssl is expecting something, check if it's available. */
1857 if(connssl
->connecting_state
== ssl_connect_2_reading
1858 || connssl
->connecting_state
== ssl_connect_2_writing
) {
1860 int writefd
= ssl_connect_2_writing
==
1861 connssl
->connecting_state
?sockfd
:CURL_SOCKET_BAD
;
1862 int readfd
= ssl_connect_2_reading
==
1863 connssl
->connecting_state
?sockfd
:CURL_SOCKET_BAD
;
1866 int what
= Curl_socket_ready(readfd
, writefd
,
1867 nonblocking
?0:(int)timeout_ms
);
1869 /* readable or writable, go loop in the outer loop */
1871 else if(0 == what
) {
1878 failf(data
, "SSL connection timeout");
1879 return CURLE_OPERATION_TIMEDOUT
;
1883 /* anything that gets here is fatally bad */
1884 failf(data
, "select/poll on SSL socket, errno: %d", SOCKERRNO
);
1885 return CURLE_SSL_CONNECT_ERROR
;
1887 } /* while()-loop for the select() */
1890 /* get the timeout from step2 to avoid computing it twice. */
1891 retcode
= ossl_connect_step2(conn
, sockindex
);
1895 } /* repeat step2 until all transactions are done. */
1898 if(ssl_connect_3
==connssl
->connecting_state
) {
1899 retcode
= ossl_connect_step3(conn
, sockindex
);
1904 if(ssl_connect_done
==connssl
->connecting_state
) {
1905 connssl
->state
= ssl_connection_complete
;
1911 /* Reset our connect state machine */
1912 connssl
->connecting_state
= ssl_connect_1
;
1918 Curl_ossl_connect_nonblocking(struct connectdata
*conn
,
1922 return ossl_connect_common(conn
, sockindex
, TRUE
, done
);
1926 Curl_ossl_connect(struct connectdata
*conn
,
1932 retcode
= ossl_connect_common(conn
, sockindex
, FALSE
, &done
);
1941 bool Curl_ossl_data_pending(const struct connectdata
*conn
,
1944 if(conn
->ssl
[connindex
].handle
)
1946 return (bool)(0 != SSL_pending(conn
->ssl
[connindex
].handle
));
1951 /* return number of sent (non-SSL) bytes */
1952 ssize_t
Curl_ossl_send(struct connectdata
*conn
,
1957 /* SSL_write() is said to return 'int' while write() and send() returns
1960 char error_buffer
[120]; /* OpenSSL documents that this must be at least 120
1962 unsigned long sslerror
;
1963 int rc
= SSL_write(conn
->ssl
[sockindex
].handle
, mem
, (int)len
);
1966 err
= SSL_get_error(conn
->ssl
[sockindex
].handle
, rc
);
1969 case SSL_ERROR_WANT_READ
:
1970 case SSL_ERROR_WANT_WRITE
:
1971 /* The operation did not complete; the same TLS/SSL I/O function
1972 should be called again later. This is basicly an EWOULDBLOCK
1975 case SSL_ERROR_SYSCALL
:
1976 failf(conn
->data
, "SSL_write() returned SYSCALL, errno = %d",
1980 /* A failure in the SSL library occurred, usually a protocol error.
1981 The OpenSSL error queue contains more information on the error. */
1982 sslerror
= ERR_get_error();
1983 failf(conn
->data
, "SSL_write() error: %s",
1984 ERR_error_string(sslerror
, error_buffer
));
1988 failf(conn
->data
, "SSL_write() return error %d", err
);
1991 return (ssize_t
)rc
; /* number of bytes */
1995 * If the read would block we return -1 and set 'wouldblock' to TRUE.
1996 * Otherwise we return the amount of data read. Other errors should return -1
1997 * and set 'wouldblock' to FALSE.
1999 ssize_t
Curl_ossl_recv(struct connectdata
*conn
, /* connection data */
2000 int num
, /* socketindex */
2001 char *buf
, /* store read data here */
2002 size_t buffersize
, /* max amount to read */
2005 char error_buffer
[120]; /* OpenSSL documents that this must be at
2006 least 120 bytes long. */
2007 unsigned long sslerror
;
2008 ssize_t nread
= (ssize_t
)SSL_read(conn
->ssl
[num
].handle
, buf
,
2010 *wouldblock
= FALSE
;
2012 /* failed SSL_read */
2013 int err
= SSL_get_error(conn
->ssl
[num
].handle
, (int)nread
);
2016 case SSL_ERROR_NONE
: /* this is not an error */
2017 case SSL_ERROR_ZERO_RETURN
: /* no more data */
2019 case SSL_ERROR_WANT_READ
:
2020 case SSL_ERROR_WANT_WRITE
:
2021 /* there's data pending, re-invoke SSL_read() */
2023 return -1; /* basically EWOULDBLOCK */
2025 /* openssl/ssl.h says "look at error stack/return value/errno" */
2026 sslerror
= ERR_get_error();
2027 failf(conn
->data
, "SSL read: %s, errno %d",
2028 ERR_error_string(sslerror
, error_buffer
),
2036 size_t Curl_ossl_version(char *buffer
, size_t size
)
2038 #ifdef YASSL_VERSION
2039 /* yassl provides an OpenSSL API compatiblity layer so it looks identical
2040 to OpenSSL in all other aspects */
2041 return snprintf(buffer
, size
, "yassl/%s", YASSL_VERSION
);
2042 #else /* YASSL_VERSION */
2044 #if(SSLEAY_VERSION_NUMBER >= 0x905000)
2047 unsigned long ssleay_value
;
2049 ssleay_value
=SSLeay();
2050 if(ssleay_value
< 0x906000) {
2051 ssleay_value
=SSLEAY_VERSION_NUMBER
;
2055 if(ssleay_value
&0xff0) {
2056 sub
[0]=(char)(((ssleay_value
>>4)&0xff) + 'a' -1);
2062 return snprintf(buffer
, size
, "OpenSSL/%lx.%lx.%lx%s",
2063 (ssleay_value
>>28)&0xf,
2064 (ssleay_value
>>20)&0xff,
2065 (ssleay_value
>>12)&0xff,
2069 #else /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2071 #if(SSLEAY_VERSION_NUMBER >= 0x900000)
2072 return snprintf(buffer
, size
, "OpenSSL/%lx.%lx.%lx",
2073 (SSLEAY_VERSION_NUMBER
>>28)&0xff,
2074 (SSLEAY_VERSION_NUMBER
>>20)&0xff,
2075 (SSLEAY_VERSION_NUMBER
>>12)&0xf);
2077 #else /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2081 if(SSLEAY_VERSION_NUMBER
&0x0f) {
2082 sub
[0]=(SSLEAY_VERSION_NUMBER
&0x0f) + 'a' -1;
2087 return snprintf(buffer
, size
, "SSL/%x.%x.%x%s",
2088 (SSLEAY_VERSION_NUMBER
>>12)&0xff,
2089 (SSLEAY_VERSION_NUMBER
>>8)&0xf,
2090 (SSLEAY_VERSION_NUMBER
>>4)&0xf, sub
);
2092 #endif /* (SSLEAY_VERSION_NUMBER >= 0x900000) */
2093 #endif /* SSLEAY_VERSION_NUMBER is less than 0.9.5 */
2095 #endif /* YASSL_VERSION */
2097 #endif /* USE_SSLEAY */