1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2018, 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"
41 #include "formdata.h" /* for the boundary function */
42 #include "url.h" /* for the ssl config check function */
43 #include "inet_pton.h"
50 #include "hostcheck.h"
51 #include "curl_printf.h"
52 #include <openssl/ssl.h>
53 #ifdef HAVE_OPENSSL_ENGINE_H
54 #include <openssl/engine.h>
56 #include <openssl/rand.h>
57 #include <openssl/x509v3.h>
58 #ifndef OPENSSL_NO_DSA
59 #include <openssl/dsa.h>
61 #include <openssl/dh.h>
62 #include <openssl/err.h>
63 #include <openssl/md5.h>
64 #include <openssl/conf.h>
65 #include <openssl/bn.h>
66 #include <openssl/rsa.h>
67 #include <openssl/bio.h>
68 #include <openssl/buffer.h>
69 #include <openssl/pkcs12.h>
71 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
72 #include <openssl/ocsp.h>
76 #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
78 /* The last #include files should be: */
79 #include "curl_memory.h"
82 #ifndef OPENSSL_VERSION_NUMBER
83 #error "OPENSSL_VERSION_NUMBER not defined"
86 #if defined(HAVE_OPENSSL_ENGINE_H)
87 #include <openssl/ui.h>
90 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
91 #define SSL_METHOD_QUAL const
93 #define SSL_METHOD_QUAL
96 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
97 #define HAVE_ERR_REMOVE_THREAD_STATE 1
100 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
101 OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
102 #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
103 #define OPENSSL_NO_SSL2
106 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
107 !defined(LIBRESSL_VERSION_NUMBER)
108 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
109 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
110 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
111 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
112 #define CONST_EXTS 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 #ifdef LIBRESSL_VERSION_NUMBER
121 static unsigned long OpenSSL_version_num(void)
123 return LIBRESSL_VERSION_NUMBER;
126 #define OpenSSL_version_num() SSLeay()
130 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
131 !defined(LIBRESSL_VERSION_NUMBER)
132 #define HAVE_X509_GET0_SIGNATURE 1
135 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
136 OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
137 !defined(OPENSSL_NO_COMP)
138 #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
141 #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
142 /* not present in older OpenSSL */
143 #define OPENSSL_load_builtin_modules(x)
147 * Whether SSL_CTX_set_keylog_callback is available.
148 * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
149 * BoringSSL: supported since d28f59c27bac (committed 2015-11-19)
150 * LibreSSL: unsupported in at least 2.5.1 (explicitly check for it since it
151 * lies and pretends to be OpenSSL 2.0.0).
153 #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
154 !defined(LIBRESSL_VERSION_NUMBER)) || \
155 defined(OPENSSL_IS_BORINGSSL)
156 #define HAVE_KEYLOG_CALLBACK
159 #if defined(LIBRESSL_VERSION_NUMBER)
160 #define OSSL_PACKAGE "LibreSSL"
161 #elif defined(OPENSSL_IS_BORINGSSL)
162 #define OSSL_PACKAGE "BoringSSL"
164 #define OSSL_PACKAGE "OpenSSL"
167 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
168 /* up2date versions of OpenSSL maintain the default reasonably secure without
169 * breaking compatibility, so it is better not to override the default by curl
171 #define DEFAULT_CIPHER_SELECTION NULL
173 /* ... but it is not the case with old versions of OpenSSL */
174 #define DEFAULT_CIPHER_SELECTION \
175 "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
178 #define ENABLE_SSLKEYLOGFILE
180 #ifdef ENABLE_SSLKEYLOGFILE
181 typedef struct ssl_tap_state {
182 int master_key_length;
183 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
184 unsigned char client_random[SSL3_RANDOM_SIZE];
186 #endif /* ENABLE_SSLKEYLOGFILE */
188 struct ssl_backend_data {
189 /* these ones requires specific SSL-types */
193 #ifdef ENABLE_SSLKEYLOGFILE
194 /* tap_state holds the last seen master key if we're logging them */
195 ssl_tap_state_t tap_state;
199 #define BACKEND connssl->backend
202 * Number of bytes to read from the random number seed file. This must be
203 * a finite value (because some entropy "files" like /dev/urandom have
204 * an infinite length), but must be large enough to provide enough
205 * entropy to properly seed OpenSSL's PRNG.
207 #define RAND_LOAD_LENGTH 1024
209 #ifdef ENABLE_SSLKEYLOGFILE
210 /* The fp for the open SSLKEYLOGFILE, or NULL if not open */
211 static FILE *keylog_file_fp;
213 #ifdef HAVE_KEYLOG_CALLBACK
214 static void ossl_keylog_callback(const SSL *ssl, const char *line)
218 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
219 may not be thread-safe. */
220 if(keylog_file_fp && line && *line) {
223 size_t linelen = strlen(line);
225 if(linelen <= sizeof(stackbuf) - 2)
228 buf = malloc(linelen + 2);
232 strncpy(buf, line, linelen);
234 buf[linelen + 1] = '\0';
236 fputs(buf, keylog_file_fp);
242 #define KEYLOG_PREFIX "CLIENT_RANDOM "
243 #define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1)
245 * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL
246 * being used doesn't have native support for doing that.
248 static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state)
250 const char *hex = "0123456789ABCDEF";
252 char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 +
253 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1];
254 const SSL_SESSION *session = SSL_get_session(ssl);
255 unsigned char client_random[SSL3_RANDOM_SIZE];
256 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
257 int master_key_length = 0;
259 if(!session || !keylog_file_fp)
262 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
263 /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
264 * we have a valid SSL context if we have a non-NULL session. */
265 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
266 master_key_length = (int)
267 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
269 if(ssl->s3 && session->master_key_length > 0) {
270 master_key_length = session->master_key_length;
271 memcpy(master_key, session->master_key, session->master_key_length);
272 memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
276 if(master_key_length <= 0)
279 /* Skip writing keys if there is no key or it did not change. */
280 if(state->master_key_length == master_key_length &&
281 !memcmp(state->master_key, master_key, master_key_length) &&
282 !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) {
286 state->master_key_length = master_key_length;
287 memcpy(state->master_key, master_key, master_key_length);
288 memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE);
290 memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN);
291 pos = KEYLOG_PREFIX_LEN;
293 /* Client Random for SSLv3/TLS */
294 for(i = 0; i < SSL3_RANDOM_SIZE; i++) {
295 line[pos++] = hex[client_random[i] >> 4];
296 line[pos++] = hex[client_random[i] & 0xF];
300 /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */
301 for(i = 0; i < master_key_length; i++) {
302 line[pos++] = hex[master_key[i] >> 4];
303 line[pos++] = hex[master_key[i] & 0xF];
308 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
309 may not be thread-safe. */
310 fputs(line, keylog_file_fp);
312 #endif /* !HAVE_KEYLOG_CALLBACK */
313 #endif /* ENABLE_SSLKEYLOGFILE */
315 static const char *SSL_ERROR_to_str(int err)
319 return "SSL_ERROR_NONE";
321 return "SSL_ERROR_SSL";
322 case SSL_ERROR_WANT_READ:
323 return "SSL_ERROR_WANT_READ";
324 case SSL_ERROR_WANT_WRITE:
325 return "SSL_ERROR_WANT_WRITE";
326 case SSL_ERROR_WANT_X509_LOOKUP:
327 return "SSL_ERROR_WANT_X509_LOOKUP";
328 case SSL_ERROR_SYSCALL:
329 return "SSL_ERROR_SYSCALL";
330 case SSL_ERROR_ZERO_RETURN:
331 return "SSL_ERROR_ZERO_RETURN";
332 case SSL_ERROR_WANT_CONNECT:
333 return "SSL_ERROR_WANT_CONNECT";
334 case SSL_ERROR_WANT_ACCEPT:
335 return "SSL_ERROR_WANT_ACCEPT";
336 #if defined(SSL_ERROR_WANT_ASYNC)
337 case SSL_ERROR_WANT_ASYNC:
338 return "SSL_ERROR_WANT_ASYNC";
340 #if defined(SSL_ERROR_WANT_ASYNC_JOB)
341 case SSL_ERROR_WANT_ASYNC_JOB:
342 return "SSL_ERROR_WANT_ASYNC_JOB";
344 #if defined(SSL_ERROR_WANT_EARLY)
345 case SSL_ERROR_WANT_EARLY:
346 return "SSL_ERROR_WANT_EARLY";
349 return "SSL_ERROR unknown";
353 /* Return error string for last OpenSSL error
355 static char *ossl_strerror(unsigned long error, char *buf, size_t size)
357 ERR_error_string_n(error, buf, size);
361 static int passwd_callback(char *buf, int num, int encrypting,
364 DEBUGASSERT(0 == encrypting);
367 int klen = curlx_uztosi(strlen((char *)global_passwd));
369 memcpy(buf, global_passwd, klen + 1);
377 * rand_enough() returns TRUE if we have seeded the random engine properly.
379 static bool rand_enough(void)
381 return (0 != RAND_status()) ? TRUE : FALSE;
384 static CURLcode Curl_ossl_seed(struct Curl_easy *data)
386 /* we have the "SSL is seeded" boolean static to prevent multiple
387 time-consuming seedings in vain */
388 static bool ssl_seeded = FALSE;
395 /* OpenSSL 1.1.0+ will return here */
401 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
403 if(data->set.str[STRING_SSL_RANDOM_FILE])
404 #define RANDOM_FILE "" /* doesn't matter won't be used */
407 /* let the option override the define */
408 RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
409 data->set.str[STRING_SSL_RANDOM_FILE]:
416 #if defined(HAVE_RAND_EGD)
417 /* only available in OpenSSL 0.9.5 and later */
418 /* EGD_SOCKET is set at configure time or not at all */
420 /* If we don't have the define set, we only do this if the egd-option
422 if(data->set.str[STRING_SSL_EGDSOCKET])
423 #define EGD_SOCKET "" /* doesn't matter won't be used */
426 /* If there's an option and a define, the option overrides the
428 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
429 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
437 /* fallback to a custom seeding of the PRNG using a hash based on a current
440 unsigned char randb[64];
441 size_t len = sizeof(randb);
443 for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
444 struct curltime tv = Curl_now();
447 tv.tv_usec *= (unsigned int)i + 2;
448 tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) *
450 tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec +
451 Curl_now().tv_usec) *
453 memcpy(&randb[i * sizeof(struct curltime)], &tv,
454 sizeof(struct curltime));
456 RAND_add(randb, (int)len, (double)len/2);
457 } while(!rand_enough());
459 /* generates a default path for the random seed file */
460 fname[0] = 0; /* blank it first */
461 RAND_file_name(fname, sizeof(fname));
463 /* we got a file name to try */
464 RAND_load_file(fname, RAND_LOAD_LENGTH);
469 infof(data, "libcurl is now using a weak random seed!\n");
470 return (rand_enough() ? CURLE_OK :
471 CURLE_SSL_CONNECT_ERROR /* confusing error code */);
474 #ifndef SSL_FILETYPE_ENGINE
475 #define SSL_FILETYPE_ENGINE 42
477 #ifndef SSL_FILETYPE_PKCS12
478 #define SSL_FILETYPE_PKCS12 43
480 static int do_file_type(const char *type)
482 if(!type || !type[0])
483 return SSL_FILETYPE_PEM;
484 if(strcasecompare(type, "PEM"))
485 return SSL_FILETYPE_PEM;
486 if(strcasecompare(type, "DER"))
487 return SSL_FILETYPE_ASN1;
488 if(strcasecompare(type, "ENG"))
489 return SSL_FILETYPE_ENGINE;
490 if(strcasecompare(type, "P12"))
491 return SSL_FILETYPE_PKCS12;
495 #if defined(HAVE_OPENSSL_ENGINE_H)
497 * Supply default password to the engine user interface conversation.
498 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
499 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
501 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
503 const char *password;
504 switch(UI_get_string_type(uis)) {
507 password = (const char *)UI_get0_user_data(ui);
508 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
509 UI_set_result(ui, uis, password);
515 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
519 * Suppress interactive request for a default password if available.
521 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
523 switch(UI_get_string_type(uis)) {
526 if(UI_get0_user_data(ui) &&
527 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
533 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
538 int cert_stuff(struct connectdata *conn,
541 const char *cert_type,
543 const char *key_type,
546 struct Curl_easy *data = conn->data;
547 char error_buffer[256];
548 bool check_privkey = TRUE;
550 int file_type = do_file_type(cert_type);
552 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
558 /* set the password in the callback userdata */
559 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
560 /* Set passwd callback: */
561 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
566 case SSL_FILETYPE_PEM:
567 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
568 if(SSL_CTX_use_certificate_chain_file(ctx,
571 "could not load PEM client certificate, " OSSL_PACKAGE
573 "(no key found, wrong pass phrase, or wrong file format?)",
574 ossl_strerror(ERR_get_error(), error_buffer,
575 sizeof(error_buffer)) );
580 case SSL_FILETYPE_ASN1:
581 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
582 we use the case above for PEM so this can only be performed with
584 if(SSL_CTX_use_certificate_file(ctx,
588 "could not load ASN1 client certificate, " OSSL_PACKAGE
590 "(no key found, wrong pass phrase, or wrong file format?)",
591 ossl_strerror(ERR_get_error(), error_buffer,
592 sizeof(error_buffer)) );
596 case SSL_FILETYPE_ENGINE:
597 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
599 if(data->state.engine) {
600 const char *cmd_name = "LOAD_CERT_CTRL";
606 params.cert_id = cert_file;
609 /* Does the engine supports LOAD_CERT_CTRL ? */
610 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
611 0, (void *)cmd_name, NULL)) {
612 failf(data, "ssl engine does not support loading certificates");
616 /* Load the certificate from the engine */
617 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
618 0, ¶ms, NULL, 1)) {
619 failf(data, "ssl engine cannot load client cert with id"
620 " '%s' [%s]", cert_file,
621 ossl_strerror(ERR_get_error(), error_buffer,
622 sizeof(error_buffer)));
627 failf(data, "ssl engine didn't initialized the certificate "
632 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
633 failf(data, "unable to set client certificate");
634 X509_free(params.cert);
637 X509_free(params.cert); /* we don't need the handle any more... */
640 failf(data, "crypto engine not set, can't load certificate");
646 failf(data, "file type ENG for certificate not implemented");
650 case SSL_FILETYPE_PKCS12:
655 STACK_OF(X509) *ca = NULL;
657 f = fopen(cert_file, "rb");
659 failf(data, "could not open PKCS12 file '%s'", cert_file);
662 p12 = d2i_PKCS12_fp(f, NULL);
666 failf(data, "error reading PKCS12 file '%s'", cert_file);
672 if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
675 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
677 ossl_strerror(ERR_get_error(), error_buffer,
678 sizeof(error_buffer)) );
685 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
687 "could not load PKCS12 client certificate, " OSSL_PACKAGE
689 ossl_strerror(ERR_get_error(), error_buffer,
690 sizeof(error_buffer)) );
694 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
695 failf(data, "unable to use private key from PKCS12 file '%s'",
700 if(!SSL_CTX_check_private_key (ctx)) {
701 failf(data, "private key from PKCS12 file '%s' "
702 "does not match certificate in same file", cert_file);
705 /* Set Certificate Verification chain */
707 while(sk_X509_num(ca)) {
709 * Note that sk_X509_pop() is used below to make sure the cert is
710 * removed from the stack properly before getting passed to
711 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
712 * we used sk_X509_value() instead, but then we'd clean it in the
713 * subsequent sk_X509_pop_free() call.
715 X509 *x = sk_X509_pop(ca);
716 if(!SSL_CTX_add_client_CA(ctx, x)) {
718 failf(data, "cannot add certificate to client CA list");
721 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
723 failf(data, "cannot add certificate to certificate chain");
733 sk_X509_pop_free(ca, X509_free);
736 return 0; /* failure! */
740 failf(data, "not supported file type '%s' for certificate", cert_type);
744 file_type = do_file_type(key_type);
747 case SSL_FILETYPE_PEM:
751 /* cert & key can only be in PEM case in the same file */
752 key_file = cert_file;
754 case SSL_FILETYPE_ASN1:
755 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
756 failf(data, "unable to set private key file: '%s' type %s",
757 key_file, key_type?key_type:"PEM");
761 case SSL_FILETYPE_ENGINE:
762 #ifdef HAVE_OPENSSL_ENGINE_H
763 { /* XXXX still needs some work */
764 EVP_PKEY *priv_key = NULL;
765 if(data->state.engine) {
766 UI_METHOD *ui_method =
767 UI_create_method((char *)"curl user interface");
769 failf(data, "unable do create " OSSL_PACKAGE
770 " user-interface method");
773 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
774 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
775 UI_method_set_reader(ui_method, ssl_ui_reader);
776 UI_method_set_writer(ui_method, ssl_ui_writer);
777 /* the typecast below was added to please mingw32 */
778 priv_key = (EVP_PKEY *)
779 ENGINE_load_private_key(data->state.engine, key_file,
782 UI_destroy_method(ui_method);
784 failf(data, "failed to load private key from crypto engine");
787 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
788 failf(data, "unable to set private key");
789 EVP_PKEY_free(priv_key);
792 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
795 failf(data, "crypto engine not set, can't load private key");
801 failf(data, "file type ENG for private key not supported");
804 case SSL_FILETYPE_PKCS12:
806 failf(data, "file type P12 for private key not supported");
811 failf(data, "not supported file type for private key");
817 failf(data, "unable to create an SSL structure");
821 x509 = SSL_get_certificate(ssl);
823 /* This version was provided by Evan Jordan and is supposed to not
824 leak memory as the previous version: */
826 EVP_PKEY *pktmp = X509_get_pubkey(x509);
827 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
828 EVP_PKEY_free(pktmp);
831 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL)
833 /* If RSA is used, don't check the private key if its flags indicate
834 * it doesn't support it. */
835 EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
837 #ifdef HAVE_OPAQUE_EVP_PKEY
838 pktype = EVP_PKEY_id(priv_key);
840 pktype = priv_key->type;
842 if(pktype == EVP_PKEY_RSA) {
843 RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
844 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
845 check_privkey = FALSE;
846 RSA_free(rsa); /* Decrement reference count */
853 /* If we are using DSA, we can copy the parameters from
856 if(check_privkey == TRUE) {
857 /* Now we know that a key and cert have been set against
859 if(!SSL_CTX_check_private_key(ctx)) {
860 failf(data, "Private key does not match the certificate public key");
868 /* returns non-zero on failure */
869 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
872 return X509_NAME_oneline(a, buf, size);
874 BIO *bio_out = BIO_new(BIO_s_mem());
879 return 1; /* alloc failed! */
881 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
882 BIO_get_mem_ptr(bio_out, &biomem);
884 if((size_t)biomem->length < size)
885 size = biomem->length;
887 size--; /* don't overwrite the buffer end */
889 memcpy(buf, biomem->data, size);
901 * @retval 0 error initializing SSL
902 * @retval 1 SSL initialized successfully
904 static int Curl_ossl_init(void)
906 #ifdef ENABLE_SSLKEYLOGFILE
907 char *keylog_file_name;
910 OPENSSL_load_builtin_modules();
912 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
913 ENGINE_load_builtin_engines();
916 /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
917 that function makes an exit() call on wrongly formatted config files
918 which makes it hard to use in some situations. OPENSSL_config() itself
919 calls CONF_modules_load_file() and we use that instead and we ignore
922 /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
924 #ifndef CONF_MFLAGS_DEFAULT_SECTION
925 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
928 CONF_modules_load_file(NULL, NULL,
929 CONF_MFLAGS_DEFAULT_SECTION|
930 CONF_MFLAGS_IGNORE_MISSING_FILE);
932 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
933 !defined(LIBRESSL_VERSION_NUMBER)
934 /* OpenSSL 1.1.0+ takes care of initialization itself */
936 /* Lets get nice error messages */
937 SSL_load_error_strings();
939 /* Init the global ciphers and digests */
940 if(!SSLeay_add_ssl_algorithms())
943 OpenSSL_add_all_algorithms();
946 #ifdef ENABLE_SSLKEYLOGFILE
947 if(!keylog_file_fp) {
948 keylog_file_name = curl_getenv("SSLKEYLOGFILE");
949 if(keylog_file_name) {
950 keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT);
953 if(setvbuf(keylog_file_fp, NULL, _IONBF, 0))
955 if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096))
958 fclose(keylog_file_fp);
959 keylog_file_fp = NULL;
962 Curl_safefree(keylog_file_name);
971 static void Curl_ossl_cleanup(void)
973 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
974 !defined(LIBRESSL_VERSION_NUMBER)
975 /* OpenSSL 1.1 deprecates all these cleanup functions and
976 turns them into no-ops in OpenSSL 1.0 compatibility mode */
978 /* Free ciphers and digests lists */
981 #ifdef HAVE_ENGINE_CLEANUP
982 /* Free engine list */
986 /* Free OpenSSL error strings */
989 /* Free thread local error state, destroying hash upon zero refcount */
990 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
991 ERR_remove_thread_state(NULL);
996 /* Free all memory allocated by all configuration modules */
999 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
1000 SSL_COMP_free_compression_methods();
1004 #ifdef ENABLE_SSLKEYLOGFILE
1005 if(keylog_file_fp) {
1006 fclose(keylog_file_fp);
1007 keylog_file_fp = NULL;
1013 * This function is used to determine connection status.
1016 * 1 means the connection is still in place
1017 * 0 means the connection has been closed
1018 * -1 means the connection status is unknown
1020 static int Curl_ossl_check_cxn(struct connectdata *conn)
1022 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
1023 recv MSG_PEEK instead. Bug #795 */
1027 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
1028 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
1030 return 0; /* connection has been closed */
1032 return 1; /* connection still in place */
1033 else if(nread == -1) {
1034 int err = SOCKERRNO;
1035 if(err == EINPROGRESS ||
1036 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
1040 return 1; /* connection still in place */
1041 if(err == ECONNRESET ||
1043 err == ECONNABORTED ||
1058 return 0; /* connection has been closed */
1061 return -1; /* connection status unknown */
1064 /* Selects an OpenSSL crypto engine
1066 static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
1069 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1072 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
1073 e = ENGINE_by_id(engine);
1075 /* avoid memory leak */
1076 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1077 const char *e_id = ENGINE_get_id(e);
1078 if(!strcmp(engine, e_id))
1084 failf(data, "SSL Engine '%s' not found", engine);
1085 return CURLE_SSL_ENGINE_NOTFOUND;
1088 if(data->state.engine) {
1089 ENGINE_finish(data->state.engine);
1090 ENGINE_free(data->state.engine);
1091 data->state.engine = NULL;
1093 if(!ENGINE_init(e)) {
1097 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
1098 engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
1099 return CURLE_SSL_ENGINE_INITFAILED;
1101 data->state.engine = e;
1105 failf(data, "SSL Engine not supported");
1106 return CURLE_SSL_ENGINE_NOTFOUND;
1110 /* Sets engine as default for all SSL operations
1112 static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
1114 #ifdef HAVE_OPENSSL_ENGINE_H
1115 if(data->state.engine) {
1116 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
1117 infof(data, "set default crypto engine '%s'\n",
1118 ENGINE_get_id(data->state.engine));
1121 failf(data, "set default crypto engine '%s' failed",
1122 ENGINE_get_id(data->state.engine));
1123 return CURLE_SSL_ENGINE_SETFAILED;
1132 /* Return list of OpenSSL crypto engine names.
1134 static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
1136 struct curl_slist *list = NULL;
1137 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1138 struct curl_slist *beg;
1141 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1142 beg = curl_slist_append(list, ENGINE_get_id(e));
1144 curl_slist_free_all(list);
1155 static void ossl_close(struct ssl_connect_data *connssl)
1157 if(BACKEND->handle) {
1158 (void)SSL_shutdown(BACKEND->handle);
1159 SSL_set_connect_state(BACKEND->handle);
1161 SSL_free(BACKEND->handle);
1162 BACKEND->handle = NULL;
1165 SSL_CTX_free(BACKEND->ctx);
1166 BACKEND->ctx = NULL;
1171 * This function is called when an SSL connection is closed.
1173 static void Curl_ossl_close(struct connectdata *conn, int sockindex)
1175 ossl_close(&conn->ssl[sockindex]);
1176 ossl_close(&conn->proxy_ssl[sockindex]);
1180 * This function is called to shut down the SSL layer but keep the
1181 * socket open (CCC - Clear Command Channel)
1183 static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
1186 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1187 struct Curl_easy *data = conn->data;
1188 char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
1189 to be at least 256 bytes long. */
1190 unsigned long sslerror;
1196 /* This has only been tested on the proftpd server, and the mod_tls code
1197 sends a close notify alert without waiting for a close notify alert in
1198 response. Thus we wait for a close notify alert from the server, but
1199 we do not send one. Let's hope other servers do the same... */
1201 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1202 (void)SSL_shutdown(BACKEND->handle);
1204 if(BACKEND->handle) {
1205 buffsize = (int)sizeof(buf);
1207 int what = SOCKET_READABLE(conn->sock[sockindex],
1208 SSL_SHUTDOWN_TIMEOUT);
1212 /* Something to read, let's do it and hope that it is the close
1213 notify alert from the server */
1214 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
1215 err = SSL_get_error(BACKEND->handle, (int)nread);
1218 case SSL_ERROR_NONE: /* this is not an error */
1219 case SSL_ERROR_ZERO_RETURN: /* no more data */
1220 /* This is the expected response. There was no data but only
1221 the close notify alert */
1224 case SSL_ERROR_WANT_READ:
1225 /* there's data pending, re-invoke SSL_read() */
1226 infof(data, "SSL_ERROR_WANT_READ\n");
1228 case SSL_ERROR_WANT_WRITE:
1229 /* SSL wants a write. Really odd. Let's bail out. */
1230 infof(data, "SSL_ERROR_WANT_WRITE\n");
1234 /* openssl/ssl.h says "look at error stack/return value/errno" */
1235 sslerror = ERR_get_error();
1236 failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
1238 ossl_strerror(sslerror, buf, sizeof(buf)) :
1239 SSL_ERROR_to_str(err)),
1245 else if(0 == what) {
1247 failf(data, "SSL shutdown timeout");
1251 /* anything that gets here is fatally bad */
1252 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1256 } /* while()-loop for the select() */
1258 if(data->set.verbose) {
1259 #ifdef HAVE_SSL_GET_SHUTDOWN
1260 switch(SSL_get_shutdown(BACKEND->handle)) {
1261 case SSL_SENT_SHUTDOWN:
1262 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1264 case SSL_RECEIVED_SHUTDOWN:
1265 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1267 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1268 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1269 "SSL_RECEIVED__SHUTDOWN\n");
1275 SSL_free(BACKEND->handle);
1276 BACKEND->handle = NULL;
1281 static void Curl_ossl_session_free(void *ptr)
1284 SSL_SESSION_free(ptr);
1288 * This function is called when the 'data' struct is going away. Close
1289 * down everything and free all resources!
1291 static void Curl_ossl_close_all(struct Curl_easy *data)
1293 #ifdef HAVE_OPENSSL_ENGINE_H
1294 if(data->state.engine) {
1295 ENGINE_finish(data->state.engine);
1296 ENGINE_free(data->state.engine);
1297 data->state.engine = NULL;
1302 #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
1303 defined(HAVE_ERR_REMOVE_THREAD_STATE)
1304 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
1305 so we need to clean it here in case the thread will be killed. All OpenSSL
1306 code should extract the error in association with the error so clearing
1307 this queue here should be harmless at worst. */
1308 ERR_remove_thread_state(NULL);
1312 /* ====================================================== */
1315 /* Quote from RFC2818 section 3.1 "Server Identity"
1317 If a subjectAltName extension of type dNSName is present, that MUST
1318 be used as the identity. Otherwise, the (most specific) Common Name
1319 field in the Subject field of the certificate MUST be used. Although
1320 the use of the Common Name is existing practice, it is deprecated and
1321 Certification Authorities are encouraged to use the dNSName instead.
1323 Matching is performed using the matching rules specified by
1324 [RFC2459]. If more than one identity of a given type is present in
1325 the certificate (e.g., more than one dNSName name, a match in any one
1326 of the set is considered acceptable.) Names may contain the wildcard
1327 character * which is considered to match any single domain name
1328 component or component fragment. E.g., *.a.com matches foo.a.com but
1329 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1331 In some cases, the URI is specified as an IP address rather than a
1332 hostname. In this case, the iPAddress subjectAltName must be present
1333 in the certificate and must exactly match the IP in the URI.
1336 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1338 bool matched = FALSE;
1339 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1341 struct Curl_easy *data = conn->data;
1342 STACK_OF(GENERAL_NAME) *altnames;
1344 struct in6_addr addr;
1346 struct in_addr addr;
1348 CURLcode result = CURLE_OK;
1349 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
1350 bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
1351 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1353 const char * const dispname = SSL_IS_PROXY() ?
1354 conn->http_proxy.host.dispname : conn->host.dispname;
1357 if(conn->bits.ipv6_ip &&
1358 Curl_inet_pton(AF_INET6, hostname, &addr)) {
1360 addrlen = sizeof(struct in6_addr);
1364 if(Curl_inet_pton(AF_INET, hostname, &addr)) {
1366 addrlen = sizeof(struct in_addr);
1369 /* get a "list" of alternative names */
1370 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1375 bool dnsmatched = FALSE;
1376 bool ipmatched = FALSE;
1378 /* get amount of alternatives, RFC2459 claims there MUST be at least
1379 one, but we don't depend on it... */
1380 numalts = sk_GENERAL_NAME_num(altnames);
1382 /* loop through all alternatives - until a dnsmatch */
1383 for(i = 0; (i < numalts) && !dnsmatched; i++) {
1384 /* get a handle to alternative name number i */
1385 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1387 if(check->type == GEN_DNS)
1389 else if(check->type == GEN_IPADD)
1392 /* only check alternatives of the same type the target is */
1393 if(check->type == target) {
1394 /* get data and length */
1395 const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
1396 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1399 case GEN_DNS: /* name/pattern comparison */
1400 /* The OpenSSL man page explicitly says: "In general it cannot be
1401 assumed that the data returned by ASN1_STRING_data() is null
1402 terminated or does not contain embedded nulls." But also that
1403 "The actual format of the data will depend on the actual string
1404 type itself: for example for and IA5String the data will be ASCII"
1406 Gisle researched the OpenSSL sources:
1407 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1408 it always 0-terminates an IA5String."
1410 if((altlen == strlen(altptr)) &&
1411 /* if this isn't true, there was an embedded zero in the name
1412 string and we cannot match it. */
1413 Curl_cert_hostcheck(altptr, hostname)) {
1416 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1421 case GEN_IPADD: /* IP address comparison */
1422 /* compare alternative IP address if the data chunk is the same size
1423 our server IP address is */
1424 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1427 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1434 GENERAL_NAMES_free(altnames);
1436 if(dnsmatched || ipmatched)
1441 /* an alternative name matched */
1443 else if(dNSName || iPAddress) {
1444 infof(data, " subjectAltName does not match %s\n", dispname);
1445 failf(data, "SSL: no alternative certificate subject name matches "
1446 "target host name '%s'", dispname);
1447 result = CURLE_PEER_FAILED_VERIFICATION;
1450 /* we have to look to the last occurrence of a commonName in the
1451 distinguished one to get the most significant one. */
1454 /* The following is done because of a bug in 0.9.6b */
1456 unsigned char *nulstr = (unsigned char *)"";
1457 unsigned char *peer_CN = nulstr;
1459 X509_NAME *name = X509_get_subject_name(server_cert);
1461 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
1464 /* we have the name entry and we will now convert this to a string
1465 that we can use for comparison. Doing this we support BMPstring,
1470 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1472 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1473 is already UTF-8 encoded. We check for this case and copy the raw
1474 string manually to avoid the problem. This code can be made
1475 conditional in the future when OpenSSL has been fixed. Work-around
1476 brought by Alexis S. L. Carvalho. */
1478 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1479 j = ASN1_STRING_length(tmp);
1481 peer_CN = OPENSSL_malloc(j + 1);
1483 memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
1488 else /* not a UTF8 name */
1489 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1491 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1492 /* there was a terminating zero before the end of string, this
1493 cannot match and we return failure! */
1494 failf(data, "SSL: illegal cert name field");
1495 result = CURLE_PEER_FAILED_VERIFICATION;
1500 if(peer_CN == nulstr)
1503 /* convert peer_CN from UTF8 */
1504 CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
1505 strlen((char *)peer_CN));
1506 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1508 OPENSSL_free(peer_CN);
1514 /* error already detected, pass through */
1518 "SSL: unable to obtain common name from peer certificate");
1519 result = CURLE_PEER_FAILED_VERIFICATION;
1521 else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
1522 failf(data, "SSL: certificate subject name '%s' does not match "
1523 "target host name '%s'", peer_CN, dispname);
1524 result = CURLE_PEER_FAILED_VERIFICATION;
1527 infof(data, " common name: %s (matched)\n", peer_CN);
1530 OPENSSL_free(peer_CN);
1536 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1537 !defined(OPENSSL_NO_OCSP)
1538 static CURLcode verifystatus(struct connectdata *conn,
1539 struct ssl_connect_data *connssl)
1542 const unsigned char *p;
1543 CURLcode result = CURLE_OK;
1544 struct Curl_easy *data = conn->data;
1546 OCSP_RESPONSE *rsp = NULL;
1547 OCSP_BASICRESP *br = NULL;
1548 X509_STORE *st = NULL;
1549 STACK_OF(X509) *ch = NULL;
1551 long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &p);
1554 failf(data, "No OCSP response received");
1555 result = CURLE_SSL_INVALIDCERTSTATUS;
1559 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1561 failf(data, "Invalid OCSP response");
1562 result = CURLE_SSL_INVALIDCERTSTATUS;
1566 ocsp_status = OCSP_response_status(rsp);
1567 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1568 failf(data, "Invalid OCSP response status: %s (%d)",
1569 OCSP_response_status_str(ocsp_status), ocsp_status);
1570 result = CURLE_SSL_INVALIDCERTSTATUS;
1574 br = OCSP_response_get1_basic(rsp);
1576 failf(data, "Invalid OCSP response");
1577 result = CURLE_SSL_INVALIDCERTSTATUS;
1581 ch = SSL_get_peer_cert_chain(BACKEND->handle);
1582 st = SSL_CTX_get_cert_store(BACKEND->ctx);
1584 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1585 (defined(LIBRESSL_VERSION_NUMBER) && \
1586 LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
1587 /* The authorized responder cert in the OCSP response MUST be signed by the
1588 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1589 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1590 expects this issuer to be present in the chain embedded in the OCSP
1591 response. So we add it if necessary. */
1593 /* First make sure the peer cert chain includes both a peer and an issuer,
1594 and the OCSP response contains a responder cert. */
1595 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1596 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1598 /* Find issuer of responder cert and add it to the OCSP response chain */
1599 for(i = 0; i < sk_X509_num(ch); i++) {
1600 X509 *issuer = sk_X509_value(ch, i);
1601 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1602 if(!OCSP_basic_add1_cert(br, issuer)) {
1603 failf(data, "Could not add issuer cert to OCSP response");
1604 result = CURLE_SSL_INVALIDCERTSTATUS;
1612 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1613 failf(data, "OCSP response verification failed");
1614 result = CURLE_SSL_INVALIDCERTSTATUS;
1618 for(i = 0; i < OCSP_resp_count(br); i++) {
1619 int cert_status, crl_reason;
1620 OCSP_SINGLERESP *single = NULL;
1622 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1624 single = OCSP_resp_get0(br, i);
1628 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1629 &thisupd, &nextupd);
1631 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1632 failf(data, "OCSP response has expired");
1633 result = CURLE_SSL_INVALIDCERTSTATUS;
1637 infof(data, "SSL certificate status: %s (%d)\n",
1638 OCSP_cert_status_str(cert_status), cert_status);
1640 switch(cert_status) {
1641 case V_OCSP_CERTSTATUS_GOOD:
1644 case V_OCSP_CERTSTATUS_REVOKED:
1645 result = CURLE_SSL_INVALIDCERTSTATUS;
1647 failf(data, "SSL certificate revocation reason: %s (%d)",
1648 OCSP_crl_reason_str(crl_reason), crl_reason);
1651 case V_OCSP_CERTSTATUS_UNKNOWN:
1652 result = CURLE_SSL_INVALIDCERTSTATUS;
1658 if(br) OCSP_BASICRESP_free(br);
1659 OCSP_RESPONSE_free(rsp);
1665 #endif /* USE_OPENSSL */
1667 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1668 and thus this cannot be done there. */
1669 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1671 static const char *ssl_msg_type(int ssl_ver, int msg)
1673 #ifdef SSL2_VERSION_MAJOR
1674 if(ssl_ver == SSL2_VERSION_MAJOR) {
1678 case SSL2_MT_CLIENT_HELLO:
1679 return "Client hello";
1680 case SSL2_MT_CLIENT_MASTER_KEY:
1681 return "Client key";
1682 case SSL2_MT_CLIENT_FINISHED:
1683 return "Client finished";
1684 case SSL2_MT_SERVER_HELLO:
1685 return "Server hello";
1686 case SSL2_MT_SERVER_VERIFY:
1687 return "Server verify";
1688 case SSL2_MT_SERVER_FINISHED:
1689 return "Server finished";
1690 case SSL2_MT_REQUEST_CERTIFICATE:
1691 return "Request CERT";
1692 case SSL2_MT_CLIENT_CERTIFICATE:
1693 return "Client CERT";
1698 if(ssl_ver == SSL3_VERSION_MAJOR) {
1700 case SSL3_MT_HELLO_REQUEST:
1701 return "Hello request";
1702 case SSL3_MT_CLIENT_HELLO:
1703 return "Client hello";
1704 case SSL3_MT_SERVER_HELLO:
1705 return "Server hello";
1706 #ifdef SSL3_MT_NEWSESSION_TICKET
1707 case SSL3_MT_NEWSESSION_TICKET:
1708 return "Newsession Ticket";
1710 case SSL3_MT_CERTIFICATE:
1711 return "Certificate";
1712 case SSL3_MT_SERVER_KEY_EXCHANGE:
1713 return "Server key exchange";
1714 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1715 return "Client key exchange";
1716 case SSL3_MT_CERTIFICATE_REQUEST:
1717 return "Request CERT";
1718 case SSL3_MT_SERVER_DONE:
1719 return "Server finished";
1720 case SSL3_MT_CERTIFICATE_VERIFY:
1721 return "CERT verify";
1722 case SSL3_MT_FINISHED:
1724 #ifdef SSL3_MT_CERTIFICATE_STATUS
1725 case SSL3_MT_CERTIFICATE_STATUS:
1726 return "Certificate Status";
1733 static const char *tls_rt_type(int type)
1736 #ifdef SSL3_RT_HEADER
1737 case SSL3_RT_HEADER:
1738 return "TLS header";
1740 case SSL3_RT_CHANGE_CIPHER_SPEC:
1741 return "TLS change cipher";
1744 case SSL3_RT_HANDSHAKE:
1745 return "TLS handshake";
1746 case SSL3_RT_APPLICATION_DATA:
1747 return "TLS app data";
1749 return "TLS Unknown";
1755 * Our callback from the SSL/TLS layers.
1757 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1758 const void *buf, size_t len, SSL *ssl,
1761 struct Curl_easy *data;
1762 const char *msg_name, *tls_rt_name;
1765 int msg_type, txt_len;
1766 const char *verstr = NULL;
1767 struct connectdata *conn = userp;
1769 if(!conn || !conn->data || !conn->data->set.fdebug ||
1770 (direction != 0 && direction != 1))
1776 #ifdef SSL2_VERSION /* removed in recent versions */
1789 #ifdef TLS1_1_VERSION
1790 case TLS1_1_VERSION:
1794 #ifdef TLS1_2_VERSION
1795 case TLS1_2_VERSION:
1799 #ifdef TLS1_3_VERSION
1800 case TLS1_3_VERSION:
1807 snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1813 /* the info given when the version is zero is not that useful for us */
1815 ssl_ver >>= 8; /* check the upper 8 bits only below */
1817 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1818 * always pass-up content-type as 0. But the interesting message-type
1821 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
1822 tls_rt_name = tls_rt_type(content_type);
1826 msg_type = *(char *)buf;
1827 msg_name = ssl_msg_type(ssl_ver, msg_type);
1829 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
1830 verstr, direction?"OUT":"IN",
1831 tls_rt_name, msg_name, msg_type);
1832 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1835 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1836 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1842 /* ====================================================== */
1844 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1845 # define use_sni(x) sni = (x)
1847 # define use_sni(x) Curl_nop_stmt
1850 /* Check for OpenSSL 1.0.2 which has ALPN support. */
1852 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1853 && !defined(OPENSSL_NO_TLSEXT)
1857 /* Check for OpenSSL 1.0.1 which has NPN support. */
1859 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
1860 && !defined(OPENSSL_NO_TLSEXT) \
1861 && !defined(OPENSSL_NO_NEXTPROTONEG)
1868 * in is a list of length prefixed strings. this function has to select
1869 * the protocol we want to use from the list and write its string into out.
1873 select_next_protocol(unsigned char **out, unsigned char *outlen,
1874 const unsigned char *in, unsigned int inlen,
1875 const char *key, unsigned int keylen)
1878 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
1879 if(memcmp(&in[i + 1], key, keylen) == 0) {
1880 *out = (unsigned char *) &in[i + 1];
1889 select_next_proto_cb(SSL *ssl,
1890 unsigned char **out, unsigned char *outlen,
1891 const unsigned char *in, unsigned int inlen,
1894 struct connectdata *conn = (struct connectdata*) arg;
1899 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
1900 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
1901 NGHTTP2_PROTO_VERSION_ID_LEN)) {
1902 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
1903 NGHTTP2_PROTO_VERSION_ID);
1904 conn->negnpn = CURL_HTTP_VERSION_2;
1905 return SSL_TLSEXT_ERR_OK;
1909 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
1910 ALPN_HTTP_1_1_LENGTH)) {
1911 infof(conn->data, "NPN, negotiated HTTP1.1\n");
1912 conn->negnpn = CURL_HTTP_VERSION_1_1;
1913 return SSL_TLSEXT_ERR_OK;
1916 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
1917 *out = (unsigned char *)ALPN_HTTP_1_1;
1918 *outlen = ALPN_HTTP_1_1_LENGTH;
1919 conn->negnpn = CURL_HTTP_VERSION_1_1;
1921 return SSL_TLSEXT_ERR_OK;
1923 #endif /* HAS_NPN */
1926 get_ssl_version_txt(SSL *ssl)
1931 switch(SSL_version(ssl)) {
1932 #ifdef TLS1_3_VERSION
1933 case TLS1_3_VERSION:
1936 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1937 case TLS1_2_VERSION:
1939 case TLS1_1_VERSION:
1953 set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
1956 #if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION)
1957 /* convoluted #if condition just to avoid compiler warnings on unused
1959 struct Curl_easy *data = conn->data;
1961 long ssl_version = SSL_CONN_CONFIG(version);
1962 long ssl_version_max = SSL_CONN_CONFIG(version_max);
1964 if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) {
1965 ssl_version_max = ssl_version << 16;
1968 switch(ssl_version) {
1969 case CURL_SSLVERSION_TLSv1_3:
1970 #ifdef TLS1_3_VERSION
1972 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1973 SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION);
1974 *ctx_options |= SSL_OP_NO_TLSv1_2;
1978 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
1979 return CURLE_NOT_BUILT_IN;
1982 case CURL_SSLVERSION_TLSv1_2:
1983 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1984 *ctx_options |= SSL_OP_NO_TLSv1_1;
1986 failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
1987 return CURLE_NOT_BUILT_IN;
1990 case CURL_SSLVERSION_TLSv1_1:
1991 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1992 *ctx_options |= SSL_OP_NO_TLSv1;
1994 failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
1995 return CURLE_NOT_BUILT_IN;
1998 case CURL_SSLVERSION_TLSv1_0:
1999 *ctx_options |= SSL_OP_NO_SSLv2;
2000 *ctx_options |= SSL_OP_NO_SSLv3;
2004 switch(ssl_version_max) {
2005 case CURL_SSLVERSION_MAX_TLSv1_0:
2006 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2007 *ctx_options |= SSL_OP_NO_TLSv1_1;
2010 case CURL_SSLVERSION_MAX_TLSv1_1:
2011 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2012 *ctx_options |= SSL_OP_NO_TLSv1_2;
2015 case CURL_SSLVERSION_MAX_TLSv1_2:
2016 case CURL_SSLVERSION_MAX_DEFAULT:
2017 #ifdef TLS1_3_VERSION
2018 *ctx_options |= SSL_OP_NO_TLSv1_3;
2021 case CURL_SSLVERSION_MAX_TLSv1_3:
2022 #ifdef TLS1_3_VERSION
2025 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2026 return CURLE_NOT_BUILT_IN;
2032 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
2034 CURLcode result = CURLE_OK;
2036 struct Curl_easy *data = conn->data;
2037 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
2038 X509_LOOKUP *lookup = NULL;
2039 curl_socket_t sockfd = conn->sock[sockindex];
2040 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2041 long ctx_options = 0;
2042 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2044 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
2047 struct in6_addr addr;
2049 struct in_addr addr;
2052 long * const certverifyresult = SSL_IS_PROXY() ?
2053 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2054 const long int ssl_version = SSL_CONN_CONFIG(version);
2056 const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
2058 char * const ssl_cert = SSL_SET_OPTION(cert);
2059 const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
2060 const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
2061 const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
2062 const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
2063 const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
2064 char error_buffer[256];
2066 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
2068 /* Make funny stuff to get random input */
2069 result = Curl_ossl_seed(data);
2073 *certverifyresult = !X509_V_OK;
2075 /* check to see if we've been told to use an explicit SSL/TLS version */
2077 switch(ssl_version) {
2078 case CURL_SSLVERSION_DEFAULT:
2079 case CURL_SSLVERSION_TLSv1:
2080 case CURL_SSLVERSION_TLSv1_0:
2081 case CURL_SSLVERSION_TLSv1_1:
2082 case CURL_SSLVERSION_TLSv1_2:
2083 case CURL_SSLVERSION_TLSv1_3:
2084 /* it will be handled later with the context options */
2085 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
2086 !defined(LIBRESSL_VERSION_NUMBER)
2087 req_method = TLS_client_method();
2089 req_method = SSLv23_client_method();
2093 case CURL_SSLVERSION_SSLv2:
2094 #ifdef OPENSSL_NO_SSL2
2095 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2096 return CURLE_NOT_BUILT_IN;
2099 if(ssl_authtype == CURL_TLSAUTH_SRP)
2100 return CURLE_SSL_CONNECT_ERROR;
2102 req_method = SSLv2_client_method();
2106 case CURL_SSLVERSION_SSLv3:
2107 #ifdef OPENSSL_NO_SSL3_METHOD
2108 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
2109 return CURLE_NOT_BUILT_IN;
2112 if(ssl_authtype == CURL_TLSAUTH_SRP)
2113 return CURLE_SSL_CONNECT_ERROR;
2115 req_method = SSLv3_client_method();
2120 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2121 return CURLE_SSL_CONNECT_ERROR;
2125 SSL_CTX_free(BACKEND->ctx);
2126 BACKEND->ctx = SSL_CTX_new(req_method);
2129 failf(data, "SSL: couldn't create a context: %s",
2130 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
2131 return CURLE_OUT_OF_MEMORY;
2134 #ifdef SSL_MODE_RELEASE_BUFFERS
2135 SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS);
2138 #ifdef SSL_CTRL_SET_MSG_CALLBACK
2139 if(data->set.fdebug && data->set.verbose) {
2140 /* the SSL trace callback is only used for verbose logging */
2141 SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace);
2142 SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn);
2146 /* OpenSSL contains code to work-around lots of bugs and flaws in various
2147 SSL-implementations. SSL_CTX_set_options() is used to enabled those
2148 work-arounds. The man page for this option states that SSL_OP_ALL enables
2149 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
2150 enable the bug workaround options if compatibility with somewhat broken
2151 implementations is desired."
2153 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
2154 disable "rfc4507bis session ticket support". rfc4507bis was later turned
2155 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
2157 The enabled extension concerns the session management. I wonder how often
2158 libcurl stops a connection and then resumes a TLS session. also, sending
2159 the session data is some overhead. .I suggest that you just use your
2160 proposed patch (which explicitly disables TICKET).
2162 If someone writes an application with libcurl and openssl who wants to
2163 enable the feature, one can do this in the SSL callback.
2165 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
2166 interoperability with web server Netscape Enterprise Server 2.0.1 which
2167 was released back in 1996.
2169 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
2170 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
2171 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
2172 this option regardless of OpenSSL version and SSL_OP_ALL definition.
2174 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
2175 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
2176 SSL_OP_ALL that _disables_ that work-around despite the fact that
2177 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
2178 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
2182 ctx_options = SSL_OP_ALL;
2184 #ifdef SSL_OP_NO_TICKET
2185 ctx_options |= SSL_OP_NO_TICKET;
2188 #ifdef SSL_OP_NO_COMPRESSION
2189 ctx_options |= SSL_OP_NO_COMPRESSION;
2192 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2193 /* mitigate CVE-2010-4180 */
2194 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
2197 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2198 /* unless the user explicitly ask to allow the protocol vulnerability we
2199 use the work-around */
2200 if(!SSL_SET_OPTION(enable_beast))
2201 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2204 switch(ssl_version) {
2205 case CURL_SSLVERSION_SSLv3:
2207 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2208 infof(data, "Set version TLSv1.x for SRP authorisation\n");
2211 ctx_options |= SSL_OP_NO_SSLv2;
2212 ctx_options |= SSL_OP_NO_TLSv1;
2213 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2214 ctx_options |= SSL_OP_NO_TLSv1_1;
2215 ctx_options |= SSL_OP_NO_TLSv1_2;
2216 #ifdef TLS1_3_VERSION
2217 ctx_options |= SSL_OP_NO_TLSv1_3;
2222 case CURL_SSLVERSION_DEFAULT:
2223 case CURL_SSLVERSION_TLSv1:
2224 ctx_options |= SSL_OP_NO_SSLv2;
2225 ctx_options |= SSL_OP_NO_SSLv3;
2228 case CURL_SSLVERSION_TLSv1_0:
2229 case CURL_SSLVERSION_TLSv1_1:
2230 case CURL_SSLVERSION_TLSv1_2:
2231 case CURL_SSLVERSION_TLSv1_3:
2232 result = set_ssl_version_min_max(&ctx_options, conn, sockindex);
2233 if(result != CURLE_OK)
2237 case CURL_SSLVERSION_SSLv2:
2238 #ifndef OPENSSL_NO_SSL2
2239 ctx_options |= SSL_OP_NO_SSLv3;
2240 ctx_options |= SSL_OP_NO_TLSv1;
2241 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2242 ctx_options |= SSL_OP_NO_TLSv1_1;
2243 ctx_options |= SSL_OP_NO_TLSv1_2;
2244 #ifdef TLS1_3_VERSION
2245 ctx_options |= SSL_OP_NO_TLSv1_3;
2250 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2251 return CURLE_NOT_BUILT_IN;
2255 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2256 return CURLE_SSL_CONNECT_ERROR;
2259 SSL_CTX_set_options(BACKEND->ctx, ctx_options);
2262 if(conn->bits.tls_enable_npn)
2263 SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn);
2267 if(conn->bits.tls_enable_alpn) {
2269 unsigned char protocols[128];
2272 if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
2273 (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
2274 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
2276 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
2277 NGHTTP2_PROTO_VERSION_ID_LEN);
2278 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
2279 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
2283 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2284 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2285 cur += ALPN_HTTP_1_1_LENGTH;
2286 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
2288 /* expects length prefixed preference ordered list of protocols in wire
2291 SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur);
2295 if(ssl_cert || ssl_cert_type) {
2296 if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type,
2297 SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
2298 SSL_SET_OPTION(key_passwd))) {
2299 /* failf() is already done in cert_stuff() */
2300 return CURLE_SSL_CERTPROBLEM;
2304 ciphers = SSL_CONN_CONFIG(cipher_list);
2306 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2308 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
2309 failf(data, "failed setting cipher list: %s", ciphers);
2310 return CURLE_SSL_CIPHER;
2312 infof(data, "Cipher selection: %s\n", ciphers);
2316 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2317 char * const ssl_username = SSL_SET_OPTION(username);
2319 infof(data, "Using TLS-SRP username: %s\n", ssl_username);
2321 if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) {
2322 failf(data, "Unable to set SRP user name");
2323 return CURLE_BAD_FUNCTION_ARGUMENT;
2325 if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) {
2326 failf(data, "failed setting SRP password");
2327 return CURLE_BAD_FUNCTION_ARGUMENT;
2329 if(!SSL_CONN_CONFIG(cipher_list)) {
2330 infof(data, "Setting cipher list SRP\n");
2332 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) {
2333 failf(data, "failed setting SRP cipher list");
2334 return CURLE_SSL_CIPHER;
2340 if(ssl_cafile || ssl_capath) {
2342 /* tell SSL where to find CA certificates that are used to verify
2343 the servers certificate. */
2344 if(!SSL_CTX_load_verify_locations(BACKEND->ctx,
2345 ssl_cafile, ssl_capath)) {
2346 /* Fail if we insist on successfully verifying the server. */
2347 failf(data, "error setting certificate verify locations:\n"
2348 " CAfile: %s\n CApath: %s",
2349 ssl_cafile ? ssl_cafile : "none",
2350 ssl_capath ? ssl_capath : "none");
2351 return CURLE_SSL_CACERT_BADFILE;
2354 /* Everything is fine. */
2355 infof(data, "successfully set certificate verify locations:\n"
2356 " CAfile: %s\n CApath: %s\n",
2357 ssl_cafile ? ssl_cafile : "none",
2358 ssl_capath ? ssl_capath : "none");
2362 infof(data, "ignoring certificate verify locations due to "
2363 "disabled peer verification\n");
2366 #ifdef CURL_CA_FALLBACK
2367 else if(verifypeer) {
2368 /* verfying the peer without any CA certificates won't
2369 work so use openssl's built in default as fallback */
2370 SSL_CTX_set_default_verify_paths(BACKEND->ctx);
2375 /* tell SSL where to find CRL file that is used to check certificate
2377 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx),
2378 X509_LOOKUP_file());
2380 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
2381 failf(data, "error loading CRL file: %s", ssl_crlfile);
2382 return CURLE_SSL_CRL_BADFILE;
2384 /* Everything is fine. */
2385 infof(data, "successfully load CRL file:\n");
2386 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2387 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2389 infof(data, " CRLfile: %s\n", ssl_crlfile);
2392 /* Try building a chain using issuers in the trusted store first to avoid
2393 problems with server-sent legacy intermediates.
2394 Newer versions of OpenSSL do alternate chain checking by default which
2395 gives us the same fix without as much of a performance hit (slight), so we
2396 prefer that if available.
2397 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2399 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2401 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2402 X509_V_FLAG_TRUSTED_FIRST);
2406 /* SSL always tries to verify the peer, this only says whether it should
2407 * fail to connect if the verification fails, or if it should continue
2408 * anyway. In the latter case the result of the verification is checked with
2409 * SSL_get_verify_result() below. */
2410 SSL_CTX_set_verify(BACKEND->ctx,
2411 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
2413 /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
2414 #if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK)
2415 if(keylog_file_fp) {
2416 SSL_CTX_set_keylog_callback(BACKEND->ctx, ossl_keylog_callback);
2420 /* give application a chance to interfere with SSL set up. */
2421 if(data->set.ssl.fsslctx) {
2422 result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
2423 data->set.ssl.fsslctxp);
2425 failf(data, "error signaled by ssl ctx callback");
2430 /* Lets make an SSL structure */
2432 SSL_free(BACKEND->handle);
2433 BACKEND->handle = SSL_new(BACKEND->ctx);
2434 if(!BACKEND->handle) {
2435 failf(data, "SSL: couldn't create a context (handle)!");
2436 return CURLE_OUT_OF_MEMORY;
2439 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2440 !defined(OPENSSL_NO_OCSP)
2441 if(SSL_CONN_CONFIG(verifystatus))
2442 SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp);
2445 SSL_set_connect_state(BACKEND->handle);
2447 BACKEND->server_cert = 0x0;
2448 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2449 if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
2451 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
2454 !SSL_set_tlsext_host_name(BACKEND->handle, hostname))
2455 infof(data, "WARNING: failed to configure server name indication (SNI) "
2459 /* Check if there's a cached ID we can/should use here! */
2460 if(SSL_SET_OPTION(primary.sessionid)) {
2461 void *ssl_sessionid = NULL;
2463 Curl_ssl_sessionid_lock(conn);
2464 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
2465 /* we got a session id, use it! */
2466 if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
2467 Curl_ssl_sessionid_unlock(conn);
2468 failf(data, "SSL: SSL_set_session failed: %s",
2469 ossl_strerror(ERR_get_error(), error_buffer,
2470 sizeof(error_buffer)));
2471 return CURLE_SSL_CONNECT_ERROR;
2473 /* Informational message */
2474 infof(data, "SSL re-using session ID\n");
2476 Curl_ssl_sessionid_unlock(conn);
2479 if(conn->proxy_ssl[sockindex].use) {
2480 BIO *const bio = BIO_new(BIO_f_ssl());
2481 SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
2482 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2483 DEBUGASSERT(handle != NULL);
2484 DEBUGASSERT(bio != NULL);
2485 BIO_set_ssl(bio, handle, FALSE);
2486 SSL_set_bio(BACKEND->handle, bio, bio);
2488 else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
2489 /* pass the raw socket into the SSL layers */
2490 failf(data, "SSL: SSL_set_fd failed: %s",
2491 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
2492 return CURLE_SSL_CONNECT_ERROR;
2495 connssl->connecting_state = ssl_connect_2;
2500 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2502 struct Curl_easy *data = conn->data;
2504 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2505 long * const certverifyresult = SSL_IS_PROXY() ?
2506 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2507 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2508 || ssl_connect_2_reading == connssl->connecting_state
2509 || ssl_connect_2_writing == connssl->connecting_state);
2513 err = SSL_connect(BACKEND->handle);
2514 /* If keylogging is enabled but the keylog callback is not supported then log
2515 secrets here, immediately after SSL_connect by using tap_ssl_key. */
2516 #if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK)
2517 tap_ssl_key(BACKEND->handle, &BACKEND->tap_state);
2521 0 is "not successful but was shut down controlled"
2522 <0 is "handshake was not successful, because a fatal error occurred" */
2524 int detail = SSL_get_error(BACKEND->handle, err);
2526 if(SSL_ERROR_WANT_READ == detail) {
2527 connssl->connecting_state = ssl_connect_2_reading;
2530 if(SSL_ERROR_WANT_WRITE == detail) {
2531 connssl->connecting_state = ssl_connect_2_writing;
2535 /* untreated error */
2536 unsigned long errdetail;
2537 char error_buffer[256]="";
2543 /* the connection failed, we're not waiting for anything else. */
2544 connssl->connecting_state = ssl_connect_2;
2546 /* Get the earliest error code from the thread's error queue and removes
2548 errdetail = ERR_get_error();
2550 /* Extract which lib and reason */
2551 lib = ERR_GET_LIB(errdetail);
2552 reason = ERR_GET_REASON(errdetail);
2554 if((lib == ERR_LIB_SSL) &&
2555 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2556 result = CURLE_SSL_CACERT;
2558 lerr = SSL_get_verify_result(BACKEND->handle);
2559 if(lerr != X509_V_OK) {
2560 *certverifyresult = lerr;
2561 snprintf(error_buffer, sizeof(error_buffer),
2562 "SSL certificate problem: %s",
2563 X509_verify_cert_error_string(lerr));
2566 /* strcpy() is fine here as long as the string fits within
2568 strcpy(error_buffer, "SSL certificate verification failed");
2571 result = CURLE_SSL_CONNECT_ERROR;
2572 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
2575 /* detail is already set to the SSL error above */
2577 /* If we e.g. use SSLv2 request-method and the server doesn't like us
2578 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
2579 * the SO_ERROR is also lost.
2581 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
2582 const char * const hostname = SSL_IS_PROXY() ?
2583 conn->http_proxy.host.name : conn->host.name;
2584 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
2585 failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
2586 SSL_ERROR_to_str(detail), hostname, port);
2590 /* Could be a CERT problem */
2591 failf(data, "%s", error_buffer);
2597 /* we have been connected fine, we're not waiting for anything else. */
2598 connssl->connecting_state = ssl_connect_3;
2600 /* Informational message */
2601 infof(data, "SSL connection using %s / %s\n",
2602 get_ssl_version_txt(BACKEND->handle),
2603 SSL_get_cipher(BACKEND->handle));
2606 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
2609 if(conn->bits.tls_enable_alpn) {
2610 const unsigned char *neg_protocol;
2612 SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len);
2614 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
2617 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
2618 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
2619 conn->negnpn = CURL_HTTP_VERSION_2;
2623 if(len == ALPN_HTTP_1_1_LENGTH &&
2624 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
2625 conn->negnpn = CURL_HTTP_VERSION_1_1;
2629 infof(data, "ALPN, server did not agree to a protocol\n");
2637 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
2643 return 1; /* buffer too big */
2645 i = i2t_ASN1_OBJECT(buf, ilen, a);
2648 return 1; /* buffer too small */
2653 #define push_certinfo(_label, _num) \
2655 long info_len = BIO_get_mem_data(mem, &ptr); \
2656 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
2657 if(1 != BIO_reset(mem)) \
2661 static void pubkey_show(struct Curl_easy *data,
2666 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2674 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
2678 push_certinfo(namebuf, num);
2681 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2682 #define print_pubkey_BN(_type, _name, _num) \
2683 pubkey_show(data, mem, _num, #_type, #_name, _name)
2686 #define print_pubkey_BN(_type, _name, _num) \
2688 if(_type->_name) { \
2689 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
2694 static int X509V3_ext(struct Curl_easy *data,
2696 CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
2701 if((int)sk_X509_EXTENSION_num(exts) <= 0)
2702 /* no extensions, bail out */
2705 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
2707 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2712 BIO *bio_out = BIO_new(BIO_s_mem());
2717 obj = X509_EXTENSION_get_object(ext);
2719 asn1_object_dump(obj, namebuf, sizeof(namebuf));
2721 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
2722 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
2724 BIO_get_mem_ptr(bio_out, &biomem);
2726 for(j = 0; j < (size_t)biomem->length; j++) {
2727 const char *sep = "";
2728 if(biomem->data[j] == '\n') {
2730 j++; /* skip the newline */
2732 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
2734 if(j<(size_t)biomem->length)
2735 ptr += snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
2739 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
2744 return 0; /* all is fine */
2747 static CURLcode get_cert_chain(struct connectdata *conn,
2748 struct ssl_connect_data *connssl)
2754 struct Curl_easy *data = conn->data;
2758 sk = SSL_get_peer_cert_chain(BACKEND->handle);
2760 return CURLE_OUT_OF_MEMORY;
2763 numcerts = sk_X509_num(sk);
2765 result = Curl_ssl_init_certinfo(data, numcerts);
2770 mem = BIO_new(BIO_s_mem());
2772 for(i = 0; i < numcerts; i++) {
2774 X509 *x = sk_X509_value(sk, i);
2775 EVP_PKEY *pubkey = NULL;
2778 const ASN1_BIT_STRING *psig = NULL;
2780 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
2781 push_certinfo("Subject", i);
2783 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
2784 push_certinfo("Issuer", i);
2786 BIO_printf(mem, "%lx", X509_get_version(x));
2787 push_certinfo("Version", i);
2789 num = X509_get_serialNumber(x);
2790 if(num->type == V_ASN1_NEG_INTEGER)
2792 for(j = 0; j < num->length; j++)
2793 BIO_printf(mem, "%02x", num->data[j]);
2794 push_certinfo("Serial Number", i);
2796 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
2798 const X509_ALGOR *palg = NULL;
2799 ASN1_STRING *a = ASN1_STRING_new();
2801 X509_get0_signature(&psig, &palg, x);
2802 X509_signature_print(mem, palg, a);
2803 ASN1_STRING_free(a);
2806 i2a_ASN1_OBJECT(mem, palg->algorithm);
2807 push_certinfo("Public Key Algorithm", i);
2810 X509V3_ext(data, i, X509_get0_extensions(x));
2814 /* before OpenSSL 1.0.2 */
2815 X509_CINF *cinf = x->cert_info;
2817 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
2818 push_certinfo("Signature Algorithm", i);
2820 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
2821 push_certinfo("Public Key Algorithm", i);
2823 X509V3_ext(data, i, cinf->extensions);
2825 psig = x->signature;
2829 ASN1_TIME_print(mem, X509_get0_notBefore(x));
2830 push_certinfo("Start date", i);
2832 ASN1_TIME_print(mem, X509_get0_notAfter(x));
2833 push_certinfo("Expire date", i);
2835 pubkey = X509_get_pubkey(x);
2837 infof(data, " Unable to load public key\n");
2840 #ifdef HAVE_OPAQUE_EVP_PKEY
2841 pktype = EVP_PKEY_id(pubkey);
2843 pktype = pubkey->type;
2849 #ifdef HAVE_OPAQUE_EVP_PKEY
2850 rsa = EVP_PKEY_get0_RSA(pubkey);
2852 rsa = pubkey->pkey.rsa;
2855 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2860 RSA_get0_key(rsa, &n, &e, NULL);
2862 push_certinfo("RSA Public Key", i);
2863 print_pubkey_BN(rsa, n, i);
2864 print_pubkey_BN(rsa, e, i);
2867 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
2868 push_certinfo("RSA Public Key", i);
2869 print_pubkey_BN(rsa, n, i);
2870 print_pubkey_BN(rsa, e, i);
2877 #ifndef OPENSSL_NO_DSA
2879 #ifdef HAVE_OPAQUE_EVP_PKEY
2880 dsa = EVP_PKEY_get0_DSA(pubkey);
2882 dsa = pubkey->pkey.dsa;
2884 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2889 const BIGNUM *pub_key;
2891 DSA_get0_pqg(dsa, &p, &q, &g);
2892 DSA_get0_key(dsa, &pub_key, NULL);
2894 print_pubkey_BN(dsa, p, i);
2895 print_pubkey_BN(dsa, q, i);
2896 print_pubkey_BN(dsa, g, i);
2897 print_pubkey_BN(dsa, pub_key, i);
2900 print_pubkey_BN(dsa, p, i);
2901 print_pubkey_BN(dsa, q, i);
2902 print_pubkey_BN(dsa, g, i);
2903 print_pubkey_BN(dsa, pub_key, i);
2905 #endif /* !OPENSSL_NO_DSA */
2911 #ifdef HAVE_OPAQUE_EVP_PKEY
2912 dh = EVP_PKEY_get0_DH(pubkey);
2914 dh = pubkey->pkey.dh;
2916 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2921 const BIGNUM *pub_key;
2922 DH_get0_pqg(dh, &p, &q, &g);
2923 DH_get0_key(dh, &pub_key, NULL);
2924 print_pubkey_BN(dh, p, i);
2925 print_pubkey_BN(dh, q, i);
2926 print_pubkey_BN(dh, g, i);
2927 print_pubkey_BN(dh, pub_key, i);
2930 print_pubkey_BN(dh, p, i);
2931 print_pubkey_BN(dh, g, i);
2932 print_pubkey_BN(dh, pub_key, i);
2937 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2942 EVP_PKEY_free(pubkey);
2946 for(j = 0; j < psig->length; j++)
2947 BIO_printf(mem, "%02x:", psig->data[j]);
2948 push_certinfo("Signature", i);
2951 PEM_write_bio_X509(mem, x);
2952 push_certinfo("Cert", i);
2961 * Heavily modified from:
2962 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
2964 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
2965 const char *pinnedpubkey)
2968 int len1 = 0, len2 = 0;
2969 unsigned char *buff1 = NULL, *temp = NULL;
2971 /* Result is returned to caller */
2972 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
2974 /* if a path wasn't specified, don't pin */
2982 /* Begin Gyrations to get the subjectPublicKeyInfo */
2983 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
2985 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
2986 /thread/d61858dae102c6c7 */
2987 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
2991 /* https://www.openssl.org/docs/crypto/buffer.html */
2992 buff1 = temp = malloc(len1);
2996 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
2997 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
3000 * These checks are verifying we got back the same values as when we
3001 * sized the buffer. It's pretty weak since they should always be the
3002 * same. But it gives us something to test.
3004 if((len1 != len2) || !temp || ((temp - buff1) != len1))
3009 /* The one good exit point */
3010 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
3013 /* https://www.openssl.org/docs/crypto/buffer.html */
3021 * Get the server cert, verify it and show it etc, only call failf() if the
3022 * 'strict' argument is TRUE as otherwise all this is for informational
3025 * We check certificates to authenticate the server; otherwise we risk
3026 * man-in-the-middle attack.
3028 static CURLcode servercert(struct connectdata *conn,
3029 struct ssl_connect_data *connssl,
3032 CURLcode result = CURLE_OK;
3035 struct Curl_easy *data = conn->data;
3040 long * const certverifyresult = SSL_IS_PROXY() ?
3041 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
3042 BIO *mem = BIO_new(BIO_s_mem());
3044 if(data->set.ssl.certinfo)
3045 /* we've been asked to gather certificate info! */
3046 (void)get_cert_chain(conn, connssl);
3048 BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle);
3049 if(!BACKEND->server_cert) {
3054 failf(data, "SSL: couldn't get peer certificate!");
3055 return CURLE_PEER_FAILED_VERIFICATION;
3058 infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
3060 rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert),
3061 buffer, sizeof(buffer));
3062 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
3064 ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert));
3065 len = BIO_get_mem_data(mem, (char **) &ptr);
3066 infof(data, " start date: %.*s\n", len, ptr);
3067 (void)BIO_reset(mem);
3069 ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert));
3070 len = BIO_get_mem_data(mem, (char **) &ptr);
3071 infof(data, " expire date: %.*s\n", len, ptr);
3072 (void)BIO_reset(mem);
3076 if(SSL_CONN_CONFIG(verifyhost)) {
3077 result = verifyhost(conn, BACKEND->server_cert);
3079 X509_free(BACKEND->server_cert);
3080 BACKEND->server_cert = NULL;
3085 rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert),
3086 buffer, sizeof(buffer));
3089 failf(data, "SSL: couldn't get X509-issuer name!");
3090 result = CURLE_SSL_CONNECT_ERROR;
3093 infof(data, " issuer: %s\n", buffer);
3095 /* We could do all sorts of certificate verification stuff here before
3096 deallocating the certificate. */
3098 /* e.g. match issuer name with provided issuer certificate */
3099 if(SSL_SET_OPTION(issuercert)) {
3100 fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
3103 failf(data, "SSL: Unable to open issuer cert (%s)",
3104 SSL_SET_OPTION(issuercert));
3105 X509_free(BACKEND->server_cert);
3106 BACKEND->server_cert = NULL;
3107 return CURLE_SSL_ISSUER_ERROR;
3110 issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
3113 failf(data, "SSL: Unable to read issuer cert (%s)",
3114 SSL_SET_OPTION(issuercert));
3115 X509_free(BACKEND->server_cert);
3118 return CURLE_SSL_ISSUER_ERROR;
3123 if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) {
3125 failf(data, "SSL: Certificate issuer check failed (%s)",
3126 SSL_SET_OPTION(issuercert));
3127 X509_free(BACKEND->server_cert);
3129 BACKEND->server_cert = NULL;
3130 return CURLE_SSL_ISSUER_ERROR;
3133 infof(data, " SSL certificate issuer check ok (%s)\n",
3134 SSL_SET_OPTION(issuercert));
3138 lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle);
3140 if(*certverifyresult != X509_V_OK) {
3141 if(SSL_CONN_CONFIG(verifypeer)) {
3142 /* We probably never reach this, because SSL_connect() will fail
3143 and we return earlier if verifypeer is set? */
3145 failf(data, "SSL certificate verify result: %s (%ld)",
3146 X509_verify_cert_error_string(lerr), lerr);
3147 result = CURLE_PEER_FAILED_VERIFICATION;
3150 infof(data, " SSL certificate verify result: %s (%ld),"
3151 " continuing anyway.\n",
3152 X509_verify_cert_error_string(lerr), lerr);
3155 infof(data, " SSL certificate verify ok.\n");
3158 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3159 !defined(OPENSSL_NO_OCSP)
3160 if(SSL_CONN_CONFIG(verifystatus)) {
3161 result = verifystatus(conn, connssl);
3163 X509_free(BACKEND->server_cert);
3164 BACKEND->server_cert = NULL;
3171 /* when not strict, we don't bother about the verify cert problems */
3174 ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
3175 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
3176 if(!result && ptr) {
3177 result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr);
3179 failf(data, "SSL: public key does not match pinned public key!");
3182 X509_free(BACKEND->server_cert);
3183 BACKEND->server_cert = NULL;
3184 connssl->connecting_state = ssl_connect_done;
3189 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
3191 CURLcode result = CURLE_OK;
3192 struct Curl_easy *data = conn->data;
3193 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3195 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
3197 if(SSL_SET_OPTION(primary.sessionid)) {
3199 SSL_SESSION *our_ssl_sessionid;
3200 void *old_ssl_sessionid = NULL;
3202 our_ssl_sessionid = SSL_get1_session(BACKEND->handle);
3204 /* SSL_get1_session() will increment the reference count and the session
3205 will stay in memory until explicitly freed with SSL_SESSION_free(3),
3206 regardless of its state. */
3208 Curl_ssl_sessionid_lock(conn);
3209 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
3212 if(old_ssl_sessionid != our_ssl_sessionid) {
3213 infof(data, "old SSL session ID is stale, removing\n");
3214 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
3220 result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
3221 0 /* unknown size */, sockindex);
3223 Curl_ssl_sessionid_unlock(conn);
3224 failf(data, "failed to store ssl session");
3229 /* Session was incache, so refcount already incremented earlier.
3230 * Avoid further increments with each SSL_get1_session() call.
3231 * This does not free the session as refcount remains > 0
3233 SSL_SESSION_free(our_ssl_sessionid);
3235 Curl_ssl_sessionid_unlock(conn);
3239 * We check certificates to authenticate the server; otherwise we risk
3240 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
3241 * verify the peer ignore faults and failures from the server cert
3245 result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
3246 SSL_CONN_CONFIG(verifyhost)));
3249 connssl->connecting_state = ssl_connect_done;
3254 static Curl_recv ossl_recv;
3255 static Curl_send ossl_send;
3257 static CURLcode ossl_connect_common(struct connectdata *conn,
3263 struct Curl_easy *data = conn->data;
3264 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3265 curl_socket_t sockfd = conn->sock[sockindex];
3269 /* check if the connection has already been established */
3270 if(ssl_connection_complete == connssl->state) {
3275 if(ssl_connect_1 == connssl->connecting_state) {
3276 /* Find out how much more time we're allowed */
3277 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3279 if(timeout_ms < 0) {
3280 /* no need to continue if time already is up */
3281 failf(data, "SSL connection timeout");
3282 return CURLE_OPERATION_TIMEDOUT;
3285 result = ossl_connect_step1(conn, sockindex);
3290 while(ssl_connect_2 == connssl->connecting_state ||
3291 ssl_connect_2_reading == connssl->connecting_state ||
3292 ssl_connect_2_writing == connssl->connecting_state) {
3294 /* check allowed time left */
3295 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3297 if(timeout_ms < 0) {
3298 /* no need to continue if time already is up */
3299 failf(data, "SSL connection timeout");
3300 return CURLE_OPERATION_TIMEDOUT;
3303 /* if ssl is expecting something, check if it's available. */
3304 if(connssl->connecting_state == ssl_connect_2_reading ||
3305 connssl->connecting_state == ssl_connect_2_writing) {
3307 curl_socket_t writefd = ssl_connect_2_writing ==
3308 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3309 curl_socket_t readfd = ssl_connect_2_reading ==
3310 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3312 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
3313 nonblocking?0:timeout_ms);
3316 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
3317 return CURLE_SSL_CONNECT_ERROR;
3325 failf(data, "SSL connection timeout");
3326 return CURLE_OPERATION_TIMEDOUT;
3328 /* socket is readable or writable */
3331 /* Run transaction, and return to the caller if it failed or if this
3332 * connection is done nonblocking and this loop would execute again. This
3333 * permits the owner of a multi handle to abort a connection attempt
3334 * before step2 has completed while ensuring that a client using select()
3335 * or epoll() will always have a valid fdset to wait on.
3337 result = ossl_connect_step2(conn, sockindex);
3338 if(result || (nonblocking &&
3339 (ssl_connect_2 == connssl->connecting_state ||
3340 ssl_connect_2_reading == connssl->connecting_state ||
3341 ssl_connect_2_writing == connssl->connecting_state)))
3344 } /* repeat step2 until all transactions are done. */
3346 if(ssl_connect_3 == connssl->connecting_state) {
3347 result = ossl_connect_step3(conn, sockindex);
3352 if(ssl_connect_done == connssl->connecting_state) {
3353 connssl->state = ssl_connection_complete;
3354 conn->recv[sockindex] = ossl_recv;
3355 conn->send[sockindex] = ossl_send;
3361 /* Reset our connect state machine */
3362 connssl->connecting_state = ssl_connect_1;
3367 static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
3371 return ossl_connect_common(conn, sockindex, TRUE, done);
3374 static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
3379 result = ossl_connect_common(conn, sockindex, FALSE, &done);
3388 static bool Curl_ossl_data_pending(const struct connectdata *conn,
3391 const struct ssl_connect_data *connssl = &conn->ssl[connindex];
3392 const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
3394 if(connssl->backend->handle && SSL_pending(connssl->backend->handle))
3397 if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle))
3403 static size_t Curl_ossl_version(char *buffer, size_t size);
3405 static ssize_t ossl_send(struct connectdata *conn,
3411 /* SSL_write() is said to return 'int' while write() and send() returns
3414 char error_buffer[256];
3415 unsigned long sslerror;
3418 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3422 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3423 rc = SSL_write(BACKEND->handle, mem, memlen);
3426 err = SSL_get_error(BACKEND->handle, rc);
3429 case SSL_ERROR_WANT_READ:
3430 case SSL_ERROR_WANT_WRITE:
3431 /* The operation did not complete; the same TLS/SSL I/O function
3432 should be called again later. This is basically an EWOULDBLOCK
3434 *curlcode = CURLE_AGAIN;
3436 case SSL_ERROR_SYSCALL:
3437 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
3439 *curlcode = CURLE_SEND_ERROR;
3442 /* A failure in the SSL library occurred, usually a protocol error.
3443 The OpenSSL error queue contains more information on the error. */
3444 sslerror = ERR_get_error();
3445 if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
3446 ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
3447 conn->ssl[sockindex].state == ssl_connection_complete &&
3448 conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
3450 Curl_ossl_version(ver, 120);
3451 failf(conn->data, "Error: %s does not support double SSL tunneling.",
3455 failf(conn->data, "SSL_write() error: %s",
3456 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
3457 *curlcode = CURLE_SEND_ERROR;
3461 failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
3462 SSL_ERROR_to_str(err), SOCKERRNO);
3463 *curlcode = CURLE_SEND_ERROR;
3466 *curlcode = CURLE_OK;
3467 return (ssize_t)rc; /* number of bytes */
3470 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3471 int num, /* socketindex */
3472 char *buf, /* store read data here */
3473 size_t buffersize, /* max amount to read */
3476 char error_buffer[256];
3477 unsigned long sslerror;
3480 struct ssl_connect_data *connssl = &conn->ssl[num];
3484 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3485 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
3487 /* failed SSL_read */
3488 int err = SSL_get_error(BACKEND->handle, (int)nread);
3491 case SSL_ERROR_NONE: /* this is not an error */
3492 case SSL_ERROR_ZERO_RETURN: /* no more data */
3494 case SSL_ERROR_WANT_READ:
3495 case SSL_ERROR_WANT_WRITE:
3496 /* there's data pending, re-invoke SSL_read() */
3497 *curlcode = CURLE_AGAIN;
3500 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3502 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3503 sslerror = ERR_get_error();
3504 if((nread < 0) || sslerror) {
3505 /* If the return code was negative or there actually is an error in the
3507 failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d",
3509 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)) :
3510 SSL_ERROR_to_str(err)),
3512 *curlcode = CURLE_RECV_ERROR;
3520 static size_t Curl_ossl_version(char *buffer, size_t size)
3522 #ifdef OPENSSL_IS_BORINGSSL
3523 return snprintf(buffer, size, OSSL_PACKAGE);
3524 #else /* OPENSSL_IS_BORINGSSL */
3526 unsigned long ssleay_value;
3529 ssleay_value = OpenSSL_version_num();
3530 if(ssleay_value < 0x906000) {
3531 ssleay_value = SSLEAY_VERSION_NUMBER;
3535 if(ssleay_value&0xff0) {
3536 int minor_ver = (ssleay_value >> 4) & 0xff;
3537 if(minor_ver > 26) {
3538 /* handle extended version introduced for 0.9.8za */
3539 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
3543 sub[0] = (char) (minor_ver + 'a' - 1);
3550 return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
3552 (ssleay_value>>28)&0xf,
3553 (ssleay_value>>20)&0xff,
3554 (ssleay_value>>12)&0xff,
3556 #endif /* OPENSSL_IS_BORINGSSL */
3559 /* can be called with data == NULL */
3560 static CURLcode Curl_ossl_random(struct Curl_easy *data,
3561 unsigned char *entropy, size_t length)
3565 if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
3566 return CURLE_FAILED_INIT; /* couldn't seed for some reason */
3570 return CURLE_FAILED_INIT;
3572 /* RAND_bytes() returns 1 on success, 0 otherwise. */
3573 rc = RAND_bytes(entropy, curlx_uztosi(length));
3574 return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
3577 static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */
3579 unsigned char *md5sum /* output */,
3583 unsigned int len = 0;
3586 mdctx = EVP_MD_CTX_create();
3587 EVP_DigestInit_ex(mdctx, EVP_md5(), NULL);
3588 EVP_DigestUpdate(mdctx, tmp, tmplen);
3589 EVP_DigestFinal_ex(mdctx, md5sum, &len);
3590 EVP_MD_CTX_destroy(mdctx);
3594 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3595 static void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
3597 unsigned char *sha256sum /* output */,
3601 unsigned int len = 0;
3604 mdctx = EVP_MD_CTX_create();
3605 EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL);
3606 EVP_DigestUpdate(mdctx, tmp, tmplen);
3607 EVP_DigestFinal_ex(mdctx, sha256sum, &len);
3608 EVP_MD_CTX_destroy(mdctx);
3612 static bool Curl_ossl_cert_status_request(void)
3614 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3615 !defined(OPENSSL_NO_OCSP)
3622 static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl,
3625 /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
3626 return info == CURLINFO_TLS_SESSION ?
3627 (void *)BACKEND->ctx : (void *)BACKEND->handle;
3630 const struct Curl_ssl Curl_ssl_openssl = {
3631 { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
3633 1, /* have_ca_path */
3634 1, /* have_certinfo */
3635 1, /* have_pinnedpubkey */
3636 1, /* have_ssl_ctx */
3637 1, /* support_https_proxy */
3639 sizeof(struct ssl_backend_data),
3641 Curl_ossl_init, /* init */
3642 Curl_ossl_cleanup, /* cleanup */
3643 Curl_ossl_version, /* version */
3644 Curl_ossl_check_cxn, /* check_cxn */
3645 Curl_ossl_shutdown, /* shutdown */
3646 Curl_ossl_data_pending, /* data_pending */
3647 Curl_ossl_random, /* random */
3648 Curl_ossl_cert_status_request, /* cert_status_request */
3649 Curl_ossl_connect, /* connect */
3650 Curl_ossl_connect_nonblocking, /* connect_nonblocking */
3651 Curl_ossl_get_internals, /* get_internals */
3652 Curl_ossl_close, /* close_one */
3653 Curl_ossl_close_all, /* close_all */
3654 Curl_ossl_session_free, /* session_free */
3655 Curl_ossl_set_engine, /* set_engine */
3656 Curl_ossl_set_engine_default, /* set_engine_default */
3657 Curl_ossl_engines_list, /* engines_list */
3658 Curl_none_false_start, /* false_start */
3659 Curl_ossl_md5sum, /* md5sum */
3660 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3661 Curl_ossl_sha256sum /* sha256sum */
3663 NULL /* sha256sum */
3667 #endif /* USE_OPENSSL */