1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, 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 https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
25 * but vtls.c should ever call or use these functions.
29 * The original SSLeay-using code for curl was written by Linas Vepstas and
30 * Sampo Kellomaki 1998.
33 #include "curl_setup.h"
43 #include "formdata.h" /* for the boundary function */
44 #include "url.h" /* for the ssl config check function */
45 #include "inet_pton.h"
52 #include "hostcheck.h"
53 #include "curl_printf.h"
55 #include <openssl/ssl.h>
56 #include <openssl/rand.h>
57 #include <openssl/x509v3.h>
58 #include <openssl/dsa.h>
59 #include <openssl/dh.h>
60 #include <openssl/err.h>
61 #include <openssl/md5.h>
62 #include <openssl/conf.h>
63 #include <openssl/bn.h>
64 #include <openssl/rsa.h>
66 #ifdef HAVE_OPENSSL_PKCS12_H
67 #include <openssl/pkcs12.h>
70 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
71 #include <openssl/ocsp.h>
75 #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
77 /* The last #include files should be: */
78 #include "curl_memory.h"
81 #ifndef OPENSSL_VERSION_NUMBER
82 #error "OPENSSL_VERSION_NUMBER not defined"
85 #if defined(HAVE_OPENSSL_ENGINE_H)
86 #include <openssl/ui.h>
89 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
90 #define SSL_METHOD_QUAL const
92 #define SSL_METHOD_QUAL
95 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
96 #define HAVE_ERR_REMOVE_THREAD_STATE 1
99 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
100 OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
101 #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
102 #define OPENSSL_NO_SSL2
105 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
106 !defined(LIBRESSL_VERSION_NUMBER)
107 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
108 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
109 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
110 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
111 #define CONST_EXTS const
112 #define CONST_ASN1_BIT_STRING const
113 #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
115 /* For OpenSSL before 1.1.0 */
116 #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
117 #define X509_get0_notBefore(x) X509_get_notBefore(x)
118 #define X509_get0_notAfter(x) X509_get_notAfter(x)
119 #define CONST_EXTS /* nope */
120 #define CONST_ASN1_BIT_STRING /* nope */
121 #ifdef LIBRESSL_VERSION_NUMBER
122 static unsigned long OpenSSL_version_num(void)
124 return LIBRESSL_VERSION_NUMBER;
127 #define OpenSSL_version_num() SSLeay()
131 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
132 !defined(LIBRESSL_VERSION_NUMBER)
133 #define HAVE_X509_GET0_SIGNATURE 1
136 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
137 OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
138 !defined(OPENSSL_NO_COMP)
139 #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
142 #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
143 /* not present in older OpenSSL */
144 #define OPENSSL_load_builtin_modules(x)
147 #if defined(LIBRESSL_VERSION_NUMBER)
148 #define OSSL_PACKAGE "LibreSSL"
149 #elif defined(OPENSSL_IS_BORINGSSL)
150 #define OSSL_PACKAGE "BoringSSL"
152 #define OSSL_PACKAGE "OpenSSL"
156 * Number of bytes to read from the random number seed file. This must be
157 * a finite value (because some entropy "files" like /dev/urandom have
158 * an infinite length), but must be large enough to provide enough
159 * entopy to properly seed OpenSSL's PRNG.
161 #define RAND_LOAD_LENGTH 1024
163 static int passwd_callback(char *buf, int num, int encrypting,
166 DEBUGASSERT(0 == encrypting);
169 int klen = curlx_uztosi(strlen((char *)global_passwd));
171 memcpy(buf, global_passwd, klen+1);
179 * rand_enough() returns TRUE if we have seeded the random engine properly.
181 static bool rand_enough(void)
183 return (0 != RAND_status()) ? TRUE : FALSE;
186 static CURLcode Curl_ossl_seed(struct Curl_easy *data)
188 /* we have the "SSL is seeded" boolean static to prevent multiple
189 time-consuming seedings in vain */
190 static bool ssl_seeded = FALSE;
191 char *buf = data->state.buffer; /* point to the big buffer */
198 /* OpenSSL 1.1.0+ will return here */
204 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
206 if(data->set.str[STRING_SSL_RANDOM_FILE])
207 #define RANDOM_FILE "" /* doesn't matter won't be used */
210 /* let the option override the define */
211 nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
212 data->set.str[STRING_SSL_RANDOM_FILE]:
219 #if defined(HAVE_RAND_EGD)
220 /* only available in OpenSSL 0.9.5 and later */
221 /* EGD_SOCKET is set at configure time or not at all */
223 /* If we don't have the define set, we only do this if the egd-option
225 if(data->set.str[STRING_SSL_EGDSOCKET])
226 #define EGD_SOCKET "" /* doesn't matter won't be used */
229 /* If there's an option and a define, the option overrides the
231 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
232 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
241 /* If we get here, it means we need to seed the PRNG using a "silly"
244 unsigned char randb[64];
245 int len = sizeof(randb);
246 if(!RAND_bytes(randb, len))
248 RAND_add(randb, len, (len >> 1));
249 } while(!rand_enough());
251 /* generates a default path for the random seed file */
252 buf[0]=0; /* blank it first */
253 RAND_file_name(buf, BUFSIZE);
255 /* we got a file name to try */
256 nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
261 infof(data, "libcurl is now using a weak random seed!\n");
262 return CURLE_SSL_CONNECT_ERROR; /* confusing error code */
265 #ifndef SSL_FILETYPE_ENGINE
266 #define SSL_FILETYPE_ENGINE 42
268 #ifndef SSL_FILETYPE_PKCS12
269 #define SSL_FILETYPE_PKCS12 43
271 static int do_file_type(const char *type)
273 if(!type || !type[0])
274 return SSL_FILETYPE_PEM;
275 if(strcasecompare(type, "PEM"))
276 return SSL_FILETYPE_PEM;
277 if(strcasecompare(type, "DER"))
278 return SSL_FILETYPE_ASN1;
279 if(strcasecompare(type, "ENG"))
280 return SSL_FILETYPE_ENGINE;
281 if(strcasecompare(type, "P12"))
282 return SSL_FILETYPE_PKCS12;
286 #if defined(HAVE_OPENSSL_ENGINE_H)
288 * Supply default password to the engine user interface conversation.
289 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
290 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
292 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
294 const char *password;
295 switch(UI_get_string_type(uis)) {
298 password = (const char *)UI_get0_user_data(ui);
299 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
300 UI_set_result(ui, uis, password);
306 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
310 * Suppress interactive request for a default password if available.
312 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
314 switch(UI_get_string_type(uis)) {
317 if(UI_get0_user_data(ui) &&
318 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
324 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
329 int cert_stuff(struct connectdata *conn,
332 const char *cert_type,
334 const char *key_type,
337 struct Curl_easy *data = conn->data;
339 int file_type = do_file_type(cert_type);
341 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
347 /* set the password in the callback userdata */
348 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
349 /* Set passwd callback: */
350 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
355 case SSL_FILETYPE_PEM:
356 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
357 if(SSL_CTX_use_certificate_chain_file(ctx,
360 "could not load PEM client certificate, " OSSL_PACKAGE
362 "(no key found, wrong pass phrase, or wrong file format?)",
363 ERR_error_string(ERR_get_error(), NULL) );
368 case SSL_FILETYPE_ASN1:
369 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
370 we use the case above for PEM so this can only be performed with
372 if(SSL_CTX_use_certificate_file(ctx,
376 "could not load ASN1 client certificate, " OSSL_PACKAGE
378 "(no key found, wrong pass phrase, or wrong file format?)",
379 ERR_error_string(ERR_get_error(), NULL) );
383 case SSL_FILETYPE_ENGINE:
384 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
386 if(data->state.engine) {
387 const char *cmd_name = "LOAD_CERT_CTRL";
393 params.cert_id = cert_file;
396 /* Does the engine supports LOAD_CERT_CTRL ? */
397 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
398 0, (void *)cmd_name, NULL)) {
399 failf(data, "ssl engine does not support loading certificates");
403 /* Load the certificate from the engine */
404 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
405 0, ¶ms, NULL, 1)) {
406 failf(data, "ssl engine cannot load client cert with id"
407 " '%s' [%s]", cert_file,
408 ERR_error_string(ERR_get_error(), NULL));
413 failf(data, "ssl engine didn't initialized the certificate "
418 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
419 failf(data, "unable to set client certificate");
420 X509_free(params.cert);
423 X509_free(params.cert); /* we don't need the handle any more... */
426 failf(data, "crypto engine not set, can't load certificate");
432 failf(data, "file type ENG for certificate not implemented");
436 case SSL_FILETYPE_PKCS12:
438 #ifdef HAVE_OPENSSL_PKCS12_H
442 STACK_OF(X509) *ca = NULL;
444 f = fopen(cert_file, "rb");
446 failf(data, "could not open PKCS12 file '%s'", cert_file);
449 p12 = d2i_PKCS12_fp(f, NULL);
453 failf(data, "error reading PKCS12 file '%s'", cert_file);
459 if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
462 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
464 ERR_error_string(ERR_get_error(), NULL) );
471 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
473 "could not load PKCS12 client certificate, " OSSL_PACKAGE
475 ERR_error_string(ERR_get_error(), NULL) );
479 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
480 failf(data, "unable to use private key from PKCS12 file '%s'",
485 if(!SSL_CTX_check_private_key (ctx)) {
486 failf(data, "private key from PKCS12 file '%s' "
487 "does not match certificate in same file", cert_file);
490 /* Set Certificate Verification chain */
492 while(sk_X509_num(ca)) {
494 * Note that sk_X509_pop() is used below to make sure the cert is
495 * removed from the stack properly before getting passed to
496 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
497 * we used sk_X509_value() instead, but then we'd clean it in the
498 * subsequent sk_X509_pop_free() call.
500 X509 *x = sk_X509_pop(ca);
501 if(!SSL_CTX_add_client_CA(ctx, x)) {
503 failf(data, "cannot add certificate to client CA list");
506 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
508 failf(data, "cannot add certificate to certificate chain");
518 sk_X509_pop_free(ca, X509_free);
521 return 0; /* failure! */
524 failf(data, "file type P12 for certificate not supported");
529 failf(data, "not supported file type '%s' for certificate", cert_type);
533 file_type = do_file_type(key_type);
536 case SSL_FILETYPE_PEM:
540 /* cert & key can only be in PEM case in the same file */
542 case SSL_FILETYPE_ASN1:
543 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
544 failf(data, "unable to set private key file: '%s' type %s",
545 key_file, key_type?key_type:"PEM");
549 case SSL_FILETYPE_ENGINE:
550 #ifdef HAVE_OPENSSL_ENGINE_H
551 { /* XXXX still needs some work */
552 EVP_PKEY *priv_key = NULL;
553 if(data->state.engine) {
554 UI_METHOD *ui_method =
555 UI_create_method((char *)"curl user interface");
557 failf(data, "unable do create " OSSL_PACKAGE
558 " user-interface method");
561 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
562 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
563 UI_method_set_reader(ui_method, ssl_ui_reader);
564 UI_method_set_writer(ui_method, ssl_ui_writer);
565 /* the typecast below was added to please mingw32 */
566 priv_key = (EVP_PKEY *)
567 ENGINE_load_private_key(data->state.engine, key_file,
570 UI_destroy_method(ui_method);
572 failf(data, "failed to load private key from crypto engine");
575 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
576 failf(data, "unable to set private key");
577 EVP_PKEY_free(priv_key);
580 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
583 failf(data, "crypto engine not set, can't load private key");
589 failf(data, "file type ENG for private key not supported");
592 case SSL_FILETYPE_PKCS12:
594 failf(data, "file type P12 for private key not supported");
599 failf(data, "not supported file type for private key");
605 failf(data, "unable to create an SSL structure");
609 x509=SSL_get_certificate(ssl);
611 /* This version was provided by Evan Jordan and is supposed to not
612 leak memory as the previous version: */
614 EVP_PKEY *pktmp = X509_get_pubkey(x509);
615 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
616 EVP_PKEY_free(pktmp);
621 /* If we are using DSA, we can copy the parameters from
625 /* Now we know that a key and cert have been set against
627 if(!SSL_CTX_check_private_key(ctx)) {
628 failf(data, "Private key does not match the certificate public key");
635 /* returns non-zero on failure */
636 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
639 return X509_NAME_oneline(a, buf, size);
641 BIO *bio_out = BIO_new(BIO_s_mem());
646 return 1; /* alloc failed! */
648 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
649 BIO_get_mem_ptr(bio_out, &biomem);
651 if((size_t)biomem->length < size)
652 size = biomem->length;
654 size--; /* don't overwrite the buffer end */
656 memcpy(buf, biomem->data, size);
665 /* Return error string for last OpenSSL error
667 static char *ossl_strerror(unsigned long error, char *buf, size_t size)
669 /* OpenSSL 0.9.6 and later has a function named
670 ERR_error_string_n() that takes the size of the buffer as a
672 ERR_error_string_n(error, buf, size);
679 * @retval 0 error initializing SSL
680 * @retval 1 SSL initialized successfully
682 int Curl_ossl_init(void)
684 OPENSSL_load_builtin_modules();
686 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
687 ENGINE_load_builtin_engines();
690 /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
691 that function makes an exit() call on wrongly formatted config files
692 which makes it hard to use in some situations. OPENSSL_config() itself
693 calls CONF_modules_load_file() and we use that instead and we ignore
696 /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
698 #ifndef CONF_MFLAGS_DEFAULT_SECTION
699 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
702 CONF_modules_load_file(NULL, NULL,
703 CONF_MFLAGS_DEFAULT_SECTION|
704 CONF_MFLAGS_IGNORE_MISSING_FILE);
706 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
707 !defined(LIBRESSL_VERSION_NUMBER)
708 /* OpenSSL 1.1.0+ takes care of initialization itself */
710 /* Lets get nice error messages */
711 SSL_load_error_strings();
713 /* Init the global ciphers and digests */
714 if(!SSLeay_add_ssl_algorithms())
717 OpenSSL_add_all_algorithms();
724 void Curl_ossl_cleanup(void)
726 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
727 !defined(LIBRESSL_VERSION_NUMBER)
728 /* OpenSSL 1.1 deprecates all these cleanup functions and
729 turns them into no-ops in OpenSSL 1.0 compatibility mode */
731 /* Free ciphers and digests lists */
734 #ifdef HAVE_ENGINE_CLEANUP
735 /* Free engine list */
739 /* Free OpenSSL error strings */
742 /* Free thread local error state, destroying hash upon zero refcount */
743 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
744 ERR_remove_thread_state(NULL);
749 /* Free all memory allocated by all configuration modules */
752 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
753 SSL_COMP_free_compression_methods();
759 * This function is used to determine connection status.
762 * 1 means the connection is still in place
763 * 0 means the connection has been closed
764 * -1 means the connection status is unknown
766 int Curl_ossl_check_cxn(struct connectdata *conn)
768 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
769 recv MSG_PEEK instead. Bug #795 */
773 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
774 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
776 return 0; /* connection has been closed */
778 return 1; /* connection still in place */
779 else if(nread == -1) {
781 if(err == EINPROGRESS ||
782 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
786 return 1; /* connection still in place */
787 if(err == ECONNRESET ||
789 err == ECONNABORTED ||
804 return 0; /* connection has been closed */
807 return -1; /* connection status unknown */
810 /* Selects an OpenSSL crypto engine
812 CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
814 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
817 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
818 e = ENGINE_by_id(engine);
820 /* avoid memory leak */
821 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
822 const char *e_id = ENGINE_get_id(e);
823 if(!strcmp(engine, e_id))
829 failf(data, "SSL Engine '%s' not found", engine);
830 return CURLE_SSL_ENGINE_NOTFOUND;
833 if(data->state.engine) {
834 ENGINE_finish(data->state.engine);
835 ENGINE_free(data->state.engine);
836 data->state.engine = NULL;
838 if(!ENGINE_init(e)) {
842 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
843 engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
844 return CURLE_SSL_ENGINE_INITFAILED;
846 data->state.engine = e;
850 failf(data, "SSL Engine not supported");
851 return CURLE_SSL_ENGINE_NOTFOUND;
855 /* Sets engine as default for all SSL operations
857 CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
859 #ifdef HAVE_OPENSSL_ENGINE_H
860 if(data->state.engine) {
861 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
862 infof(data, "set default crypto engine '%s'\n",
863 ENGINE_get_id(data->state.engine));
866 failf(data, "set default crypto engine '%s' failed",
867 ENGINE_get_id(data->state.engine));
868 return CURLE_SSL_ENGINE_SETFAILED;
877 /* Return list of OpenSSL crypto engine names.
879 struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
881 struct curl_slist *list = NULL;
882 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
883 struct curl_slist *beg;
886 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
887 beg = curl_slist_append(list, ENGINE_get_id(e));
889 curl_slist_free_all(list);
900 static void ossl_close(struct ssl_connect_data *connssl)
902 if(connssl->handle) {
903 (void)SSL_shutdown(connssl->handle);
904 SSL_set_connect_state(connssl->handle);
906 SSL_free(connssl->handle);
907 connssl->handle = NULL;
910 SSL_CTX_free(connssl->ctx);
916 * This function is called when an SSL connection is closed.
918 void Curl_ossl_close(struct connectdata *conn, int sockindex)
920 ossl_close(&conn->ssl[sockindex]);
921 ossl_close(&conn->proxy_ssl[sockindex]);
925 * This function is called to shut down the SSL layer but keep the
926 * socket open (CCC - Clear Command Channel)
928 int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
931 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
932 struct Curl_easy *data = conn->data;
933 char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
934 to be at least 256 bytes long. */
935 unsigned long sslerror;
941 /* This has only been tested on the proftpd server, and the mod_tls code
942 sends a close notify alert without waiting for a close notify alert in
943 response. Thus we wait for a close notify alert from the server, but
944 we do not send one. Let's hope other servers do the same... */
946 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
947 (void)SSL_shutdown(connssl->handle);
949 if(connssl->handle) {
950 buffsize = (int)sizeof(buf);
952 int what = SOCKET_READABLE(conn->sock[sockindex],
953 SSL_SHUTDOWN_TIMEOUT);
957 /* Something to read, let's do it and hope that it is the close
958 notify alert from the server */
959 nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
961 err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
964 case SSL_ERROR_NONE: /* this is not an error */
965 case SSL_ERROR_ZERO_RETURN: /* no more data */
966 /* This is the expected response. There was no data but only
967 the close notify alert */
970 case SSL_ERROR_WANT_READ:
971 /* there's data pending, re-invoke SSL_read() */
972 infof(data, "SSL_ERROR_WANT_READ\n");
974 case SSL_ERROR_WANT_WRITE:
975 /* SSL wants a write. Really odd. Let's bail out. */
976 infof(data, "SSL_ERROR_WANT_WRITE\n");
980 /* openssl/ssl.h says "look at error stack/return value/errno" */
981 sslerror = ERR_get_error();
982 failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d",
983 ossl_strerror(sslerror, buf, sizeof(buf)),
991 failf(data, "SSL shutdown timeout");
995 /* anything that gets here is fatally bad */
996 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1000 } /* while()-loop for the select() */
1002 if(data->set.verbose) {
1003 #ifdef HAVE_SSL_GET_SHUTDOWN
1004 switch(SSL_get_shutdown(connssl->handle)) {
1005 case SSL_SENT_SHUTDOWN:
1006 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1008 case SSL_RECEIVED_SHUTDOWN:
1009 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1011 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1012 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1013 "SSL_RECEIVED__SHUTDOWN\n");
1019 SSL_free(connssl->handle);
1020 connssl->handle = NULL;
1025 void Curl_ossl_session_free(void *ptr)
1028 SSL_SESSION_free(ptr);
1032 * This function is called when the 'data' struct is going away. Close
1033 * down everything and free all resources!
1035 void Curl_ossl_close_all(struct Curl_easy *data)
1037 #ifdef HAVE_OPENSSL_ENGINE_H
1038 if(data->state.engine) {
1039 ENGINE_finish(data->state.engine);
1040 ENGINE_free(data->state.engine);
1041 data->state.engine = NULL;
1046 #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
1047 defined(HAVE_ERR_REMOVE_THREAD_STATE)
1048 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
1049 so we need to clean it here in case the thread will be killed. All OpenSSL
1050 code should extract the error in association with the error so clearing
1051 this queue here should be harmless at worst. */
1052 ERR_remove_thread_state(NULL);
1056 /* ====================================================== */
1059 /* Quote from RFC2818 section 3.1 "Server Identity"
1061 If a subjectAltName extension of type dNSName is present, that MUST
1062 be used as the identity. Otherwise, the (most specific) Common Name
1063 field in the Subject field of the certificate MUST be used. Although
1064 the use of the Common Name is existing practice, it is deprecated and
1065 Certification Authorities are encouraged to use the dNSName instead.
1067 Matching is performed using the matching rules specified by
1068 [RFC2459]. If more than one identity of a given type is present in
1069 the certificate (e.g., more than one dNSName name, a match in any one
1070 of the set is considered acceptable.) Names may contain the wildcard
1071 character * which is considered to match any single domain name
1072 component or component fragment. E.g., *.a.com matches foo.a.com but
1073 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1075 In some cases, the URI is specified as an IP address rather than a
1076 hostname. In this case, the iPAddress subjectAltName must be present
1077 in the certificate and must exactly match the IP in the URI.
1080 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1082 bool matched = FALSE;
1083 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1085 struct Curl_easy *data = conn->data;
1086 STACK_OF(GENERAL_NAME) *altnames;
1088 struct in6_addr addr;
1090 struct in_addr addr;
1092 CURLcode result = CURLE_OK;
1093 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
1094 bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
1095 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1097 const char * const dispname = SSL_IS_PROXY() ?
1098 conn->http_proxy.host.dispname : conn->host.dispname;
1101 if(conn->bits.ipv6_ip &&
1102 Curl_inet_pton(AF_INET6, hostname, &addr)) {
1104 addrlen = sizeof(struct in6_addr);
1108 if(Curl_inet_pton(AF_INET, hostname, &addr)) {
1110 addrlen = sizeof(struct in_addr);
1113 /* get a "list" of alternative names */
1114 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1119 bool dnsmatched = FALSE;
1120 bool ipmatched = FALSE;
1122 /* get amount of alternatives, RFC2459 claims there MUST be at least
1123 one, but we don't depend on it... */
1124 numalts = sk_GENERAL_NAME_num(altnames);
1126 /* loop through all alternatives - until a dnsmatch */
1127 for(i=0; (i < numalts) && !dnsmatched; i++) {
1128 /* get a handle to alternative name number i */
1129 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1131 if(check->type == GEN_DNS)
1133 else if(check->type == GEN_IPADD)
1136 /* only check alternatives of the same type the target is */
1137 if(check->type == target) {
1138 /* get data and length */
1139 const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
1140 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1143 case GEN_DNS: /* name/pattern comparison */
1144 /* The OpenSSL man page explicitly says: "In general it cannot be
1145 assumed that the data returned by ASN1_STRING_data() is null
1146 terminated or does not contain embedded nulls." But also that
1147 "The actual format of the data will depend on the actual string
1148 type itself: for example for and IA5String the data will be ASCII"
1150 Gisle researched the OpenSSL sources:
1151 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1152 it always 0-terminates an IA5String."
1154 if((altlen == strlen(altptr)) &&
1155 /* if this isn't true, there was an embedded zero in the name
1156 string and we cannot match it. */
1157 Curl_cert_hostcheck(altptr, hostname)) {
1160 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1165 case GEN_IPADD: /* IP address comparison */
1166 /* compare alternative IP address if the data chunk is the same size
1167 our server IP address is */
1168 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1171 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1178 GENERAL_NAMES_free(altnames);
1180 if(dnsmatched || ipmatched)
1185 /* an alternative name matched */
1187 else if(dNSName || iPAddress) {
1188 infof(data, " subjectAltName does not match %s\n", dispname);
1189 failf(data, "SSL: no alternative certificate subject name matches "
1190 "target host name '%s'", dispname);
1191 result = CURLE_PEER_FAILED_VERIFICATION;
1194 /* we have to look to the last occurrence of a commonName in the
1195 distinguished one to get the most significant one. */
1198 /* The following is done because of a bug in 0.9.6b */
1200 unsigned char *nulstr = (unsigned char *)"";
1201 unsigned char *peer_CN = nulstr;
1203 X509_NAME *name = X509_get_subject_name(server_cert);
1205 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
1208 /* we have the name entry and we will now convert this to a string
1209 that we can use for comparison. Doing this we support BMPstring,
1214 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1216 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1217 is already UTF-8 encoded. We check for this case and copy the raw
1218 string manually to avoid the problem. This code can be made
1219 conditional in the future when OpenSSL has been fixed. Work-around
1220 brought by Alexis S. L. Carvalho. */
1222 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1223 j = ASN1_STRING_length(tmp);
1225 peer_CN = OPENSSL_malloc(j+1);
1227 memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
1232 else /* not a UTF8 name */
1233 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1235 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1236 /* there was a terminating zero before the end of string, this
1237 cannot match and we return failure! */
1238 failf(data, "SSL: illegal cert name field");
1239 result = CURLE_PEER_FAILED_VERIFICATION;
1244 if(peer_CN == nulstr)
1247 /* convert peer_CN from UTF8 */
1248 CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
1249 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1251 OPENSSL_free(peer_CN);
1257 /* error already detected, pass through */
1261 "SSL: unable to obtain common name from peer certificate");
1262 result = CURLE_PEER_FAILED_VERIFICATION;
1264 else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
1265 failf(data, "SSL: certificate subject name '%s' does not match "
1266 "target host name '%s'", peer_CN, dispname);
1267 result = CURLE_PEER_FAILED_VERIFICATION;
1270 infof(data, " common name: %s (matched)\n", peer_CN);
1273 OPENSSL_free(peer_CN);
1279 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1280 !defined(OPENSSL_NO_OCSP)
1281 static CURLcode verifystatus(struct connectdata *conn,
1282 struct ssl_connect_data *connssl)
1285 const unsigned char *p;
1286 CURLcode result = CURLE_OK;
1287 struct Curl_easy *data = conn->data;
1289 OCSP_RESPONSE *rsp = NULL;
1290 OCSP_BASICRESP *br = NULL;
1291 X509_STORE *st = NULL;
1292 STACK_OF(X509) *ch = NULL;
1294 long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
1297 failf(data, "No OCSP response received");
1298 result = CURLE_SSL_INVALIDCERTSTATUS;
1302 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1304 failf(data, "Invalid OCSP response");
1305 result = CURLE_SSL_INVALIDCERTSTATUS;
1309 ocsp_status = OCSP_response_status(rsp);
1310 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1311 failf(data, "Invalid OCSP response status: %s (%d)",
1312 OCSP_response_status_str(ocsp_status), ocsp_status);
1313 result = CURLE_SSL_INVALIDCERTSTATUS;
1317 br = OCSP_response_get1_basic(rsp);
1319 failf(data, "Invalid OCSP response");
1320 result = CURLE_SSL_INVALIDCERTSTATUS;
1324 ch = SSL_get_peer_cert_chain(connssl->handle);
1325 st = SSL_CTX_get_cert_store(connssl->ctx);
1327 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1328 defined(LIBRESSL_VERSION_NUMBER))
1329 /* The authorized responder cert in the OCSP response MUST be signed by the
1330 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1331 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1332 expects this issuer to be present in the chain embedded in the OCSP
1333 response. So we add it if necessary. */
1335 /* First make sure the peer cert chain includes both a peer and an issuer,
1336 and the OCSP response contains a responder cert. */
1337 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1338 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1340 /* Find issuer of responder cert and add it to the OCSP response chain */
1341 for(i = 0; i < sk_X509_num(ch); i++) {
1342 X509 *issuer = sk_X509_value(ch, i);
1343 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1344 if(!OCSP_basic_add1_cert(br, issuer)) {
1345 failf(data, "Could not add issuer cert to OCSP response");
1346 result = CURLE_SSL_INVALIDCERTSTATUS;
1354 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1355 failf(data, "OCSP response verification failed");
1356 result = CURLE_SSL_INVALIDCERTSTATUS;
1360 for(i = 0; i < OCSP_resp_count(br); i++) {
1361 int cert_status, crl_reason;
1362 OCSP_SINGLERESP *single = NULL;
1364 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1366 single = OCSP_resp_get0(br, i);
1370 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1371 &thisupd, &nextupd);
1373 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1374 failf(data, "OCSP response has expired");
1375 result = CURLE_SSL_INVALIDCERTSTATUS;
1379 infof(data, "SSL certificate status: %s (%d)\n",
1380 OCSP_cert_status_str(cert_status), cert_status);
1382 switch(cert_status) {
1383 case V_OCSP_CERTSTATUS_GOOD:
1386 case V_OCSP_CERTSTATUS_REVOKED:
1387 result = CURLE_SSL_INVALIDCERTSTATUS;
1389 failf(data, "SSL certificate revocation reason: %s (%d)",
1390 OCSP_crl_reason_str(crl_reason), crl_reason);
1393 case V_OCSP_CERTSTATUS_UNKNOWN:
1394 result = CURLE_SSL_INVALIDCERTSTATUS;
1400 if(br) OCSP_BASICRESP_free(br);
1401 OCSP_RESPONSE_free(rsp);
1407 #endif /* USE_OPENSSL */
1409 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1410 and thus this cannot be done there. */
1411 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1413 static const char *ssl_msg_type(int ssl_ver, int msg)
1415 #ifdef SSL2_VERSION_MAJOR
1416 if(ssl_ver == SSL2_VERSION_MAJOR) {
1420 case SSL2_MT_CLIENT_HELLO:
1421 return "Client hello";
1422 case SSL2_MT_CLIENT_MASTER_KEY:
1423 return "Client key";
1424 case SSL2_MT_CLIENT_FINISHED:
1425 return "Client finished";
1426 case SSL2_MT_SERVER_HELLO:
1427 return "Server hello";
1428 case SSL2_MT_SERVER_VERIFY:
1429 return "Server verify";
1430 case SSL2_MT_SERVER_FINISHED:
1431 return "Server finished";
1432 case SSL2_MT_REQUEST_CERTIFICATE:
1433 return "Request CERT";
1434 case SSL2_MT_CLIENT_CERTIFICATE:
1435 return "Client CERT";
1440 if(ssl_ver == SSL3_VERSION_MAJOR) {
1442 case SSL3_MT_HELLO_REQUEST:
1443 return "Hello request";
1444 case SSL3_MT_CLIENT_HELLO:
1445 return "Client hello";
1446 case SSL3_MT_SERVER_HELLO:
1447 return "Server hello";
1448 #ifdef SSL3_MT_NEWSESSION_TICKET
1449 case SSL3_MT_NEWSESSION_TICKET:
1450 return "Newsession Ticket";
1452 case SSL3_MT_CERTIFICATE:
1453 return "Certificate";
1454 case SSL3_MT_SERVER_KEY_EXCHANGE:
1455 return "Server key exchange";
1456 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1457 return "Client key exchange";
1458 case SSL3_MT_CERTIFICATE_REQUEST:
1459 return "Request CERT";
1460 case SSL3_MT_SERVER_DONE:
1461 return "Server finished";
1462 case SSL3_MT_CERTIFICATE_VERIFY:
1463 return "CERT verify";
1464 case SSL3_MT_FINISHED:
1466 #ifdef SSL3_MT_CERTIFICATE_STATUS
1467 case SSL3_MT_CERTIFICATE_STATUS:
1468 return "Certificate Status";
1475 static const char *tls_rt_type(int type)
1478 #ifdef SSL3_RT_HEADER
1479 case SSL3_RT_HEADER:
1480 return "TLS header";
1482 case SSL3_RT_CHANGE_CIPHER_SPEC:
1483 return "TLS change cipher";
1486 case SSL3_RT_HANDSHAKE:
1487 return "TLS handshake";
1488 case SSL3_RT_APPLICATION_DATA:
1489 return "TLS app data";
1491 return "TLS Unknown";
1497 * Our callback from the SSL/TLS layers.
1499 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1500 const void *buf, size_t len, SSL *ssl,
1503 struct Curl_easy *data;
1504 const char *msg_name, *tls_rt_name;
1507 int msg_type, txt_len;
1508 const char *verstr = NULL;
1509 struct connectdata *conn = userp;
1511 if(!conn || !conn->data || !conn->data->set.fdebug ||
1512 (direction != 0 && direction != 1))
1518 #ifdef SSL2_VERSION /* removed in recent versions */
1531 #ifdef TLS1_1_VERSION
1532 case TLS1_1_VERSION:
1536 #ifdef TLS1_2_VERSION
1537 case TLS1_2_VERSION:
1541 #ifdef TLS1_3_VERSION
1542 case TLS1_3_VERSION:
1549 snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1555 /* the info given when the version is zero is not that useful for us */
1557 ssl_ver >>= 8; /* check the upper 8 bits only below */
1559 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1560 * always pass-up content-type as 0. But the interesting message-type
1563 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
1564 tls_rt_name = tls_rt_type(content_type);
1568 msg_type = *(char *)buf;
1569 msg_name = ssl_msg_type(ssl_ver, msg_type);
1571 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
1572 verstr, direction?"OUT":"IN",
1573 tls_rt_name, msg_name, msg_type);
1574 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1577 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1578 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1584 /* ====================================================== */
1586 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1587 # define use_sni(x) sni = (x)
1589 # define use_sni(x) Curl_nop_stmt
1592 /* Check for OpenSSL 1.0.2 which has ALPN support. */
1594 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1595 && !defined(OPENSSL_NO_TLSEXT)
1599 /* Check for OpenSSL 1.0.1 which has NPN support. */
1601 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
1602 && !defined(OPENSSL_NO_TLSEXT) \
1603 && !defined(OPENSSL_NO_NEXTPROTONEG)
1610 * in is a list of lenght prefixed strings. this function has to select
1611 * the protocol we want to use from the list and write its string into out.
1615 select_next_protocol(unsigned char **out, unsigned char *outlen,
1616 const unsigned char *in, unsigned int inlen,
1617 const char *key, unsigned int keylen)
1620 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
1621 if(memcmp(&in[i + 1], key, keylen) == 0) {
1622 *out = (unsigned char *) &in[i + 1];
1631 select_next_proto_cb(SSL *ssl,
1632 unsigned char **out, unsigned char *outlen,
1633 const unsigned char *in, unsigned int inlen,
1636 struct connectdata *conn = (struct connectdata*) arg;
1641 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
1642 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
1643 NGHTTP2_PROTO_VERSION_ID_LEN)) {
1644 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
1645 NGHTTP2_PROTO_VERSION_ID);
1646 conn->negnpn = CURL_HTTP_VERSION_2;
1647 return SSL_TLSEXT_ERR_OK;
1651 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
1652 ALPN_HTTP_1_1_LENGTH)) {
1653 infof(conn->data, "NPN, negotiated HTTP1.1\n");
1654 conn->negnpn = CURL_HTTP_VERSION_1_1;
1655 return SSL_TLSEXT_ERR_OK;
1658 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
1659 *out = (unsigned char *)ALPN_HTTP_1_1;
1660 *outlen = ALPN_HTTP_1_1_LENGTH;
1661 conn->negnpn = CURL_HTTP_VERSION_1_1;
1663 return SSL_TLSEXT_ERR_OK;
1665 #endif /* HAS_NPN */
1668 get_ssl_version_txt(SSL *ssl)
1673 switch(SSL_version(ssl)) {
1674 #ifdef TLS1_3_VERSION
1675 case TLS1_3_VERSION:
1678 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1679 case TLS1_2_VERSION:
1681 case TLS1_1_VERSION:
1694 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
1696 CURLcode result = CURLE_OK;
1698 struct Curl_easy *data = conn->data;
1699 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
1700 X509_LOOKUP *lookup = NULL;
1701 curl_socket_t sockfd = conn->sock[sockindex];
1702 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1704 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1707 struct in6_addr addr;
1709 struct in_addr addr;
1712 long * const certverifyresult = SSL_IS_PROXY() ?
1713 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
1714 const long int ssl_version = SSL_CONN_CONFIG(version);
1716 const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
1718 char * const ssl_cert = SSL_SET_OPTION(cert);
1719 const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
1720 const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
1721 const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
1722 const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
1723 const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
1724 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1727 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
1729 /* Make funny stuff to get random input */
1730 result = Curl_ossl_seed(data);
1734 *certverifyresult = !X509_V_OK;
1736 /* check to see if we've been told to use an explicit SSL/TLS version */
1738 switch(ssl_version) {
1739 case CURL_SSLVERSION_DEFAULT:
1740 case CURL_SSLVERSION_TLSv1:
1741 case CURL_SSLVERSION_TLSv1_0:
1742 case CURL_SSLVERSION_TLSv1_1:
1743 case CURL_SSLVERSION_TLSv1_2:
1744 case CURL_SSLVERSION_TLSv1_3:
1745 /* it will be handled later with the context options */
1746 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
1747 !defined(LIBRESSL_VERSION_NUMBER)
1748 req_method = TLS_client_method();
1750 req_method = SSLv23_client_method();
1754 case CURL_SSLVERSION_SSLv2:
1755 #ifdef OPENSSL_NO_SSL2
1756 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
1757 return CURLE_NOT_BUILT_IN;
1760 if(ssl_authtype == CURL_TLSAUTH_SRP)
1761 return CURLE_SSL_CONNECT_ERROR;
1763 req_method = SSLv2_client_method();
1767 case CURL_SSLVERSION_SSLv3:
1768 #ifdef OPENSSL_NO_SSL3_METHOD
1769 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
1770 return CURLE_NOT_BUILT_IN;
1773 if(ssl_authtype == CURL_TLSAUTH_SRP)
1774 return CURLE_SSL_CONNECT_ERROR;
1776 req_method = SSLv3_client_method();
1781 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
1782 return CURLE_SSL_CONNECT_ERROR;
1786 SSL_CTX_free(connssl->ctx);
1787 connssl->ctx = SSL_CTX_new(req_method);
1790 failf(data, "SSL: couldn't create a context: %s",
1791 ERR_error_string(ERR_peek_error(), NULL));
1792 return CURLE_OUT_OF_MEMORY;
1795 #ifdef SSL_MODE_RELEASE_BUFFERS
1796 SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
1799 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1800 if(data->set.fdebug && data->set.verbose) {
1801 /* the SSL trace callback is only used for verbose logging */
1802 SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
1803 SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
1807 /* OpenSSL contains code to work-around lots of bugs and flaws in various
1808 SSL-implementations. SSL_CTX_set_options() is used to enabled those
1809 work-arounds. The man page for this option states that SSL_OP_ALL enables
1810 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
1811 enable the bug workaround options if compatibility with somewhat broken
1812 implementations is desired."
1814 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
1815 disable "rfc4507bis session ticket support". rfc4507bis was later turned
1816 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
1818 The enabled extension concerns the session management. I wonder how often
1819 libcurl stops a connection and then resumes a TLS session. also, sending
1820 the session data is some overhead. .I suggest that you just use your
1821 proposed patch (which explicitly disables TICKET).
1823 If someone writes an application with libcurl and openssl who wants to
1824 enable the feature, one can do this in the SSL callback.
1826 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
1827 interoperability with web server Netscape Enterprise Server 2.0.1 which
1828 was released back in 1996.
1830 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
1831 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
1832 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
1833 this option regardless of OpenSSL version and SSL_OP_ALL definition.
1835 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
1836 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
1837 SSL_OP_ALL that _disables_ that work-around despite the fact that
1838 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
1839 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
1843 ctx_options = SSL_OP_ALL;
1845 #ifdef SSL_OP_NO_TICKET
1846 ctx_options |= SSL_OP_NO_TICKET;
1849 #ifdef SSL_OP_NO_COMPRESSION
1850 ctx_options |= SSL_OP_NO_COMPRESSION;
1853 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
1854 /* mitigate CVE-2010-4180 */
1855 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
1858 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
1859 /* unless the user explicitly ask to allow the protocol vulnerability we
1860 use the work-around */
1861 if(!SSL_SET_OPTION(enable_beast))
1862 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1865 switch(ssl_version) {
1866 case CURL_SSLVERSION_SSLv3:
1868 if(ssl_authtype == CURL_TLSAUTH_SRP) {
1869 infof(data, "Set version TLSv1.x for SRP authorisation\n");
1872 ctx_options |= SSL_OP_NO_SSLv2;
1873 ctx_options |= SSL_OP_NO_TLSv1;
1874 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1875 ctx_options |= SSL_OP_NO_TLSv1_1;
1876 ctx_options |= SSL_OP_NO_TLSv1_2;
1877 #ifdef TLS1_3_VERSION
1878 ctx_options |= SSL_OP_NO_TLSv1_3;
1883 case CURL_SSLVERSION_DEFAULT:
1884 case CURL_SSLVERSION_TLSv1:
1885 ctx_options |= SSL_OP_NO_SSLv2;
1886 ctx_options |= SSL_OP_NO_SSLv3;
1889 case CURL_SSLVERSION_TLSv1_0:
1890 ctx_options |= SSL_OP_NO_SSLv2;
1891 ctx_options |= SSL_OP_NO_SSLv3;
1892 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1893 ctx_options |= SSL_OP_NO_TLSv1_1;
1894 ctx_options |= SSL_OP_NO_TLSv1_2;
1895 #ifdef TLS1_3_VERSION
1896 ctx_options |= SSL_OP_NO_TLSv1_3;
1901 case CURL_SSLVERSION_TLSv1_1:
1902 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1903 ctx_options |= SSL_OP_NO_SSLv2;
1904 ctx_options |= SSL_OP_NO_SSLv3;
1905 ctx_options |= SSL_OP_NO_TLSv1;
1906 ctx_options |= SSL_OP_NO_TLSv1_2;
1907 #ifdef TLS1_3_VERSION
1908 ctx_options |= SSL_OP_NO_TLSv1_3;
1912 failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
1913 return CURLE_NOT_BUILT_IN;
1916 case CURL_SSLVERSION_TLSv1_2:
1917 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1918 ctx_options |= SSL_OP_NO_SSLv2;
1919 ctx_options |= SSL_OP_NO_SSLv3;
1920 ctx_options |= SSL_OP_NO_TLSv1;
1921 ctx_options |= SSL_OP_NO_TLSv1_1;
1922 #ifdef TLS1_3_VERSION
1923 ctx_options |= SSL_OP_NO_TLSv1_3;
1927 failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
1928 return CURLE_NOT_BUILT_IN;
1931 case CURL_SSLVERSION_TLSv1_3:
1932 #ifdef TLS1_3_VERSION
1933 SSL_CTX_set_max_proto_version(connssl->ctx, TLS1_3_VERSION);
1934 ctx_options |= SSL_OP_NO_SSLv2;
1935 ctx_options |= SSL_OP_NO_SSLv3;
1936 ctx_options |= SSL_OP_NO_TLSv1;
1937 ctx_options |= SSL_OP_NO_TLSv1_1;
1938 ctx_options |= SSL_OP_NO_TLSv1_2;
1941 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
1942 return CURLE_NOT_BUILT_IN;
1945 case CURL_SSLVERSION_SSLv2:
1946 #ifndef OPENSSL_NO_SSL2
1947 ctx_options |= SSL_OP_NO_SSLv3;
1948 ctx_options |= SSL_OP_NO_TLSv1;
1949 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1950 ctx_options |= SSL_OP_NO_TLSv1_1;
1951 ctx_options |= SSL_OP_NO_TLSv1_2;
1952 #ifdef TLS1_3_VERSION
1953 ctx_options |= SSL_OP_NO_TLSv1_3;
1958 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
1959 return CURLE_NOT_BUILT_IN;
1963 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
1964 return CURLE_SSL_CONNECT_ERROR;
1967 SSL_CTX_set_options(connssl->ctx, ctx_options);
1970 if(conn->bits.tls_enable_npn)
1971 SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
1975 if(conn->bits.tls_enable_alpn) {
1977 unsigned char protocols[128];
1980 if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
1981 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
1983 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
1984 NGHTTP2_PROTO_VERSION_ID_LEN);
1985 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1986 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
1990 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
1991 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1992 cur += ALPN_HTTP_1_1_LENGTH;
1993 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
1995 /* expects length prefixed preference ordered list of protocols in wire
1998 SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
2002 if(ssl_cert || ssl_cert_type) {
2003 if(!cert_stuff(conn, connssl->ctx, ssl_cert, ssl_cert_type,
2004 SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
2005 SSL_SET_OPTION(key_passwd))) {
2006 /* failf() is already done in cert_stuff() */
2007 return CURLE_SSL_CERTPROBLEM;
2011 ciphers = SSL_CONN_CONFIG(cipher_list);
2013 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2014 if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
2015 failf(data, "failed setting cipher list: %s", ciphers);
2016 return CURLE_SSL_CIPHER;
2018 infof(data, "Cipher selection: %s\n", ciphers);
2021 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2022 char * const ssl_username = SSL_SET_OPTION(username);
2024 infof(data, "Using TLS-SRP username: %s\n", ssl_username);
2026 if(!SSL_CTX_set_srp_username(connssl->ctx, ssl_username)) {
2027 failf(data, "Unable to set SRP user name");
2028 return CURLE_BAD_FUNCTION_ARGUMENT;
2030 if(!SSL_CTX_set_srp_password(connssl->ctx, SSL_SET_OPTION(password))) {
2031 failf(data, "failed setting SRP password");
2032 return CURLE_BAD_FUNCTION_ARGUMENT;
2034 if(!SSL_CONN_CONFIG(cipher_list)) {
2035 infof(data, "Setting cipher list SRP\n");
2037 if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
2038 failf(data, "failed setting SRP cipher list");
2039 return CURLE_SSL_CIPHER;
2045 if(ssl_cafile || ssl_capath) {
2046 /* tell SSL where to find CA certificates that are used to verify
2047 the servers certificate. */
2048 if(!SSL_CTX_load_verify_locations(connssl->ctx, ssl_cafile, ssl_capath)) {
2050 /* Fail if we insist on successfully verifying the server. */
2051 failf(data, "error setting certificate verify locations:\n"
2052 " CAfile: %s\n CApath: %s",
2053 ssl_cafile ? ssl_cafile : "none",
2054 ssl_capath ? ssl_capath : "none");
2055 return CURLE_SSL_CACERT_BADFILE;
2058 /* Just continue with a warning if no strict certificate verification
2060 infof(data, "error setting certificate verify locations,"
2061 " continuing anyway:\n");
2065 /* Everything is fine. */
2066 infof(data, "successfully set certificate verify locations:\n");
2071 ssl_cafile ? ssl_cafile : "none",
2072 ssl_capath ? ssl_capath : "none");
2074 #ifdef CURL_CA_FALLBACK
2075 else if(verifypeer) {
2076 /* verfying the peer without any CA certificates won't
2077 work so use openssl's built in default as fallback */
2078 SSL_CTX_set_default_verify_paths(connssl->ctx);
2083 /* tell SSL where to find CRL file that is used to check certificate
2085 lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
2086 X509_LOOKUP_file());
2088 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
2089 failf(data, "error loading CRL file: %s", ssl_crlfile);
2090 return CURLE_SSL_CRL_BADFILE;
2093 /* Everything is fine. */
2094 infof(data, "successfully load CRL file:\n");
2095 X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
2096 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2098 infof(data, " CRLfile: %s\n", ssl_crlfile);
2101 /* Try building a chain using issuers in the trusted store first to avoid
2102 problems with server-sent legacy intermediates.
2103 Newer versions of OpenSSL do alternate chain checking by default which
2104 gives us the same fix without as much of a performance hit (slight), so we
2105 prefer that if available.
2106 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2108 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2110 X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
2111 X509_V_FLAG_TRUSTED_FIRST);
2115 /* SSL always tries to verify the peer, this only says whether it should
2116 * fail to connect if the verification fails, or if it should continue
2117 * anyway. In the latter case the result of the verification is checked with
2118 * SSL_get_verify_result() below. */
2119 SSL_CTX_set_verify(connssl->ctx,
2120 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
2122 /* give application a chance to interfere with SSL set up. */
2123 if(data->set.ssl.fsslctx) {
2124 result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
2125 data->set.ssl.fsslctxp);
2127 failf(data, "error signaled by ssl ctx callback");
2132 /* Lets make an SSL structure */
2134 SSL_free(connssl->handle);
2135 connssl->handle = SSL_new(connssl->ctx);
2136 if(!connssl->handle) {
2137 failf(data, "SSL: couldn't create a context (handle)!");
2138 return CURLE_OUT_OF_MEMORY;
2141 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2142 !defined(OPENSSL_NO_OCSP)
2143 if(SSL_CONN_CONFIG(verifystatus))
2144 SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
2147 SSL_set_connect_state(connssl->handle);
2149 connssl->server_cert = 0x0;
2150 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2151 if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
2153 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
2156 !SSL_set_tlsext_host_name(connssl->handle, hostname))
2157 infof(data, "WARNING: failed to configure server name indication (SNI) "
2161 /* Check if there's a cached ID we can/should use here! */
2162 if(data->set.general_ssl.sessionid) {
2163 void *ssl_sessionid = NULL;
2165 Curl_ssl_sessionid_lock(conn);
2166 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
2167 /* we got a session id, use it! */
2168 if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
2169 Curl_ssl_sessionid_unlock(conn);
2170 failf(data, "SSL: SSL_set_session failed: %s",
2171 ERR_error_string(ERR_get_error(), NULL));
2172 return CURLE_SSL_CONNECT_ERROR;
2174 /* Informational message */
2175 infof(data, "SSL re-using session ID\n");
2177 Curl_ssl_sessionid_unlock(conn);
2180 if(conn->proxy_ssl[sockindex].use) {
2181 BIO *const bio = BIO_new(BIO_f_ssl());
2182 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2183 DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
2184 DEBUGASSERT(bio != NULL);
2185 BIO_set_ssl(bio, conn->proxy_ssl[sockindex].handle, FALSE);
2186 SSL_set_bio(connssl->handle, bio, bio);
2188 else if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
2189 /* pass the raw socket into the SSL layers */
2190 failf(data, "SSL: SSL_set_fd failed: %s",
2191 ERR_error_string(ERR_get_error(), NULL));
2192 return CURLE_SSL_CONNECT_ERROR;
2195 connssl->connecting_state = ssl_connect_2;
2200 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2202 struct Curl_easy *data = conn->data;
2204 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2205 long * const certverifyresult = SSL_IS_PROXY() ?
2206 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2207 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2208 || ssl_connect_2_reading == connssl->connecting_state
2209 || ssl_connect_2_writing == connssl->connecting_state);
2213 err = SSL_connect(connssl->handle);
2216 0 is "not successful but was shut down controlled"
2217 <0 is "handshake was not successful, because a fatal error occurred" */
2219 int detail = SSL_get_error(connssl->handle, err);
2221 if(SSL_ERROR_WANT_READ == detail) {
2222 connssl->connecting_state = ssl_connect_2_reading;
2225 else if(SSL_ERROR_WANT_WRITE == detail) {
2226 connssl->connecting_state = ssl_connect_2_writing;
2230 /* untreated error */
2231 unsigned long errdetail;
2232 char error_buffer[256]=""; /* OpenSSL documents that this must be at
2233 least 256 bytes long. */
2239 /* the connection failed, we're not waiting for anything else. */
2240 connssl->connecting_state = ssl_connect_2;
2242 /* Get the earliest error code from the thread's error queue and removes
2244 errdetail = ERR_get_error();
2246 /* Extract which lib and reason */
2247 lib = ERR_GET_LIB(errdetail);
2248 reason = ERR_GET_REASON(errdetail);
2250 if((lib == ERR_LIB_SSL) &&
2251 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2252 result = CURLE_SSL_CACERT;
2254 lerr = SSL_get_verify_result(connssl->handle);
2255 if(lerr != X509_V_OK) {
2256 *certverifyresult = lerr;
2257 snprintf(error_buffer, sizeof(error_buffer),
2258 "SSL certificate problem: %s",
2259 X509_verify_cert_error_string(lerr));
2262 /* strcpy() is fine here as long as the string fits within
2264 strcpy(error_buffer, "SSL certificate verification failed");
2267 result = CURLE_SSL_CONNECT_ERROR;
2268 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
2271 /* detail is already set to the SSL error above */
2273 /* If we e.g. use SSLv2 request-method and the server doesn't like us
2274 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
2275 * the SO_ERROR is also lost.
2277 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
2278 const char * const hostname = SSL_IS_PROXY() ?
2279 conn->http_proxy.host.name : conn->host.name;
2280 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
2281 failf(data, "Unknown SSL protocol error in connection to %s:%ld ",
2286 /* Could be a CERT problem */
2287 failf(data, "%s", error_buffer);
2293 /* we have been connected fine, we're not waiting for anything else. */
2294 connssl->connecting_state = ssl_connect_3;
2296 /* Informational message */
2297 infof(data, "SSL connection using %s / %s\n",
2298 get_ssl_version_txt(connssl->handle),
2299 SSL_get_cipher(connssl->handle));
2302 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
2305 if(conn->bits.tls_enable_alpn) {
2306 const unsigned char *neg_protocol;
2308 SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
2310 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
2313 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
2314 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
2315 conn->negnpn = CURL_HTTP_VERSION_2;
2319 if(len == ALPN_HTTP_1_1_LENGTH &&
2320 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
2321 conn->negnpn = CURL_HTTP_VERSION_1_1;
2325 infof(data, "ALPN, server did not agree to a protocol\n");
2333 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
2339 return 1; /* buffer too big */
2341 i = i2t_ASN1_OBJECT(buf, ilen, a);
2344 return 1; /* buffer too small */
2349 #define push_certinfo(_label, _num) \
2351 long info_len = BIO_get_mem_data(mem, &ptr); \
2352 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
2353 if(1!=BIO_reset(mem)) \
2357 static void pubkey_show(struct Curl_easy *data,
2362 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2370 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
2374 push_certinfo(namebuf, num);
2377 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2378 #define print_pubkey_BN(_type, _name, _num) \
2379 pubkey_show(data, mem, _num, #_type, #_name, _name)
2382 #define print_pubkey_BN(_type, _name, _num) \
2384 if(_type->_name) { \
2385 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
2390 static int X509V3_ext(struct Curl_easy *data,
2392 CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
2397 if((int)sk_X509_EXTENSION_num(exts) <= 0)
2398 /* no extensions, bail out */
2401 for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
2403 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2408 BIO *bio_out = BIO_new(BIO_s_mem());
2413 obj = X509_EXTENSION_get_object(ext);
2415 asn1_object_dump(obj, namebuf, sizeof(namebuf));
2417 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
2418 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
2420 BIO_get_mem_ptr(bio_out, &biomem);
2422 for(j = 0; j < (size_t)biomem->length; j++) {
2424 if(biomem->data[j] == '\n') {
2426 j++; /* skip the newline */
2428 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
2430 if(j<(size_t)biomem->length)
2431 ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
2435 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
2440 return 0; /* all is fine */
2443 static CURLcode get_cert_chain(struct connectdata *conn,
2444 struct ssl_connect_data *connssl)
2450 struct Curl_easy *data = conn->data;
2454 sk = SSL_get_peer_cert_chain(connssl->handle);
2456 return CURLE_OUT_OF_MEMORY;
2459 numcerts = sk_X509_num(sk);
2461 result = Curl_ssl_init_certinfo(data, numcerts);
2466 mem = BIO_new(BIO_s_mem());
2468 for(i = 0; i < numcerts; i++) {
2470 X509 *x = sk_X509_value(sk, i);
2471 EVP_PKEY *pubkey=NULL;
2474 CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
2476 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
2477 push_certinfo("Subject", i);
2479 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
2480 push_certinfo("Issuer", i);
2482 BIO_printf(mem, "%lx", X509_get_version(x));
2483 push_certinfo("Version", i);
2485 num = X509_get_serialNumber(x);
2486 if(num->type == V_ASN1_NEG_INTEGER)
2488 for(j = 0; j < num->length; j++)
2489 BIO_printf(mem, "%02x", num->data[j]);
2490 push_certinfo("Serial Number", i);
2492 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
2494 const X509_ALGOR *palg = NULL;
2495 ASN1_STRING *a = ASN1_STRING_new();
2497 X509_get0_signature(&psig, &palg, x);
2498 X509_signature_print(mem, palg, a);
2499 ASN1_STRING_free(a);
2502 i2a_ASN1_OBJECT(mem, palg->algorithm);
2503 push_certinfo("Public Key Algorithm", i);
2506 X509V3_ext(data, i, X509_get0_extensions(x));
2510 /* before OpenSSL 1.0.2 */
2511 X509_CINF *cinf = x->cert_info;
2513 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
2514 push_certinfo("Signature Algorithm", i);
2516 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
2517 push_certinfo("Public Key Algorithm", i);
2519 X509V3_ext(data, i, cinf->extensions);
2521 psig = x->signature;
2525 ASN1_TIME_print(mem, X509_get0_notBefore(x));
2526 push_certinfo("Start date", i);
2528 ASN1_TIME_print(mem, X509_get0_notAfter(x));
2529 push_certinfo("Expire date", i);
2531 pubkey = X509_get_pubkey(x);
2533 infof(data, " Unable to load public key\n");
2536 #ifdef HAVE_OPAQUE_EVP_PKEY
2537 pktype = EVP_PKEY_id(pubkey);
2539 pktype = pubkey->type;
2545 #ifdef HAVE_OPAQUE_EVP_PKEY
2546 rsa = EVP_PKEY_get0_RSA(pubkey);
2548 rsa = pubkey->pkey.rsa;
2551 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2562 RSA_get0_key(rsa, &n, &e, &d);
2563 RSA_get0_factors(rsa, &p, &q);
2564 RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
2566 push_certinfo("RSA Public Key", i);
2567 print_pubkey_BN(rsa, n, i);
2568 print_pubkey_BN(rsa, e, i);
2569 print_pubkey_BN(rsa, d, i);
2570 print_pubkey_BN(rsa, p, i);
2571 print_pubkey_BN(rsa, q, i);
2572 print_pubkey_BN(rsa, dmp1, i);
2573 print_pubkey_BN(rsa, dmq1, i);
2574 print_pubkey_BN(rsa, iqmp, i);
2577 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
2578 push_certinfo("RSA Public Key", i);
2579 print_pubkey_BN(rsa, n, i);
2580 print_pubkey_BN(rsa, e, i);
2581 print_pubkey_BN(rsa, d, i);
2582 print_pubkey_BN(rsa, p, i);
2583 print_pubkey_BN(rsa, q, i);
2584 print_pubkey_BN(rsa, dmp1, i);
2585 print_pubkey_BN(rsa, dmq1, i);
2586 print_pubkey_BN(rsa, iqmp, i);
2594 #ifdef HAVE_OPAQUE_EVP_PKEY
2595 dsa = EVP_PKEY_get0_DSA(pubkey);
2597 dsa = pubkey->pkey.dsa;
2599 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2604 const BIGNUM *priv_key;
2605 const BIGNUM *pub_key;
2607 DSA_get0_pqg(dsa, &p, &q, &g);
2608 DSA_get0_key(dsa, &pub_key, &priv_key);
2610 print_pubkey_BN(dsa, p, i);
2611 print_pubkey_BN(dsa, q, i);
2612 print_pubkey_BN(dsa, g, i);
2613 print_pubkey_BN(dsa, priv_key, i);
2614 print_pubkey_BN(dsa, pub_key, i);
2617 print_pubkey_BN(dsa, p, i);
2618 print_pubkey_BN(dsa, q, i);
2619 print_pubkey_BN(dsa, g, i);
2620 print_pubkey_BN(dsa, priv_key, i);
2621 print_pubkey_BN(dsa, pub_key, i);
2628 #ifdef HAVE_OPAQUE_EVP_PKEY
2629 dh = EVP_PKEY_get0_DH(pubkey);
2631 dh = pubkey->pkey.dh;
2633 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2638 const BIGNUM *priv_key;
2639 const BIGNUM *pub_key;
2640 DH_get0_pqg(dh, &p, &q, &g);
2641 DH_get0_key(dh, &pub_key, &priv_key);
2642 print_pubkey_BN(dh, p, i);
2643 print_pubkey_BN(dh, q, i);
2644 print_pubkey_BN(dh, g, i);
2645 print_pubkey_BN(dh, priv_key, i);
2646 print_pubkey_BN(dh, pub_key, i);
2649 print_pubkey_BN(dh, p, i);
2650 print_pubkey_BN(dh, g, i);
2651 print_pubkey_BN(dh, priv_key, i);
2652 print_pubkey_BN(dh, pub_key, i);
2657 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2662 EVP_PKEY_free(pubkey);
2666 for(j = 0; j < psig->length; j++)
2667 BIO_printf(mem, "%02x:", psig->data[j]);
2668 push_certinfo("Signature", i);
2671 PEM_write_bio_X509(mem, x);
2672 push_certinfo("Cert", i);
2681 * Heavily modified from:
2682 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
2684 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
2685 const char *pinnedpubkey)
2688 int len1 = 0, len2 = 0;
2689 unsigned char *buff1 = NULL, *temp = NULL;
2691 /* Result is returned to caller */
2692 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
2694 /* if a path wasn't specified, don't pin */
2702 /* Begin Gyrations to get the subjectPublicKeyInfo */
2703 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
2705 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
2706 /thread/d61858dae102c6c7 */
2707 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
2711 /* https://www.openssl.org/docs/crypto/buffer.html */
2712 buff1 = temp = malloc(len1);
2716 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
2717 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
2720 * These checks are verifying we got back the same values as when we
2721 * sized the buffer. It's pretty weak since they should always be the
2722 * same. But it gives us something to test.
2724 if((len1 != len2) || !temp || ((temp - buff1) != len1))
2729 /* The one good exit point */
2730 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
2733 /* https://www.openssl.org/docs/crypto/buffer.html */
2741 * Get the server cert, verify it and show it etc, only call failf() if the
2742 * 'strict' argument is TRUE as otherwise all this is for informational
2745 * We check certificates to authenticate the server; otherwise we risk
2746 * man-in-the-middle attack.
2748 static CURLcode servercert(struct connectdata *conn,
2749 struct ssl_connect_data *connssl,
2752 CURLcode result = CURLE_OK;
2755 struct Curl_easy *data = conn->data;
2758 char *buffer = data->state.buffer;
2760 long * const certverifyresult = SSL_IS_PROXY() ?
2761 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2762 BIO *mem = BIO_new(BIO_s_mem());
2764 if(data->set.ssl.certinfo)
2765 /* we've been asked to gather certificate info! */
2766 (void)get_cert_chain(conn, connssl);
2768 connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
2769 if(!connssl->server_cert) {
2773 failf(data, "SSL: couldn't get peer certificate!");
2774 return CURLE_PEER_FAILED_VERIFICATION;
2777 infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
2779 rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
2781 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
2783 ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
2784 len = BIO_get_mem_data(mem, (char **) &ptr);
2785 infof(data, " start date: %.*s\n", len, ptr);
2786 rc = BIO_reset(mem);
2788 ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
2789 len = BIO_get_mem_data(mem, (char **) &ptr);
2790 infof(data, " expire date: %.*s\n", len, ptr);
2791 rc = BIO_reset(mem);
2795 if(SSL_CONN_CONFIG(verifyhost)) {
2796 result = verifyhost(conn, connssl->server_cert);
2798 X509_free(connssl->server_cert);
2799 connssl->server_cert = NULL;
2804 rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
2808 failf(data, "SSL: couldn't get X509-issuer name!");
2809 result = CURLE_SSL_CONNECT_ERROR;
2812 infof(data, " issuer: %s\n", buffer);
2814 /* We could do all sorts of certificate verification stuff here before
2815 deallocating the certificate. */
2817 /* e.g. match issuer name with provided issuer certificate */
2818 if(SSL_SET_OPTION(issuercert)) {
2819 fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
2822 failf(data, "SSL: Unable to open issuer cert (%s)",
2823 SSL_SET_OPTION(issuercert));
2824 X509_free(connssl->server_cert);
2825 connssl->server_cert = NULL;
2826 return CURLE_SSL_ISSUER_ERROR;
2829 issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
2832 failf(data, "SSL: Unable to read issuer cert (%s)",
2833 SSL_SET_OPTION(issuercert));
2834 X509_free(connssl->server_cert);
2837 return CURLE_SSL_ISSUER_ERROR;
2842 if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
2844 failf(data, "SSL: Certificate issuer check failed (%s)",
2845 SSL_SET_OPTION(issuercert));
2846 X509_free(connssl->server_cert);
2848 connssl->server_cert = NULL;
2849 return CURLE_SSL_ISSUER_ERROR;
2852 infof(data, " SSL certificate issuer check ok (%s)\n",
2853 SSL_SET_OPTION(issuercert));
2857 lerr = *certverifyresult = SSL_get_verify_result(connssl->handle);
2859 if(*certverifyresult != X509_V_OK) {
2860 if(SSL_CONN_CONFIG(verifypeer)) {
2861 /* We probably never reach this, because SSL_connect() will fail
2862 and we return earlier if verifypeer is set? */
2864 failf(data, "SSL certificate verify result: %s (%ld)",
2865 X509_verify_cert_error_string(lerr), lerr);
2866 result = CURLE_PEER_FAILED_VERIFICATION;
2869 infof(data, " SSL certificate verify result: %s (%ld),"
2870 " continuing anyway.\n",
2871 X509_verify_cert_error_string(lerr), lerr);
2874 infof(data, " SSL certificate verify ok.\n");
2877 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2878 !defined(OPENSSL_NO_OCSP)
2879 if(SSL_CONN_CONFIG(verifystatus)) {
2880 result = verifystatus(conn, connssl);
2882 X509_free(connssl->server_cert);
2883 connssl->server_cert = NULL;
2890 /* when not strict, we don't bother about the verify cert problems */
2893 ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
2894 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
2895 if(!result && ptr) {
2896 result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
2898 failf(data, "SSL: public key does not match pinned public key!");
2901 X509_free(connssl->server_cert);
2902 connssl->server_cert = NULL;
2903 connssl->connecting_state = ssl_connect_done;
2908 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
2910 CURLcode result = CURLE_OK;
2911 struct Curl_easy *data = conn->data;
2912 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2914 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
2916 if(data->set.general_ssl.sessionid) {
2918 SSL_SESSION *our_ssl_sessionid;
2919 void *old_ssl_sessionid = NULL;
2921 our_ssl_sessionid = SSL_get1_session(connssl->handle);
2923 /* SSL_get1_session() will increment the reference count and the session
2924 will stay in memory until explicitly freed with SSL_SESSION_free(3),
2925 regardless of its state. */
2927 Curl_ssl_sessionid_lock(conn);
2928 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
2931 if(old_ssl_sessionid != our_ssl_sessionid) {
2932 infof(data, "old SSL session ID is stale, removing\n");
2933 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
2939 result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
2940 0 /* unknown size */, sockindex);
2942 Curl_ssl_sessionid_unlock(conn);
2943 failf(data, "failed to store ssl session");
2948 /* Session was incache, so refcount already incremented earlier.
2949 * Avoid further increments with each SSL_get1_session() call.
2950 * This does not free the session as refcount remains > 0
2952 SSL_SESSION_free(our_ssl_sessionid);
2954 Curl_ssl_sessionid_unlock(conn);
2958 * We check certificates to authenticate the server; otherwise we risk
2959 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
2960 * verify the peer ignore faults and failures from the server cert
2964 result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
2965 SSL_CONN_CONFIG(verifyhost)));
2968 connssl->connecting_state = ssl_connect_done;
2973 static Curl_recv ossl_recv;
2974 static Curl_send ossl_send;
2976 static CURLcode ossl_connect_common(struct connectdata *conn,
2982 struct Curl_easy *data = conn->data;
2983 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2984 curl_socket_t sockfd = conn->sock[sockindex];
2988 /* check if the connection has already been established */
2989 if(ssl_connection_complete == connssl->state) {
2994 if(ssl_connect_1 == connssl->connecting_state) {
2995 /* Find out how much more time we're allowed */
2996 timeout_ms = Curl_timeleft(data, NULL, TRUE);
2998 if(timeout_ms < 0) {
2999 /* no need to continue if time already is up */
3000 failf(data, "SSL connection timeout");
3001 return CURLE_OPERATION_TIMEDOUT;
3004 result = ossl_connect_step1(conn, sockindex);
3009 while(ssl_connect_2 == connssl->connecting_state ||
3010 ssl_connect_2_reading == connssl->connecting_state ||
3011 ssl_connect_2_writing == connssl->connecting_state) {
3013 /* check allowed time left */
3014 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3016 if(timeout_ms < 0) {
3017 /* no need to continue if time already is up */
3018 failf(data, "SSL connection timeout");
3019 return CURLE_OPERATION_TIMEDOUT;
3022 /* if ssl is expecting something, check if it's available. */
3023 if(connssl->connecting_state == ssl_connect_2_reading ||
3024 connssl->connecting_state == ssl_connect_2_writing) {
3026 curl_socket_t writefd = ssl_connect_2_writing==
3027 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3028 curl_socket_t readfd = ssl_connect_2_reading==
3029 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3031 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
3032 nonblocking?0:timeout_ms);
3035 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
3036 return CURLE_SSL_CONNECT_ERROR;
3038 else if(0 == what) {
3045 failf(data, "SSL connection timeout");
3046 return CURLE_OPERATION_TIMEDOUT;
3049 /* socket is readable or writable */
3052 /* Run transaction, and return to the caller if it failed or if this
3053 * connection is done nonblocking and this loop would execute again. This
3054 * permits the owner of a multi handle to abort a connection attempt
3055 * before step2 has completed while ensuring that a client using select()
3056 * or epoll() will always have a valid fdset to wait on.
3058 result = ossl_connect_step2(conn, sockindex);
3059 if(result || (nonblocking &&
3060 (ssl_connect_2 == connssl->connecting_state ||
3061 ssl_connect_2_reading == connssl->connecting_state ||
3062 ssl_connect_2_writing == connssl->connecting_state)))
3065 } /* repeat step2 until all transactions are done. */
3067 if(ssl_connect_3 == connssl->connecting_state) {
3068 result = ossl_connect_step3(conn, sockindex);
3073 if(ssl_connect_done == connssl->connecting_state) {
3074 connssl->state = ssl_connection_complete;
3075 conn->recv[sockindex] = ossl_recv;
3076 conn->send[sockindex] = ossl_send;
3082 /* Reset our connect state machine */
3083 connssl->connecting_state = ssl_connect_1;
3088 CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
3092 return ossl_connect_common(conn, sockindex, TRUE, done);
3095 CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
3100 result = ossl_connect_common(conn, sockindex, FALSE, &done);
3109 bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
3111 if(conn->ssl[connindex].handle)
3113 return (0 != SSL_pending(conn->ssl[connindex].handle) ||
3114 (conn->proxy_ssl[connindex].handle &&
3115 0 != SSL_pending(conn->proxy_ssl[connindex].handle))) ?
3121 static ssize_t ossl_send(struct connectdata *conn,
3127 /* SSL_write() is said to return 'int' while write() and send() returns
3130 char error_buffer[256]; /* OpenSSL documents that this must be at least 256
3132 unsigned long sslerror;
3138 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3139 rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
3142 err = SSL_get_error(conn->ssl[sockindex].handle, rc);
3145 case SSL_ERROR_WANT_READ:
3146 case SSL_ERROR_WANT_WRITE:
3147 /* The operation did not complete; the same TLS/SSL I/O function
3148 should be called again later. This is basically an EWOULDBLOCK
3150 *curlcode = CURLE_AGAIN;
3152 case SSL_ERROR_SYSCALL:
3153 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
3155 *curlcode = CURLE_SEND_ERROR;
3158 /* A failure in the SSL library occurred, usually a protocol error.
3159 The OpenSSL error queue contains more information on the error. */
3160 sslerror = ERR_get_error();
3161 if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
3162 ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
3163 conn->ssl[sockindex].state == ssl_connection_complete &&
3164 conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
3166 Curl_ossl_version(ver, 120);
3167 failf(conn->data, "Error: %s does not support double SSL tunneling.",
3171 failf(conn->data, "SSL_write() error: %s",
3172 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
3173 *curlcode = CURLE_SEND_ERROR;
3177 failf(conn->data, "SSL_write() return error %d", err);
3178 *curlcode = CURLE_SEND_ERROR;
3181 *curlcode = CURLE_OK;
3182 return (ssize_t)rc; /* number of bytes */
3185 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3186 int num, /* socketindex */
3187 char *buf, /* store read data here */
3188 size_t buffersize, /* max amount to read */
3191 char error_buffer[256]; /* OpenSSL documents that this must be at
3192 least 256 bytes long. */
3193 unsigned long sslerror;
3199 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3200 nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
3202 /* failed SSL_read */
3203 int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
3206 case SSL_ERROR_NONE: /* this is not an error */
3207 case SSL_ERROR_ZERO_RETURN: /* no more data */
3209 case SSL_ERROR_WANT_READ:
3210 case SSL_ERROR_WANT_WRITE:
3211 /* there's data pending, re-invoke SSL_read() */
3212 *curlcode = CURLE_AGAIN;
3215 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3217 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3218 sslerror = ERR_get_error();
3219 if((nread < 0) || sslerror) {
3220 /* If the return code was negative or there actually is an error in the
3222 failf(conn->data, "SSL read: %s, errno %d",
3223 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)),
3225 *curlcode = CURLE_RECV_ERROR;
3233 size_t Curl_ossl_version(char *buffer, size_t size)
3235 #ifdef OPENSSL_IS_BORINGSSL
3236 return snprintf(buffer, size, OSSL_PACKAGE);
3237 #else /* OPENSSL_IS_BORINGSSL */
3239 unsigned long ssleay_value;
3242 ssleay_value=OpenSSL_version_num();
3243 if(ssleay_value < 0x906000) {
3244 ssleay_value=SSLEAY_VERSION_NUMBER;
3248 if(ssleay_value&0xff0) {
3249 int minor_ver = (ssleay_value >> 4) & 0xff;
3250 if(minor_ver > 26) {
3251 /* handle extended version introduced for 0.9.8za */
3252 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
3256 sub[0] = (char) (minor_ver + 'a' - 1);
3263 return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
3265 (ssleay_value>>28)&0xf,
3266 (ssleay_value>>20)&0xff,
3267 (ssleay_value>>12)&0xff,
3269 #endif /* OPENSSL_IS_BORINGSSL */
3272 /* can be called with data == NULL */
3273 CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
3278 if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
3279 return CURLE_FAILED_INIT; /* couldn't seed for some reason */
3283 return CURLE_FAILED_INIT;
3285 /* RAND_bytes() returns 1 on success, 0 otherwise. */
3286 rc = RAND_bytes(entropy, curlx_uztosi(length));
3287 return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
3290 void Curl_ossl_md5sum(unsigned char *tmp, /* input */
3292 unsigned char *md5sum /* output */,
3298 MD5_Update(&MD5pw, tmp, tmplen);
3299 MD5_Final(md5sum, &MD5pw);
3302 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3303 void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
3305 unsigned char *sha256sum /* output */,
3308 SHA256_CTX SHA256pw;
3310 SHA256_Init(&SHA256pw);
3311 SHA256_Update(&SHA256pw, tmp, tmplen);
3312 SHA256_Final(sha256sum, &SHA256pw);
3316 bool Curl_ossl_cert_status_request(void)
3318 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3319 !defined(OPENSSL_NO_OCSP)
3325 #endif /* USE_OPENSSL */