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 defined (TIZEN_TV_EXT)
168 #define DEFAULT_CIPHER_SELECTION \
169 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:" \
170 "DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:ECDH-RSA-AES256-SHA:" \
171 "ECDH-ECDSA-AES256-SHA:AES256-SHA:ECDHE-RSA-AES128-GCM-SHA256:" \
172 "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:" \
173 "DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:" \
174 "AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:" \
175 "ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:" \
176 "EDH-DSS-DES-CBC3-SHA:ECDH-RSA-DES-CBC3-SHA:ECDH-ECDSA-DES-CBC3-SHA:" \
177 "DES-CBC3-SHA:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA"
178 #elif (OPENSSL_VERSION_NUMBER >= 0x10100000L)
179 /* up2date versions of OpenSSL maintain the default reasonably secure without
180 * breaking compatibility, so it is better not to override the default by curl
182 #define DEFAULT_CIPHER_SELECTION NULL
184 /* ... but it is not the case with old versions of OpenSSL */
185 #define DEFAULT_CIPHER_SELECTION \
186 "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
189 #define ENABLE_SSLKEYLOGFILE
191 #ifdef ENABLE_SSLKEYLOGFILE
192 typedef struct ssl_tap_state {
193 int master_key_length;
194 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
195 unsigned char client_random[SSL3_RANDOM_SIZE];
197 #endif /* ENABLE_SSLKEYLOGFILE */
199 struct ssl_backend_data {
200 /* these ones requires specific SSL-types */
204 #ifdef ENABLE_SSLKEYLOGFILE
205 /* tap_state holds the last seen master key if we're logging them */
206 ssl_tap_state_t tap_state;
210 #define BACKEND connssl->backend
213 * Number of bytes to read from the random number seed file. This must be
214 * a finite value (because some entropy "files" like /dev/urandom have
215 * an infinite length), but must be large enough to provide enough
216 * entropy to properly seed OpenSSL's PRNG.
218 #define RAND_LOAD_LENGTH 1024
220 #ifdef ENABLE_SSLKEYLOGFILE
221 /* The fp for the open SSLKEYLOGFILE, or NULL if not open */
222 static FILE *keylog_file_fp;
224 #ifdef HAVE_KEYLOG_CALLBACK
225 static void ossl_keylog_callback(const SSL *ssl, const char *line)
229 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
230 may not be thread-safe. */
231 if(keylog_file_fp && line && *line) {
234 size_t linelen = strlen(line);
236 if(linelen <= sizeof(stackbuf) - 2)
239 buf = malloc(linelen + 2);
243 strncpy(buf, line, linelen);
245 buf[linelen + 1] = '\0';
247 fputs(buf, keylog_file_fp);
253 #define KEYLOG_PREFIX "CLIENT_RANDOM "
254 #define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1)
256 * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL
257 * being used doesn't have native support for doing that.
259 static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state)
261 const char *hex = "0123456789ABCDEF";
263 char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 +
264 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1];
265 const SSL_SESSION *session = SSL_get_session(ssl);
266 unsigned char client_random[SSL3_RANDOM_SIZE];
267 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
268 int master_key_length = 0;
270 if(!session || !keylog_file_fp)
273 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
274 /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
275 * we have a valid SSL context if we have a non-NULL session. */
276 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
277 master_key_length = (int)
278 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
280 if(ssl->s3 && session->master_key_length > 0) {
281 master_key_length = session->master_key_length;
282 memcpy(master_key, session->master_key, session->master_key_length);
283 memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
287 if(master_key_length <= 0)
290 /* Skip writing keys if there is no key or it did not change. */
291 if(state->master_key_length == master_key_length &&
292 !memcmp(state->master_key, master_key, master_key_length) &&
293 !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) {
297 state->master_key_length = master_key_length;
298 memcpy(state->master_key, master_key, master_key_length);
299 memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE);
301 memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN);
302 pos = KEYLOG_PREFIX_LEN;
304 /* Client Random for SSLv3/TLS */
305 for(i = 0; i < SSL3_RANDOM_SIZE; i++) {
306 line[pos++] = hex[client_random[i] >> 4];
307 line[pos++] = hex[client_random[i] & 0xF];
311 /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */
312 for(i = 0; i < master_key_length; i++) {
313 line[pos++] = hex[master_key[i] >> 4];
314 line[pos++] = hex[master_key[i] & 0xF];
319 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
320 may not be thread-safe. */
321 fputs(line, keylog_file_fp);
323 #endif /* !HAVE_KEYLOG_CALLBACK */
324 #endif /* ENABLE_SSLKEYLOGFILE */
326 static const char *SSL_ERROR_to_str(int err)
330 return "SSL_ERROR_NONE";
332 return "SSL_ERROR_SSL";
333 case SSL_ERROR_WANT_READ:
334 return "SSL_ERROR_WANT_READ";
335 case SSL_ERROR_WANT_WRITE:
336 return "SSL_ERROR_WANT_WRITE";
337 case SSL_ERROR_WANT_X509_LOOKUP:
338 return "SSL_ERROR_WANT_X509_LOOKUP";
339 case SSL_ERROR_SYSCALL:
340 return "SSL_ERROR_SYSCALL";
341 case SSL_ERROR_ZERO_RETURN:
342 return "SSL_ERROR_ZERO_RETURN";
343 case SSL_ERROR_WANT_CONNECT:
344 return "SSL_ERROR_WANT_CONNECT";
345 case SSL_ERROR_WANT_ACCEPT:
346 return "SSL_ERROR_WANT_ACCEPT";
347 #if defined(SSL_ERROR_WANT_ASYNC)
348 case SSL_ERROR_WANT_ASYNC:
349 return "SSL_ERROR_WANT_ASYNC";
351 #if defined(SSL_ERROR_WANT_ASYNC_JOB)
352 case SSL_ERROR_WANT_ASYNC_JOB:
353 return "SSL_ERROR_WANT_ASYNC_JOB";
355 #if defined(SSL_ERROR_WANT_EARLY)
356 case SSL_ERROR_WANT_EARLY:
357 return "SSL_ERROR_WANT_EARLY";
360 return "SSL_ERROR unknown";
364 /* Return error string for last OpenSSL error
366 static char *ossl_strerror(unsigned long error, char *buf, size_t size)
368 ERR_error_string_n(error, buf, size);
372 static int passwd_callback(char *buf, int num, int encrypting,
375 DEBUGASSERT(0 == encrypting);
378 int klen = curlx_uztosi(strlen((char *)global_passwd));
380 memcpy(buf, global_passwd, klen + 1);
388 * rand_enough() returns TRUE if we have seeded the random engine properly.
390 static bool rand_enough(void)
392 return (0 != RAND_status()) ? TRUE : FALSE;
395 static CURLcode Curl_ossl_seed(struct Curl_easy *data)
397 /* we have the "SSL is seeded" boolean static to prevent multiple
398 time-consuming seedings in vain */
399 static bool ssl_seeded = FALSE;
406 /* OpenSSL 1.1.0+ will return here */
412 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
414 if(data->set.str[STRING_SSL_RANDOM_FILE])
415 #define RANDOM_FILE "" /* doesn't matter won't be used */
418 /* let the option override the define */
419 RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
420 data->set.str[STRING_SSL_RANDOM_FILE]:
427 #if defined(HAVE_RAND_EGD)
428 /* only available in OpenSSL 0.9.5 and later */
429 /* EGD_SOCKET is set at configure time or not at all */
431 /* If we don't have the define set, we only do this if the egd-option
433 if(data->set.str[STRING_SSL_EGDSOCKET])
434 #define EGD_SOCKET "" /* doesn't matter won't be used */
437 /* If there's an option and a define, the option overrides the
439 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
440 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
448 /* fallback to a custom seeding of the PRNG using a hash based on a current
451 unsigned char randb[64];
452 size_t len = sizeof(randb);
454 for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
455 struct curltime tv = Curl_now();
458 tv.tv_usec *= (unsigned int)i + 2;
459 tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) *
461 tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec +
462 Curl_now().tv_usec) *
464 memcpy(&randb[i * sizeof(struct curltime)], &tv,
465 sizeof(struct curltime));
467 RAND_add(randb, (int)len, (double)len/2);
468 } while(!rand_enough());
470 /* generates a default path for the random seed file */
471 fname[0] = 0; /* blank it first */
472 RAND_file_name(fname, sizeof(fname));
474 /* we got a file name to try */
475 RAND_load_file(fname, RAND_LOAD_LENGTH);
480 infof(data, "libcurl is now using a weak random seed!\n");
481 return (rand_enough() ? CURLE_OK :
482 CURLE_SSL_CONNECT_ERROR /* confusing error code */);
485 #ifndef SSL_FILETYPE_ENGINE
486 #define SSL_FILETYPE_ENGINE 42
488 #ifndef SSL_FILETYPE_PKCS12
489 #define SSL_FILETYPE_PKCS12 43
491 static int do_file_type(const char *type)
493 if(!type || !type[0])
494 return SSL_FILETYPE_PEM;
495 if(strcasecompare(type, "PEM"))
496 return SSL_FILETYPE_PEM;
497 if(strcasecompare(type, "DER"))
498 return SSL_FILETYPE_ASN1;
499 if(strcasecompare(type, "ENG"))
500 return SSL_FILETYPE_ENGINE;
501 if(strcasecompare(type, "P12"))
502 return SSL_FILETYPE_PKCS12;
506 #if defined(HAVE_OPENSSL_ENGINE_H)
508 * Supply default password to the engine user interface conversation.
509 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
510 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
512 static int ssl_ui_reader(UI *ui, UI_STRING *uis)
514 const char *password;
515 switch(UI_get_string_type(uis)) {
518 password = (const char *)UI_get0_user_data(ui);
519 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
520 UI_set_result(ui, uis, password);
526 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
530 * Suppress interactive request for a default password if available.
532 static int ssl_ui_writer(UI *ui, UI_STRING *uis)
534 switch(UI_get_string_type(uis)) {
537 if(UI_get0_user_data(ui) &&
538 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
544 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
549 int cert_stuff(struct connectdata *conn,
552 const char *cert_type,
554 const char *key_type,
557 struct Curl_easy *data = conn->data;
558 char error_buffer[256];
559 bool check_privkey = TRUE;
561 int file_type = do_file_type(cert_type);
563 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
569 /* set the password in the callback userdata */
570 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
571 /* Set passwd callback: */
572 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
577 case SSL_FILETYPE_PEM:
578 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
579 if(SSL_CTX_use_certificate_chain_file(ctx,
582 "could not load PEM client certificate, " OSSL_PACKAGE
584 "(no key found, wrong pass phrase, or wrong file format?)",
585 ossl_strerror(ERR_get_error(), error_buffer,
586 sizeof(error_buffer)) );
591 case SSL_FILETYPE_ASN1:
592 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
593 we use the case above for PEM so this can only be performed with
595 if(SSL_CTX_use_certificate_file(ctx,
599 "could not load ASN1 client certificate, " OSSL_PACKAGE
601 "(no key found, wrong pass phrase, or wrong file format?)",
602 ossl_strerror(ERR_get_error(), error_buffer,
603 sizeof(error_buffer)) );
607 case SSL_FILETYPE_ENGINE:
608 #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
610 if(data->state.engine) {
611 const char *cmd_name = "LOAD_CERT_CTRL";
617 params.cert_id = cert_file;
620 /* Does the engine supports LOAD_CERT_CTRL ? */
621 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
622 0, (void *)cmd_name, NULL)) {
623 failf(data, "ssl engine does not support loading certificates");
627 /* Load the certificate from the engine */
628 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
629 0, ¶ms, NULL, 1)) {
630 failf(data, "ssl engine cannot load client cert with id"
631 " '%s' [%s]", cert_file,
632 ossl_strerror(ERR_get_error(), error_buffer,
633 sizeof(error_buffer)));
638 failf(data, "ssl engine didn't initialized the certificate "
643 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
644 failf(data, "unable to set client certificate");
645 X509_free(params.cert);
648 X509_free(params.cert); /* we don't need the handle any more... */
651 failf(data, "crypto engine not set, can't load certificate");
657 failf(data, "file type ENG for certificate not implemented");
661 case SSL_FILETYPE_PKCS12:
666 STACK_OF(X509) *ca = NULL;
668 f = fopen(cert_file, "rb");
670 failf(data, "could not open PKCS12 file '%s'", cert_file);
673 p12 = d2i_PKCS12_fp(f, NULL);
677 failf(data, "error reading PKCS12 file '%s'", cert_file);
683 if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
686 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
688 ossl_strerror(ERR_get_error(), error_buffer,
689 sizeof(error_buffer)) );
696 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
698 "could not load PKCS12 client certificate, " OSSL_PACKAGE
700 ossl_strerror(ERR_get_error(), error_buffer,
701 sizeof(error_buffer)) );
705 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
706 failf(data, "unable to use private key from PKCS12 file '%s'",
711 if(!SSL_CTX_check_private_key (ctx)) {
712 failf(data, "private key from PKCS12 file '%s' "
713 "does not match certificate in same file", cert_file);
716 /* Set Certificate Verification chain */
718 while(sk_X509_num(ca)) {
720 * Note that sk_X509_pop() is used below to make sure the cert is
721 * removed from the stack properly before getting passed to
722 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
723 * we used sk_X509_value() instead, but then we'd clean it in the
724 * subsequent sk_X509_pop_free() call.
726 X509 *x = sk_X509_pop(ca);
727 if(!SSL_CTX_add_client_CA(ctx, x)) {
729 failf(data, "cannot add certificate to client CA list");
732 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
734 failf(data, "cannot add certificate to certificate chain");
744 sk_X509_pop_free(ca, X509_free);
747 return 0; /* failure! */
751 failf(data, "not supported file type '%s' for certificate", cert_type);
755 file_type = do_file_type(key_type);
758 case SSL_FILETYPE_PEM:
762 /* cert & key can only be in PEM case in the same file */
763 key_file = cert_file;
765 case SSL_FILETYPE_ASN1:
766 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
767 failf(data, "unable to set private key file: '%s' type %s",
768 key_file, key_type?key_type:"PEM");
772 case SSL_FILETYPE_ENGINE:
773 #ifdef HAVE_OPENSSL_ENGINE_H
774 { /* XXXX still needs some work */
775 EVP_PKEY *priv_key = NULL;
776 if(data->state.engine) {
777 UI_METHOD *ui_method =
778 UI_create_method((char *)"curl user interface");
780 failf(data, "unable do create " OSSL_PACKAGE
781 " user-interface method");
784 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
785 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
786 UI_method_set_reader(ui_method, ssl_ui_reader);
787 UI_method_set_writer(ui_method, ssl_ui_writer);
788 /* the typecast below was added to please mingw32 */
789 priv_key = (EVP_PKEY *)
790 ENGINE_load_private_key(data->state.engine, key_file,
793 UI_destroy_method(ui_method);
795 failf(data, "failed to load private key from crypto engine");
798 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
799 failf(data, "unable to set private key");
800 EVP_PKEY_free(priv_key);
803 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
806 failf(data, "crypto engine not set, can't load private key");
812 failf(data, "file type ENG for private key not supported");
815 case SSL_FILETYPE_PKCS12:
817 failf(data, "file type P12 for private key not supported");
822 failf(data, "not supported file type for private key");
828 failf(data, "unable to create an SSL structure");
832 x509 = SSL_get_certificate(ssl);
834 /* This version was provided by Evan Jordan and is supposed to not
835 leak memory as the previous version: */
837 EVP_PKEY *pktmp = X509_get_pubkey(x509);
838 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
839 EVP_PKEY_free(pktmp);
842 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL)
844 /* If RSA is used, don't check the private key if its flags indicate
845 * it doesn't support it. */
846 EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
848 #ifdef HAVE_OPAQUE_EVP_PKEY
849 pktype = EVP_PKEY_id(priv_key);
851 pktype = priv_key->type;
853 if(pktype == EVP_PKEY_RSA) {
854 RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
855 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
856 check_privkey = FALSE;
857 RSA_free(rsa); /* Decrement reference count */
864 /* If we are using DSA, we can copy the parameters from
867 if(check_privkey == TRUE) {
868 /* Now we know that a key and cert have been set against
870 if(!SSL_CTX_check_private_key(ctx)) {
871 failf(data, "Private key does not match the certificate public key");
879 /* returns non-zero on failure */
880 static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
883 return X509_NAME_oneline(a, buf, size);
885 BIO *bio_out = BIO_new(BIO_s_mem());
890 return 1; /* alloc failed! */
892 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
893 BIO_get_mem_ptr(bio_out, &biomem);
895 if((size_t)biomem->length < size)
896 size = biomem->length;
898 size--; /* don't overwrite the buffer end */
900 memcpy(buf, biomem->data, size);
912 * @retval 0 error initializing SSL
913 * @retval 1 SSL initialized successfully
915 static int Curl_ossl_init(void)
917 #ifdef ENABLE_SSLKEYLOGFILE
918 char *keylog_file_name;
921 OPENSSL_load_builtin_modules();
923 #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
924 ENGINE_load_builtin_engines();
927 /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
928 that function makes an exit() call on wrongly formatted config files
929 which makes it hard to use in some situations. OPENSSL_config() itself
930 calls CONF_modules_load_file() and we use that instead and we ignore
933 /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
935 #ifndef CONF_MFLAGS_DEFAULT_SECTION
936 #define CONF_MFLAGS_DEFAULT_SECTION 0x0
939 CONF_modules_load_file(NULL, NULL,
940 CONF_MFLAGS_DEFAULT_SECTION|
941 CONF_MFLAGS_IGNORE_MISSING_FILE);
943 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
944 !defined(LIBRESSL_VERSION_NUMBER)
945 /* OpenSSL 1.1.0+ takes care of initialization itself */
947 /* Lets get nice error messages */
948 SSL_load_error_strings();
950 /* Init the global ciphers and digests */
951 if(!SSLeay_add_ssl_algorithms())
954 OpenSSL_add_all_algorithms();
957 #ifdef ENABLE_SSLKEYLOGFILE
958 if(!keylog_file_fp) {
959 keylog_file_name = curl_getenv("SSLKEYLOGFILE");
960 if(keylog_file_name) {
961 keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT);
964 if(setvbuf(keylog_file_fp, NULL, _IONBF, 0))
966 if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096))
969 fclose(keylog_file_fp);
970 keylog_file_fp = NULL;
973 Curl_safefree(keylog_file_name);
982 static void Curl_ossl_cleanup(void)
984 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
985 !defined(LIBRESSL_VERSION_NUMBER)
986 /* OpenSSL 1.1 deprecates all these cleanup functions and
987 turns them into no-ops in OpenSSL 1.0 compatibility mode */
989 /* Free ciphers and digests lists */
992 #ifdef HAVE_ENGINE_CLEANUP
993 /* Free engine list */
997 /* Free OpenSSL error strings */
1000 /* Free thread local error state, destroying hash upon zero refcount */
1001 #ifdef HAVE_ERR_REMOVE_THREAD_STATE
1002 ERR_remove_thread_state(NULL);
1004 ERR_remove_state(0);
1007 /* Free all memory allocated by all configuration modules */
1008 CONF_modules_free();
1010 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
1011 SSL_COMP_free_compression_methods();
1015 #ifdef ENABLE_SSLKEYLOGFILE
1016 if(keylog_file_fp) {
1017 fclose(keylog_file_fp);
1018 keylog_file_fp = NULL;
1024 * This function is used to determine connection status.
1027 * 1 means the connection is still in place
1028 * 0 means the connection has been closed
1029 * -1 means the connection status is unknown
1031 static int Curl_ossl_check_cxn(struct connectdata *conn)
1033 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
1034 recv MSG_PEEK instead. Bug #795 */
1038 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
1039 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
1041 return 0; /* connection has been closed */
1043 return 1; /* connection still in place */
1044 else if(nread == -1) {
1045 int err = SOCKERRNO;
1046 if(err == EINPROGRESS ||
1047 #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
1051 return 1; /* connection still in place */
1052 if(err == ECONNRESET ||
1054 err == ECONNABORTED ||
1069 return 0; /* connection has been closed */
1072 return -1; /* connection status unknown */
1075 /* Selects an OpenSSL crypto engine
1077 static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
1080 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1083 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
1084 e = ENGINE_by_id(engine);
1086 /* avoid memory leak */
1087 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1088 const char *e_id = ENGINE_get_id(e);
1089 if(!strcmp(engine, e_id))
1095 failf(data, "SSL Engine '%s' not found", engine);
1096 return CURLE_SSL_ENGINE_NOTFOUND;
1099 if(data->state.engine) {
1100 ENGINE_finish(data->state.engine);
1101 ENGINE_free(data->state.engine);
1102 data->state.engine = NULL;
1104 if(!ENGINE_init(e)) {
1108 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
1109 engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
1110 return CURLE_SSL_ENGINE_INITFAILED;
1112 data->state.engine = e;
1116 failf(data, "SSL Engine not supported");
1117 return CURLE_SSL_ENGINE_NOTFOUND;
1121 /* Sets engine as default for all SSL operations
1123 static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
1125 #ifdef HAVE_OPENSSL_ENGINE_H
1126 if(data->state.engine) {
1127 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
1128 infof(data, "set default crypto engine '%s'\n",
1129 ENGINE_get_id(data->state.engine));
1132 failf(data, "set default crypto engine '%s' failed",
1133 ENGINE_get_id(data->state.engine));
1134 return CURLE_SSL_ENGINE_SETFAILED;
1143 /* Return list of OpenSSL crypto engine names.
1145 static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
1147 struct curl_slist *list = NULL;
1148 #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
1149 struct curl_slist *beg;
1152 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1153 beg = curl_slist_append(list, ENGINE_get_id(e));
1155 curl_slist_free_all(list);
1166 static void ossl_close(struct ssl_connect_data *connssl)
1168 if(BACKEND->handle) {
1169 (void)SSL_shutdown(BACKEND->handle);
1170 SSL_set_connect_state(BACKEND->handle);
1172 SSL_free(BACKEND->handle);
1173 BACKEND->handle = NULL;
1176 SSL_CTX_free(BACKEND->ctx);
1177 BACKEND->ctx = NULL;
1182 * This function is called when an SSL connection is closed.
1184 static void Curl_ossl_close(struct connectdata *conn, int sockindex)
1186 ossl_close(&conn->ssl[sockindex]);
1187 ossl_close(&conn->proxy_ssl[sockindex]);
1191 * This function is called to shut down the SSL layer but keep the
1192 * socket open (CCC - Clear Command Channel)
1194 static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
1197 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1198 struct Curl_easy *data = conn->data;
1199 char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
1200 to be at least 256 bytes long. */
1201 unsigned long sslerror;
1207 /* This has only been tested on the proftpd server, and the mod_tls code
1208 sends a close notify alert without waiting for a close notify alert in
1209 response. Thus we wait for a close notify alert from the server, but
1210 we do not send one. Let's hope other servers do the same... */
1212 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1213 (void)SSL_shutdown(BACKEND->handle);
1215 if(BACKEND->handle) {
1216 buffsize = (int)sizeof(buf);
1218 int what = SOCKET_READABLE(conn->sock[sockindex],
1219 SSL_SHUTDOWN_TIMEOUT);
1223 /* Something to read, let's do it and hope that it is the close
1224 notify alert from the server */
1225 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
1226 err = SSL_get_error(BACKEND->handle, (int)nread);
1229 case SSL_ERROR_NONE: /* this is not an error */
1230 case SSL_ERROR_ZERO_RETURN: /* no more data */
1231 /* This is the expected response. There was no data but only
1232 the close notify alert */
1235 case SSL_ERROR_WANT_READ:
1236 /* there's data pending, re-invoke SSL_read() */
1237 infof(data, "SSL_ERROR_WANT_READ\n");
1239 case SSL_ERROR_WANT_WRITE:
1240 /* SSL wants a write. Really odd. Let's bail out. */
1241 infof(data, "SSL_ERROR_WANT_WRITE\n");
1245 /* openssl/ssl.h says "look at error stack/return value/errno" */
1246 sslerror = ERR_get_error();
1247 failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
1249 ossl_strerror(sslerror, buf, sizeof(buf)) :
1250 SSL_ERROR_to_str(err)),
1256 else if(0 == what) {
1258 failf(data, "SSL shutdown timeout");
1262 /* anything that gets here is fatally bad */
1263 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1267 } /* while()-loop for the select() */
1269 if(data->set.verbose) {
1270 #ifdef HAVE_SSL_GET_SHUTDOWN
1271 switch(SSL_get_shutdown(BACKEND->handle)) {
1272 case SSL_SENT_SHUTDOWN:
1273 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1275 case SSL_RECEIVED_SHUTDOWN:
1276 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1278 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1279 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1280 "SSL_RECEIVED__SHUTDOWN\n");
1286 SSL_free(BACKEND->handle);
1287 BACKEND->handle = NULL;
1292 static void Curl_ossl_session_free(void *ptr)
1295 SSL_SESSION_free(ptr);
1299 * This function is called when the 'data' struct is going away. Close
1300 * down everything and free all resources!
1302 static void Curl_ossl_close_all(struct Curl_easy *data)
1304 #ifdef HAVE_OPENSSL_ENGINE_H
1305 if(data->state.engine) {
1306 ENGINE_finish(data->state.engine);
1307 ENGINE_free(data->state.engine);
1308 data->state.engine = NULL;
1313 #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
1314 defined(HAVE_ERR_REMOVE_THREAD_STATE)
1315 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
1316 so we need to clean it here in case the thread will be killed. All OpenSSL
1317 code should extract the error in association with the error so clearing
1318 this queue here should be harmless at worst. */
1319 ERR_remove_thread_state(NULL);
1323 /* ====================================================== */
1326 /* Quote from RFC2818 section 3.1 "Server Identity"
1328 If a subjectAltName extension of type dNSName is present, that MUST
1329 be used as the identity. Otherwise, the (most specific) Common Name
1330 field in the Subject field of the certificate MUST be used. Although
1331 the use of the Common Name is existing practice, it is deprecated and
1332 Certification Authorities are encouraged to use the dNSName instead.
1334 Matching is performed using the matching rules specified by
1335 [RFC2459]. If more than one identity of a given type is present in
1336 the certificate (e.g., more than one dNSName name, a match in any one
1337 of the set is considered acceptable.) Names may contain the wildcard
1338 character * which is considered to match any single domain name
1339 component or component fragment. E.g., *.a.com matches foo.a.com but
1340 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1342 In some cases, the URI is specified as an IP address rather than a
1343 hostname. In this case, the iPAddress subjectAltName must be present
1344 in the certificate and must exactly match the IP in the URI.
1347 static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1349 bool matched = FALSE;
1350 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1352 struct Curl_easy *data = conn->data;
1353 STACK_OF(GENERAL_NAME) *altnames;
1355 struct in6_addr addr;
1357 struct in_addr addr;
1359 CURLcode result = CURLE_OK;
1360 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
1361 bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
1362 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1364 const char * const dispname = SSL_IS_PROXY() ?
1365 conn->http_proxy.host.dispname : conn->host.dispname;
1368 if(conn->bits.ipv6_ip &&
1369 Curl_inet_pton(AF_INET6, hostname, &addr)) {
1371 addrlen = sizeof(struct in6_addr);
1375 if(Curl_inet_pton(AF_INET, hostname, &addr)) {
1377 addrlen = sizeof(struct in_addr);
1380 /* get a "list" of alternative names */
1381 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1386 bool dnsmatched = FALSE;
1387 bool ipmatched = FALSE;
1389 /* get amount of alternatives, RFC2459 claims there MUST be at least
1390 one, but we don't depend on it... */
1391 numalts = sk_GENERAL_NAME_num(altnames);
1393 /* loop through all alternatives - until a dnsmatch */
1394 for(i = 0; (i < numalts) && !dnsmatched; i++) {
1395 /* get a handle to alternative name number i */
1396 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1398 if(check->type == GEN_DNS)
1400 else if(check->type == GEN_IPADD)
1403 /* only check alternatives of the same type the target is */
1404 if(check->type == target) {
1405 /* get data and length */
1406 const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
1407 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1410 case GEN_DNS: /* name/pattern comparison */
1411 /* The OpenSSL man page explicitly says: "In general it cannot be
1412 assumed that the data returned by ASN1_STRING_data() is null
1413 terminated or does not contain embedded nulls." But also that
1414 "The actual format of the data will depend on the actual string
1415 type itself: for example for and IA5String the data will be ASCII"
1417 Gisle researched the OpenSSL sources:
1418 "I checked the 0.9.6 and 0.9.8 sources before my patch and
1419 it always 0-terminates an IA5String."
1421 if((altlen == strlen(altptr)) &&
1422 /* if this isn't true, there was an embedded zero in the name
1423 string and we cannot match it. */
1424 Curl_cert_hostcheck(altptr, hostname)) {
1427 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1432 case GEN_IPADD: /* IP address comparison */
1433 /* compare alternative IP address if the data chunk is the same size
1434 our server IP address is */
1435 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1438 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1445 GENERAL_NAMES_free(altnames);
1447 if(dnsmatched || ipmatched)
1452 /* an alternative name matched */
1454 else if(dNSName || iPAddress) {
1455 infof(data, " subjectAltName does not match %s\n", dispname);
1456 failf(data, "SSL: no alternative certificate subject name matches "
1457 "target host name '%s'", dispname);
1458 result = CURLE_PEER_FAILED_VERIFICATION;
1461 /* we have to look to the last occurrence of a commonName in the
1462 distinguished one to get the most significant one. */
1465 /* The following is done because of a bug in 0.9.6b */
1467 unsigned char *nulstr = (unsigned char *)"";
1468 unsigned char *peer_CN = nulstr;
1470 X509_NAME *name = X509_get_subject_name(server_cert);
1472 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
1475 /* we have the name entry and we will now convert this to a string
1476 that we can use for comparison. Doing this we support BMPstring,
1481 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1483 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1484 is already UTF-8 encoded. We check for this case and copy the raw
1485 string manually to avoid the problem. This code can be made
1486 conditional in the future when OpenSSL has been fixed. Work-around
1487 brought by Alexis S. L. Carvalho. */
1489 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1490 j = ASN1_STRING_length(tmp);
1492 peer_CN = OPENSSL_malloc(j + 1);
1494 memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
1499 else /* not a UTF8 name */
1500 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1502 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1503 /* there was a terminating zero before the end of string, this
1504 cannot match and we return failure! */
1505 failf(data, "SSL: illegal cert name field");
1506 result = CURLE_PEER_FAILED_VERIFICATION;
1511 if(peer_CN == nulstr)
1514 /* convert peer_CN from UTF8 */
1515 CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
1516 strlen((char *)peer_CN));
1517 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1519 OPENSSL_free(peer_CN);
1525 /* error already detected, pass through */
1529 "SSL: unable to obtain common name from peer certificate");
1530 result = CURLE_PEER_FAILED_VERIFICATION;
1532 else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
1533 failf(data, "SSL: certificate subject name '%s' does not match "
1534 "target host name '%s'", peer_CN, dispname);
1535 result = CURLE_PEER_FAILED_VERIFICATION;
1538 infof(data, " common name: %s (matched)\n", peer_CN);
1541 OPENSSL_free(peer_CN);
1547 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1548 !defined(OPENSSL_NO_OCSP)
1549 static CURLcode verifystatus(struct connectdata *conn,
1550 struct ssl_connect_data *connssl)
1553 const unsigned char *p;
1554 CURLcode result = CURLE_OK;
1555 struct Curl_easy *data = conn->data;
1557 OCSP_RESPONSE *rsp = NULL;
1558 OCSP_BASICRESP *br = NULL;
1559 X509_STORE *st = NULL;
1560 STACK_OF(X509) *ch = NULL;
1562 long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &p);
1565 failf(data, "No OCSP response received");
1566 result = CURLE_SSL_INVALIDCERTSTATUS;
1570 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1572 failf(data, "Invalid OCSP response");
1573 result = CURLE_SSL_INVALIDCERTSTATUS;
1577 ocsp_status = OCSP_response_status(rsp);
1578 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1579 failf(data, "Invalid OCSP response status: %s (%d)",
1580 OCSP_response_status_str(ocsp_status), ocsp_status);
1581 result = CURLE_SSL_INVALIDCERTSTATUS;
1585 br = OCSP_response_get1_basic(rsp);
1587 failf(data, "Invalid OCSP response");
1588 result = CURLE_SSL_INVALIDCERTSTATUS;
1592 ch = SSL_get_peer_cert_chain(BACKEND->handle);
1593 st = SSL_CTX_get_cert_store(BACKEND->ctx);
1595 #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1596 (defined(LIBRESSL_VERSION_NUMBER) && \
1597 LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
1598 /* The authorized responder cert in the OCSP response MUST be signed by the
1599 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1600 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1601 expects this issuer to be present in the chain embedded in the OCSP
1602 response. So we add it if necessary. */
1604 /* First make sure the peer cert chain includes both a peer and an issuer,
1605 and the OCSP response contains a responder cert. */
1606 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1607 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1609 /* Find issuer of responder cert and add it to the OCSP response chain */
1610 for(i = 0; i < sk_X509_num(ch); i++) {
1611 X509 *issuer = sk_X509_value(ch, i);
1612 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1613 if(!OCSP_basic_add1_cert(br, issuer)) {
1614 failf(data, "Could not add issuer cert to OCSP response");
1615 result = CURLE_SSL_INVALIDCERTSTATUS;
1623 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1624 failf(data, "OCSP response verification failed");
1625 result = CURLE_SSL_INVALIDCERTSTATUS;
1629 for(i = 0; i < OCSP_resp_count(br); i++) {
1630 int cert_status, crl_reason;
1631 OCSP_SINGLERESP *single = NULL;
1633 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1635 single = OCSP_resp_get0(br, i);
1639 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1640 &thisupd, &nextupd);
1642 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1643 failf(data, "OCSP response has expired");
1644 result = CURLE_SSL_INVALIDCERTSTATUS;
1648 infof(data, "SSL certificate status: %s (%d)\n",
1649 OCSP_cert_status_str(cert_status), cert_status);
1651 switch(cert_status) {
1652 case V_OCSP_CERTSTATUS_GOOD:
1655 case V_OCSP_CERTSTATUS_REVOKED:
1656 result = CURLE_SSL_INVALIDCERTSTATUS;
1658 failf(data, "SSL certificate revocation reason: %s (%d)",
1659 OCSP_crl_reason_str(crl_reason), crl_reason);
1662 case V_OCSP_CERTSTATUS_UNKNOWN:
1663 result = CURLE_SSL_INVALIDCERTSTATUS;
1669 if(br) OCSP_BASICRESP_free(br);
1670 OCSP_RESPONSE_free(rsp);
1676 #endif /* USE_OPENSSL */
1678 /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1679 and thus this cannot be done there. */
1680 #ifdef SSL_CTRL_SET_MSG_CALLBACK
1682 static const char *ssl_msg_type(int ssl_ver, int msg)
1684 #ifdef SSL2_VERSION_MAJOR
1685 if(ssl_ver == SSL2_VERSION_MAJOR) {
1689 case SSL2_MT_CLIENT_HELLO:
1690 return "Client hello";
1691 case SSL2_MT_CLIENT_MASTER_KEY:
1692 return "Client key";
1693 case SSL2_MT_CLIENT_FINISHED:
1694 return "Client finished";
1695 case SSL2_MT_SERVER_HELLO:
1696 return "Server hello";
1697 case SSL2_MT_SERVER_VERIFY:
1698 return "Server verify";
1699 case SSL2_MT_SERVER_FINISHED:
1700 return "Server finished";
1701 case SSL2_MT_REQUEST_CERTIFICATE:
1702 return "Request CERT";
1703 case SSL2_MT_CLIENT_CERTIFICATE:
1704 return "Client CERT";
1709 if(ssl_ver == SSL3_VERSION_MAJOR) {
1711 case SSL3_MT_HELLO_REQUEST:
1712 return "Hello request";
1713 case SSL3_MT_CLIENT_HELLO:
1714 return "Client hello";
1715 case SSL3_MT_SERVER_HELLO:
1716 return "Server hello";
1717 #ifdef SSL3_MT_NEWSESSION_TICKET
1718 case SSL3_MT_NEWSESSION_TICKET:
1719 return "Newsession Ticket";
1721 case SSL3_MT_CERTIFICATE:
1722 return "Certificate";
1723 case SSL3_MT_SERVER_KEY_EXCHANGE:
1724 return "Server key exchange";
1725 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1726 return "Client key exchange";
1727 case SSL3_MT_CERTIFICATE_REQUEST:
1728 return "Request CERT";
1729 case SSL3_MT_SERVER_DONE:
1730 return "Server finished";
1731 case SSL3_MT_CERTIFICATE_VERIFY:
1732 return "CERT verify";
1733 case SSL3_MT_FINISHED:
1735 #ifdef SSL3_MT_CERTIFICATE_STATUS
1736 case SSL3_MT_CERTIFICATE_STATUS:
1737 return "Certificate Status";
1744 static const char *tls_rt_type(int type)
1747 #ifdef SSL3_RT_HEADER
1748 case SSL3_RT_HEADER:
1749 return "TLS header";
1751 case SSL3_RT_CHANGE_CIPHER_SPEC:
1752 return "TLS change cipher";
1755 case SSL3_RT_HANDSHAKE:
1756 return "TLS handshake";
1757 case SSL3_RT_APPLICATION_DATA:
1758 return "TLS app data";
1760 return "TLS Unknown";
1766 * Our callback from the SSL/TLS layers.
1768 static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1769 const void *buf, size_t len, SSL *ssl,
1772 struct Curl_easy *data;
1773 const char *msg_name, *tls_rt_name;
1776 int msg_type, txt_len;
1777 const char *verstr = NULL;
1778 struct connectdata *conn = userp;
1780 if(!conn || !conn->data || !conn->data->set.fdebug ||
1781 (direction != 0 && direction != 1))
1787 #ifdef SSL2_VERSION /* removed in recent versions */
1800 #ifdef TLS1_1_VERSION
1801 case TLS1_1_VERSION:
1805 #ifdef TLS1_2_VERSION
1806 case TLS1_2_VERSION:
1810 #ifdef TLS1_3_VERSION
1811 case TLS1_3_VERSION:
1818 snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1824 /* the info given when the version is zero is not that useful for us */
1826 ssl_ver >>= 8; /* check the upper 8 bits only below */
1828 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
1829 * always pass-up content-type as 0. But the interesting message-type
1832 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
1833 tls_rt_name = tls_rt_type(content_type);
1837 msg_type = *(char *)buf;
1838 msg_name = ssl_msg_type(ssl_ver, msg_type);
1840 txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
1841 verstr, direction?"OUT":"IN",
1842 tls_rt_name, msg_name, msg_type);
1843 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
1846 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
1847 CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
1853 /* ====================================================== */
1855 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1856 # define use_sni(x) sni = (x)
1858 # define use_sni(x) Curl_nop_stmt
1861 /* Check for OpenSSL 1.0.2 which has ALPN support. */
1863 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1864 && !defined(OPENSSL_NO_TLSEXT)
1868 /* Check for OpenSSL 1.0.1 which has NPN support. */
1870 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
1871 && !defined(OPENSSL_NO_TLSEXT) \
1872 && !defined(OPENSSL_NO_NEXTPROTONEG)
1879 * in is a list of length prefixed strings. this function has to select
1880 * the protocol we want to use from the list and write its string into out.
1884 select_next_protocol(unsigned char **out, unsigned char *outlen,
1885 const unsigned char *in, unsigned int inlen,
1886 const char *key, unsigned int keylen)
1889 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
1890 if(memcmp(&in[i + 1], key, keylen) == 0) {
1891 *out = (unsigned char *) &in[i + 1];
1900 select_next_proto_cb(SSL *ssl,
1901 unsigned char **out, unsigned char *outlen,
1902 const unsigned char *in, unsigned int inlen,
1905 struct connectdata *conn = (struct connectdata*) arg;
1910 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
1911 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
1912 NGHTTP2_PROTO_VERSION_ID_LEN)) {
1913 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
1914 NGHTTP2_PROTO_VERSION_ID);
1915 conn->negnpn = CURL_HTTP_VERSION_2;
1916 return SSL_TLSEXT_ERR_OK;
1920 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
1921 ALPN_HTTP_1_1_LENGTH)) {
1922 infof(conn->data, "NPN, negotiated HTTP1.1\n");
1923 conn->negnpn = CURL_HTTP_VERSION_1_1;
1924 return SSL_TLSEXT_ERR_OK;
1927 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
1928 *out = (unsigned char *)ALPN_HTTP_1_1;
1929 *outlen = ALPN_HTTP_1_1_LENGTH;
1930 conn->negnpn = CURL_HTTP_VERSION_1_1;
1932 return SSL_TLSEXT_ERR_OK;
1934 #endif /* HAS_NPN */
1937 get_ssl_version_txt(SSL *ssl)
1942 switch(SSL_version(ssl)) {
1943 #ifdef TLS1_3_VERSION
1944 case TLS1_3_VERSION:
1947 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1948 case TLS1_2_VERSION:
1950 case TLS1_1_VERSION:
1964 set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
1967 #if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION)
1968 /* convoluted #if condition just to avoid compiler warnings on unused
1970 struct Curl_easy *data = conn->data;
1972 long ssl_version = SSL_CONN_CONFIG(version);
1973 long ssl_version_max = SSL_CONN_CONFIG(version_max);
1975 if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) {
1976 ssl_version_max = ssl_version << 16;
1979 switch(ssl_version) {
1980 case CURL_SSLVERSION_TLSv1_3:
1981 #ifdef TLS1_3_VERSION
1983 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1984 SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION);
1985 *ctx_options |= SSL_OP_NO_TLSv1_2;
1989 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
1990 return CURLE_NOT_BUILT_IN;
1993 case CURL_SSLVERSION_TLSv1_2:
1994 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
1995 *ctx_options |= SSL_OP_NO_TLSv1_1;
1997 failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
1998 return CURLE_NOT_BUILT_IN;
2001 case CURL_SSLVERSION_TLSv1_1:
2002 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2003 *ctx_options |= SSL_OP_NO_TLSv1;
2005 failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
2006 return CURLE_NOT_BUILT_IN;
2009 case CURL_SSLVERSION_TLSv1_0:
2010 *ctx_options |= SSL_OP_NO_SSLv2;
2011 *ctx_options |= SSL_OP_NO_SSLv3;
2015 switch(ssl_version_max) {
2016 case CURL_SSLVERSION_MAX_TLSv1_0:
2017 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2018 *ctx_options |= SSL_OP_NO_TLSv1_1;
2021 case CURL_SSLVERSION_MAX_TLSv1_1:
2022 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2023 *ctx_options |= SSL_OP_NO_TLSv1_2;
2026 case CURL_SSLVERSION_MAX_TLSv1_2:
2027 case CURL_SSLVERSION_MAX_DEFAULT:
2028 #ifdef TLS1_3_VERSION
2029 *ctx_options |= SSL_OP_NO_TLSv1_3;
2032 case CURL_SSLVERSION_MAX_TLSv1_3:
2033 #ifdef TLS1_3_VERSION
2036 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2037 return CURLE_NOT_BUILT_IN;
2043 static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
2045 CURLcode result = CURLE_OK;
2047 struct Curl_easy *data = conn->data;
2048 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
2049 X509_LOOKUP *lookup = NULL;
2050 curl_socket_t sockfd = conn->sock[sockindex];
2051 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2052 long ctx_options = 0;
2053 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2055 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
2058 struct in6_addr addr;
2060 struct in_addr addr;
2063 long * const certverifyresult = SSL_IS_PROXY() ?
2064 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2065 const long int ssl_version = SSL_CONN_CONFIG(version);
2067 const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
2069 char * const ssl_cert = SSL_SET_OPTION(cert);
2070 const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
2071 const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
2072 const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
2073 const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
2074 const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
2075 char error_buffer[256];
2077 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
2079 /* Make funny stuff to get random input */
2080 result = Curl_ossl_seed(data);
2084 *certverifyresult = !X509_V_OK;
2086 /* check to see if we've been told to use an explicit SSL/TLS version */
2088 switch(ssl_version) {
2089 case CURL_SSLVERSION_DEFAULT:
2090 case CURL_SSLVERSION_TLSv1:
2091 case CURL_SSLVERSION_TLSv1_0:
2092 case CURL_SSLVERSION_TLSv1_1:
2093 case CURL_SSLVERSION_TLSv1_2:
2094 case CURL_SSLVERSION_TLSv1_3:
2095 /* it will be handled later with the context options */
2096 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
2097 !defined(LIBRESSL_VERSION_NUMBER)
2098 req_method = TLS_client_method();
2100 req_method = SSLv23_client_method();
2104 case CURL_SSLVERSION_SSLv2:
2105 #ifdef OPENSSL_NO_SSL2
2106 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2107 return CURLE_NOT_BUILT_IN;
2110 if(ssl_authtype == CURL_TLSAUTH_SRP)
2111 return CURLE_SSL_CONNECT_ERROR;
2113 req_method = SSLv2_client_method();
2117 case CURL_SSLVERSION_SSLv3:
2118 #ifdef OPENSSL_NO_SSL3_METHOD
2119 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
2120 return CURLE_NOT_BUILT_IN;
2123 if(ssl_authtype == CURL_TLSAUTH_SRP)
2124 return CURLE_SSL_CONNECT_ERROR;
2126 req_method = SSLv3_client_method();
2131 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2132 return CURLE_SSL_CONNECT_ERROR;
2136 SSL_CTX_free(BACKEND->ctx);
2137 BACKEND->ctx = SSL_CTX_new(req_method);
2140 failf(data, "SSL: couldn't create a context: %s",
2141 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
2142 return CURLE_OUT_OF_MEMORY;
2145 #ifdef SSL_MODE_RELEASE_BUFFERS
2146 SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS);
2149 #ifdef SSL_CTRL_SET_MSG_CALLBACK
2150 if(data->set.fdebug && data->set.verbose) {
2151 /* the SSL trace callback is only used for verbose logging */
2152 SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace);
2153 SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn);
2157 /* OpenSSL contains code to work-around lots of bugs and flaws in various
2158 SSL-implementations. SSL_CTX_set_options() is used to enabled those
2159 work-arounds. The man page for this option states that SSL_OP_ALL enables
2160 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
2161 enable the bug workaround options if compatibility with somewhat broken
2162 implementations is desired."
2164 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
2165 disable "rfc4507bis session ticket support". rfc4507bis was later turned
2166 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
2168 The enabled extension concerns the session management. I wonder how often
2169 libcurl stops a connection and then resumes a TLS session. also, sending
2170 the session data is some overhead. .I suggest that you just use your
2171 proposed patch (which explicitly disables TICKET).
2173 If someone writes an application with libcurl and openssl who wants to
2174 enable the feature, one can do this in the SSL callback.
2176 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
2177 interoperability with web server Netscape Enterprise Server 2.0.1 which
2178 was released back in 1996.
2180 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
2181 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
2182 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
2183 this option regardless of OpenSSL version and SSL_OP_ALL definition.
2185 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
2186 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
2187 SSL_OP_ALL that _disables_ that work-around despite the fact that
2188 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
2189 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
2193 ctx_options = SSL_OP_ALL;
2195 #ifdef SSL_OP_NO_TICKET
2196 ctx_options |= SSL_OP_NO_TICKET;
2199 #ifdef SSL_OP_NO_COMPRESSION
2200 ctx_options |= SSL_OP_NO_COMPRESSION;
2203 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2204 /* mitigate CVE-2010-4180 */
2205 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
2208 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2209 /* unless the user explicitly ask to allow the protocol vulnerability we
2210 use the work-around */
2211 if(!SSL_SET_OPTION(enable_beast))
2212 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2215 switch(ssl_version) {
2216 case CURL_SSLVERSION_SSLv3:
2218 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2219 infof(data, "Set version TLSv1.x for SRP authorisation\n");
2222 ctx_options |= SSL_OP_NO_SSLv2;
2223 ctx_options |= SSL_OP_NO_TLSv1;
2224 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2225 ctx_options |= SSL_OP_NO_TLSv1_1;
2226 ctx_options |= SSL_OP_NO_TLSv1_2;
2227 #ifdef TLS1_3_VERSION
2228 ctx_options |= SSL_OP_NO_TLSv1_3;
2233 case CURL_SSLVERSION_DEFAULT:
2234 case CURL_SSLVERSION_TLSv1:
2235 ctx_options |= SSL_OP_NO_SSLv2;
2236 ctx_options |= SSL_OP_NO_SSLv3;
2239 case CURL_SSLVERSION_TLSv1_0:
2240 case CURL_SSLVERSION_TLSv1_1:
2241 case CURL_SSLVERSION_TLSv1_2:
2242 case CURL_SSLVERSION_TLSv1_3:
2243 result = set_ssl_version_min_max(&ctx_options, conn, sockindex);
2244 if(result != CURLE_OK)
2248 case CURL_SSLVERSION_SSLv2:
2249 #ifndef OPENSSL_NO_SSL2
2250 ctx_options |= SSL_OP_NO_SSLv3;
2251 ctx_options |= SSL_OP_NO_TLSv1;
2252 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2253 ctx_options |= SSL_OP_NO_TLSv1_1;
2254 ctx_options |= SSL_OP_NO_TLSv1_2;
2255 #ifdef TLS1_3_VERSION
2256 ctx_options |= SSL_OP_NO_TLSv1_3;
2261 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2262 return CURLE_NOT_BUILT_IN;
2266 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2267 return CURLE_SSL_CONNECT_ERROR;
2270 SSL_CTX_set_options(BACKEND->ctx, ctx_options);
2273 if(conn->bits.tls_enable_npn)
2274 SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn);
2278 if(conn->bits.tls_enable_alpn) {
2280 unsigned char protocols[128];
2283 if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
2284 (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
2285 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
2287 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
2288 NGHTTP2_PROTO_VERSION_ID_LEN);
2289 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
2290 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
2294 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2295 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2296 cur += ALPN_HTTP_1_1_LENGTH;
2297 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
2299 /* expects length prefixed preference ordered list of protocols in wire
2302 SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur);
2306 if(ssl_cert || ssl_cert_type) {
2307 if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type,
2308 SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
2309 SSL_SET_OPTION(key_passwd))) {
2310 /* failf() is already done in cert_stuff() */
2311 return CURLE_SSL_CERTPROBLEM;
2315 ciphers = SSL_CONN_CONFIG(cipher_list);
2317 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2319 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
2320 failf(data, "failed setting cipher list: %s", ciphers);
2321 return CURLE_SSL_CIPHER;
2323 infof(data, "Cipher selection: %s\n", ciphers);
2327 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2328 char * const ssl_username = SSL_SET_OPTION(username);
2330 infof(data, "Using TLS-SRP username: %s\n", ssl_username);
2332 if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) {
2333 failf(data, "Unable to set SRP user name");
2334 return CURLE_BAD_FUNCTION_ARGUMENT;
2336 if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) {
2337 failf(data, "failed setting SRP password");
2338 return CURLE_BAD_FUNCTION_ARGUMENT;
2340 if(!SSL_CONN_CONFIG(cipher_list)) {
2341 infof(data, "Setting cipher list SRP\n");
2343 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) {
2344 failf(data, "failed setting SRP cipher list");
2345 return CURLE_SSL_CIPHER;
2351 if(ssl_cafile || ssl_capath) {
2353 /* tell SSL where to find CA certificates that are used to verify
2354 the servers certificate. */
2355 if(!SSL_CTX_load_verify_locations(BACKEND->ctx,
2356 ssl_cafile, ssl_capath)) {
2357 /* Fail if we insist on successfully verifying the server. */
2358 failf(data, "error setting certificate verify locations:\n"
2359 " CAfile: %s\n CApath: %s",
2360 ssl_cafile ? ssl_cafile : "none",
2361 ssl_capath ? ssl_capath : "none");
2362 return CURLE_SSL_CACERT_BADFILE;
2365 /* Everything is fine. */
2366 infof(data, "successfully set certificate verify locations:\n"
2367 " CAfile: %s\n CApath: %s\n",
2368 ssl_cafile ? ssl_cafile : "none",
2369 ssl_capath ? ssl_capath : "none");
2373 infof(data, "ignoring certificate verify locations due to "
2374 "disabled peer verification\n");
2377 #ifdef CURL_CA_FALLBACK
2378 else if(verifypeer) {
2379 /* verfying the peer without any CA certificates won't
2380 work so use openssl's built in default as fallback */
2381 SSL_CTX_set_default_verify_paths(BACKEND->ctx);
2386 /* tell SSL where to find CRL file that is used to check certificate
2388 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx),
2389 X509_LOOKUP_file());
2391 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
2392 failf(data, "error loading CRL file: %s", ssl_crlfile);
2393 return CURLE_SSL_CRL_BADFILE;
2395 /* Everything is fine. */
2396 infof(data, "successfully load CRL file:\n");
2397 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2398 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2400 infof(data, " CRLfile: %s\n", ssl_crlfile);
2403 /* Try building a chain using issuers in the trusted store first to avoid
2404 problems with server-sent legacy intermediates.
2405 Newer versions of OpenSSL do alternate chain checking by default which
2406 gives us the same fix without as much of a performance hit (slight), so we
2407 prefer that if available.
2408 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2410 #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2412 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2413 X509_V_FLAG_TRUSTED_FIRST);
2417 /* SSL always tries to verify the peer, this only says whether it should
2418 * fail to connect if the verification fails, or if it should continue
2419 * anyway. In the latter case the result of the verification is checked with
2420 * SSL_get_verify_result() below. */
2421 SSL_CTX_set_verify(BACKEND->ctx,
2422 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
2424 /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
2425 #if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK)
2426 if(keylog_file_fp) {
2427 SSL_CTX_set_keylog_callback(BACKEND->ctx, ossl_keylog_callback);
2431 /* give application a chance to interfere with SSL set up. */
2432 if(data->set.ssl.fsslctx) {
2433 result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
2434 data->set.ssl.fsslctxp);
2436 failf(data, "error signaled by ssl ctx callback");
2441 /* Lets make an SSL structure */
2443 SSL_free(BACKEND->handle);
2444 BACKEND->handle = SSL_new(BACKEND->ctx);
2445 if(!BACKEND->handle) {
2446 failf(data, "SSL: couldn't create a context (handle)!");
2447 return CURLE_OUT_OF_MEMORY;
2450 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2451 !defined(OPENSSL_NO_OCSP)
2452 if(SSL_CONN_CONFIG(verifystatus))
2453 SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp);
2456 SSL_set_connect_state(BACKEND->handle);
2458 BACKEND->server_cert = 0x0;
2459 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2460 if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
2462 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
2465 !SSL_set_tlsext_host_name(BACKEND->handle, hostname))
2466 infof(data, "WARNING: failed to configure server name indication (SNI) "
2470 /* Check if there's a cached ID we can/should use here! */
2471 if(SSL_SET_OPTION(primary.sessionid)) {
2472 void *ssl_sessionid = NULL;
2474 Curl_ssl_sessionid_lock(conn);
2475 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
2476 /* we got a session id, use it! */
2477 if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
2478 Curl_ssl_sessionid_unlock(conn);
2479 failf(data, "SSL: SSL_set_session failed: %s",
2480 ossl_strerror(ERR_get_error(), error_buffer,
2481 sizeof(error_buffer)));
2482 return CURLE_SSL_CONNECT_ERROR;
2484 /* Informational message */
2485 infof(data, "SSL re-using session ID\n");
2487 Curl_ssl_sessionid_unlock(conn);
2490 if(conn->proxy_ssl[sockindex].use) {
2491 BIO *const bio = BIO_new(BIO_f_ssl());
2492 SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
2493 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2494 DEBUGASSERT(handle != NULL);
2495 DEBUGASSERT(bio != NULL);
2496 BIO_set_ssl(bio, handle, FALSE);
2497 SSL_set_bio(BACKEND->handle, bio, bio);
2499 else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
2500 /* pass the raw socket into the SSL layers */
2501 failf(data, "SSL: SSL_set_fd failed: %s",
2502 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
2503 return CURLE_SSL_CONNECT_ERROR;
2506 connssl->connecting_state = ssl_connect_2;
2511 static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2513 struct Curl_easy *data = conn->data;
2515 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2516 long * const certverifyresult = SSL_IS_PROXY() ?
2517 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2518 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2519 || ssl_connect_2_reading == connssl->connecting_state
2520 || ssl_connect_2_writing == connssl->connecting_state);
2524 err = SSL_connect(BACKEND->handle);
2525 /* If keylogging is enabled but the keylog callback is not supported then log
2526 secrets here, immediately after SSL_connect by using tap_ssl_key. */
2527 #if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK)
2528 tap_ssl_key(BACKEND->handle, &BACKEND->tap_state);
2532 0 is "not successful but was shut down controlled"
2533 <0 is "handshake was not successful, because a fatal error occurred" */
2535 int detail = SSL_get_error(BACKEND->handle, err);
2537 if(SSL_ERROR_WANT_READ == detail) {
2538 connssl->connecting_state = ssl_connect_2_reading;
2541 if(SSL_ERROR_WANT_WRITE == detail) {
2542 connssl->connecting_state = ssl_connect_2_writing;
2546 /* untreated error */
2547 unsigned long errdetail;
2548 char error_buffer[256]="";
2554 /* the connection failed, we're not waiting for anything else. */
2555 connssl->connecting_state = ssl_connect_2;
2557 /* Get the earliest error code from the thread's error queue and removes
2559 errdetail = ERR_get_error();
2561 /* Extract which lib and reason */
2562 lib = ERR_GET_LIB(errdetail);
2563 reason = ERR_GET_REASON(errdetail);
2565 if((lib == ERR_LIB_SSL) &&
2566 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2567 result = CURLE_SSL_CACERT;
2569 lerr = SSL_get_verify_result(BACKEND->handle);
2570 if(lerr != X509_V_OK) {
2571 *certverifyresult = lerr;
2572 snprintf(error_buffer, sizeof(error_buffer),
2573 "SSL certificate problem: %s",
2574 X509_verify_cert_error_string(lerr));
2577 /* strcpy() is fine here as long as the string fits within
2579 strcpy(error_buffer, "SSL certificate verification failed");
2582 result = CURLE_SSL_CONNECT_ERROR;
2583 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
2586 /* detail is already set to the SSL error above */
2588 /* If we e.g. use SSLv2 request-method and the server doesn't like us
2589 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
2590 * the SO_ERROR is also lost.
2592 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
2593 const char * const hostname = SSL_IS_PROXY() ?
2594 conn->http_proxy.host.name : conn->host.name;
2595 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
2596 failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
2597 SSL_ERROR_to_str(detail), hostname, port);
2601 /* Could be a CERT problem */
2602 failf(data, "%s", error_buffer);
2608 /* we have been connected fine, we're not waiting for anything else. */
2609 connssl->connecting_state = ssl_connect_3;
2611 /* Informational message */
2612 infof(data, "SSL connection using %s / %s\n",
2613 get_ssl_version_txt(BACKEND->handle),
2614 SSL_get_cipher(BACKEND->handle));
2617 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
2620 if(conn->bits.tls_enable_alpn) {
2621 const unsigned char *neg_protocol;
2623 SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len);
2625 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
2628 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
2629 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
2630 conn->negnpn = CURL_HTTP_VERSION_2;
2634 if(len == ALPN_HTTP_1_1_LENGTH &&
2635 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
2636 conn->negnpn = CURL_HTTP_VERSION_1_1;
2640 infof(data, "ALPN, server did not agree to a protocol\n");
2648 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
2654 return 1; /* buffer too big */
2656 i = i2t_ASN1_OBJECT(buf, ilen, a);
2659 return 1; /* buffer too small */
2664 #define push_certinfo(_label, _num) \
2666 long info_len = BIO_get_mem_data(mem, &ptr); \
2667 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
2668 if(1 != BIO_reset(mem)) \
2672 static void pubkey_show(struct Curl_easy *data,
2677 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2685 snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
2689 push_certinfo(namebuf, num);
2692 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2693 #define print_pubkey_BN(_type, _name, _num) \
2694 pubkey_show(data, mem, _num, #_type, #_name, _name)
2697 #define print_pubkey_BN(_type, _name, _num) \
2699 if(_type->_name) { \
2700 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
2705 static int X509V3_ext(struct Curl_easy *data,
2707 CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
2712 if((int)sk_X509_EXTENSION_num(exts) <= 0)
2713 /* no extensions, bail out */
2716 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
2718 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
2723 BIO *bio_out = BIO_new(BIO_s_mem());
2728 obj = X509_EXTENSION_get_object(ext);
2730 asn1_object_dump(obj, namebuf, sizeof(namebuf));
2732 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
2733 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
2735 BIO_get_mem_ptr(bio_out, &biomem);
2737 for(j = 0; j < (size_t)biomem->length; j++) {
2738 const char *sep = "";
2739 if(biomem->data[j] == '\n') {
2741 j++; /* skip the newline */
2743 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
2745 if(j<(size_t)biomem->length)
2746 ptr += snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
2750 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
2755 return 0; /* all is fine */
2758 static CURLcode get_cert_chain(struct connectdata *conn,
2759 struct ssl_connect_data *connssl)
2765 struct Curl_easy *data = conn->data;
2769 sk = SSL_get_peer_cert_chain(BACKEND->handle);
2771 return CURLE_OUT_OF_MEMORY;
2774 numcerts = sk_X509_num(sk);
2776 result = Curl_ssl_init_certinfo(data, numcerts);
2781 mem = BIO_new(BIO_s_mem());
2783 for(i = 0; i < numcerts; i++) {
2785 X509 *x = sk_X509_value(sk, i);
2786 EVP_PKEY *pubkey = NULL;
2789 const ASN1_BIT_STRING *psig = NULL;
2791 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
2792 push_certinfo("Subject", i);
2794 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
2795 push_certinfo("Issuer", i);
2797 BIO_printf(mem, "%lx", X509_get_version(x));
2798 push_certinfo("Version", i);
2800 num = X509_get_serialNumber(x);
2801 if(num->type == V_ASN1_NEG_INTEGER)
2803 for(j = 0; j < num->length; j++)
2804 BIO_printf(mem, "%02x", num->data[j]);
2805 push_certinfo("Serial Number", i);
2807 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
2809 const X509_ALGOR *palg = NULL;
2810 ASN1_STRING *a = ASN1_STRING_new();
2812 X509_get0_signature(&psig, &palg, x);
2813 X509_signature_print(mem, palg, a);
2814 ASN1_STRING_free(a);
2817 i2a_ASN1_OBJECT(mem, palg->algorithm);
2818 push_certinfo("Public Key Algorithm", i);
2821 X509V3_ext(data, i, X509_get0_extensions(x));
2825 /* before OpenSSL 1.0.2 */
2826 X509_CINF *cinf = x->cert_info;
2828 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
2829 push_certinfo("Signature Algorithm", i);
2831 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
2832 push_certinfo("Public Key Algorithm", i);
2834 X509V3_ext(data, i, cinf->extensions);
2836 psig = x->signature;
2840 ASN1_TIME_print(mem, X509_get0_notBefore(x));
2841 push_certinfo("Start date", i);
2843 ASN1_TIME_print(mem, X509_get0_notAfter(x));
2844 push_certinfo("Expire date", i);
2846 pubkey = X509_get_pubkey(x);
2848 infof(data, " Unable to load public key\n");
2851 #ifdef HAVE_OPAQUE_EVP_PKEY
2852 pktype = EVP_PKEY_id(pubkey);
2854 pktype = pubkey->type;
2860 #ifdef HAVE_OPAQUE_EVP_PKEY
2861 rsa = EVP_PKEY_get0_RSA(pubkey);
2863 rsa = pubkey->pkey.rsa;
2866 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2871 RSA_get0_key(rsa, &n, &e, NULL);
2873 push_certinfo("RSA Public Key", i);
2874 print_pubkey_BN(rsa, n, i);
2875 print_pubkey_BN(rsa, e, i);
2878 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
2879 push_certinfo("RSA Public Key", i);
2880 print_pubkey_BN(rsa, n, i);
2881 print_pubkey_BN(rsa, e, i);
2888 #ifndef OPENSSL_NO_DSA
2890 #ifdef HAVE_OPAQUE_EVP_PKEY
2891 dsa = EVP_PKEY_get0_DSA(pubkey);
2893 dsa = pubkey->pkey.dsa;
2895 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2900 const BIGNUM *pub_key;
2902 DSA_get0_pqg(dsa, &p, &q, &g);
2903 DSA_get0_key(dsa, &pub_key, NULL);
2905 print_pubkey_BN(dsa, p, i);
2906 print_pubkey_BN(dsa, q, i);
2907 print_pubkey_BN(dsa, g, i);
2908 print_pubkey_BN(dsa, pub_key, i);
2911 print_pubkey_BN(dsa, p, i);
2912 print_pubkey_BN(dsa, q, i);
2913 print_pubkey_BN(dsa, g, i);
2914 print_pubkey_BN(dsa, pub_key, i);
2916 #endif /* !OPENSSL_NO_DSA */
2922 #ifdef HAVE_OPAQUE_EVP_PKEY
2923 dh = EVP_PKEY_get0_DH(pubkey);
2925 dh = pubkey->pkey.dh;
2927 #ifdef HAVE_OPAQUE_RSA_DSA_DH
2932 const BIGNUM *pub_key;
2933 DH_get0_pqg(dh, &p, &q, &g);
2934 DH_get0_key(dh, &pub_key, NULL);
2935 print_pubkey_BN(dh, p, i);
2936 print_pubkey_BN(dh, q, i);
2937 print_pubkey_BN(dh, g, i);
2938 print_pubkey_BN(dh, pub_key, i);
2941 print_pubkey_BN(dh, p, i);
2942 print_pubkey_BN(dh, g, i);
2943 print_pubkey_BN(dh, pub_key, i);
2948 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
2953 EVP_PKEY_free(pubkey);
2957 for(j = 0; j < psig->length; j++)
2958 BIO_printf(mem, "%02x:", psig->data[j]);
2959 push_certinfo("Signature", i);
2962 PEM_write_bio_X509(mem, x);
2963 push_certinfo("Cert", i);
2972 * Heavily modified from:
2973 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
2975 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
2976 const char *pinnedpubkey)
2979 int len1 = 0, len2 = 0;
2980 unsigned char *buff1 = NULL, *temp = NULL;
2982 /* Result is returned to caller */
2983 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
2985 /* if a path wasn't specified, don't pin */
2993 /* Begin Gyrations to get the subjectPublicKeyInfo */
2994 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
2996 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
2997 /thread/d61858dae102c6c7 */
2998 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
3002 /* https://www.openssl.org/docs/crypto/buffer.html */
3003 buff1 = temp = malloc(len1);
3007 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
3008 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
3011 * These checks are verifying we got back the same values as when we
3012 * sized the buffer. It's pretty weak since they should always be the
3013 * same. But it gives us something to test.
3015 if((len1 != len2) || !temp || ((temp - buff1) != len1))
3020 /* The one good exit point */
3021 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
3024 /* https://www.openssl.org/docs/crypto/buffer.html */
3032 * Get the server cert, verify it and show it etc, only call failf() if the
3033 * 'strict' argument is TRUE as otherwise all this is for informational
3036 * We check certificates to authenticate the server; otherwise we risk
3037 * man-in-the-middle attack.
3039 static CURLcode servercert(struct connectdata *conn,
3040 struct ssl_connect_data *connssl,
3043 CURLcode result = CURLE_OK;
3046 struct Curl_easy *data = conn->data;
3051 long * const certverifyresult = SSL_IS_PROXY() ?
3052 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
3053 BIO *mem = BIO_new(BIO_s_mem());
3055 if(data->set.ssl.certinfo)
3056 /* we've been asked to gather certificate info! */
3057 (void)get_cert_chain(conn, connssl);
3059 BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle);
3060 if(!BACKEND->server_cert) {
3065 failf(data, "SSL: couldn't get peer certificate!");
3066 return CURLE_PEER_FAILED_VERIFICATION;
3069 infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
3071 rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert),
3072 buffer, sizeof(buffer));
3073 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
3075 ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert));
3076 len = BIO_get_mem_data(mem, (char **) &ptr);
3077 infof(data, " start date: %.*s\n", len, ptr);
3078 (void)BIO_reset(mem);
3080 ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert));
3081 len = BIO_get_mem_data(mem, (char **) &ptr);
3082 infof(data, " expire date: %.*s\n", len, ptr);
3083 (void)BIO_reset(mem);
3087 if(SSL_CONN_CONFIG(verifyhost)) {
3088 result = verifyhost(conn, BACKEND->server_cert);
3090 X509_free(BACKEND->server_cert);
3091 BACKEND->server_cert = NULL;
3096 rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert),
3097 buffer, sizeof(buffer));
3100 failf(data, "SSL: couldn't get X509-issuer name!");
3101 result = CURLE_SSL_CONNECT_ERROR;
3104 infof(data, " issuer: %s\n", buffer);
3106 /* We could do all sorts of certificate verification stuff here before
3107 deallocating the certificate. */
3109 /* e.g. match issuer name with provided issuer certificate */
3110 if(SSL_SET_OPTION(issuercert)) {
3111 fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
3114 failf(data, "SSL: Unable to open issuer cert (%s)",
3115 SSL_SET_OPTION(issuercert));
3116 X509_free(BACKEND->server_cert);
3117 BACKEND->server_cert = NULL;
3118 return CURLE_SSL_ISSUER_ERROR;
3121 issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
3124 failf(data, "SSL: Unable to read issuer cert (%s)",
3125 SSL_SET_OPTION(issuercert));
3126 X509_free(BACKEND->server_cert);
3129 return CURLE_SSL_ISSUER_ERROR;
3134 if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) {
3136 failf(data, "SSL: Certificate issuer check failed (%s)",
3137 SSL_SET_OPTION(issuercert));
3138 X509_free(BACKEND->server_cert);
3140 BACKEND->server_cert = NULL;
3141 return CURLE_SSL_ISSUER_ERROR;
3144 infof(data, " SSL certificate issuer check ok (%s)\n",
3145 SSL_SET_OPTION(issuercert));
3149 lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle);
3151 if(*certverifyresult != X509_V_OK) {
3152 if(SSL_CONN_CONFIG(verifypeer)) {
3153 /* We probably never reach this, because SSL_connect() will fail
3154 and we return earlier if verifypeer is set? */
3156 failf(data, "SSL certificate verify result: %s (%ld)",
3157 X509_verify_cert_error_string(lerr), lerr);
3158 result = CURLE_PEER_FAILED_VERIFICATION;
3161 infof(data, " SSL certificate verify result: %s (%ld),"
3162 " continuing anyway.\n",
3163 X509_verify_cert_error_string(lerr), lerr);
3166 infof(data, " SSL certificate verify ok.\n");
3169 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3170 !defined(OPENSSL_NO_OCSP)
3171 if(SSL_CONN_CONFIG(verifystatus)) {
3172 result = verifystatus(conn, connssl);
3174 X509_free(BACKEND->server_cert);
3175 BACKEND->server_cert = NULL;
3182 /* when not strict, we don't bother about the verify cert problems */
3185 ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
3186 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
3187 if(!result && ptr) {
3188 result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr);
3190 failf(data, "SSL: public key does not match pinned public key!");
3193 X509_free(BACKEND->server_cert);
3194 BACKEND->server_cert = NULL;
3195 connssl->connecting_state = ssl_connect_done;
3200 static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
3202 CURLcode result = CURLE_OK;
3203 struct Curl_easy *data = conn->data;
3204 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3206 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
3208 if(SSL_SET_OPTION(primary.sessionid)) {
3210 SSL_SESSION *our_ssl_sessionid;
3211 void *old_ssl_sessionid = NULL;
3213 our_ssl_sessionid = SSL_get1_session(BACKEND->handle);
3215 /* SSL_get1_session() will increment the reference count and the session
3216 will stay in memory until explicitly freed with SSL_SESSION_free(3),
3217 regardless of its state. */
3219 Curl_ssl_sessionid_lock(conn);
3220 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
3223 if(old_ssl_sessionid != our_ssl_sessionid) {
3224 infof(data, "old SSL session ID is stale, removing\n");
3225 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
3231 result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
3232 0 /* unknown size */, sockindex);
3234 Curl_ssl_sessionid_unlock(conn);
3235 failf(data, "failed to store ssl session");
3240 /* Session was incache, so refcount already incremented earlier.
3241 * Avoid further increments with each SSL_get1_session() call.
3242 * This does not free the session as refcount remains > 0
3244 SSL_SESSION_free(our_ssl_sessionid);
3246 Curl_ssl_sessionid_unlock(conn);
3250 * We check certificates to authenticate the server; otherwise we risk
3251 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
3252 * verify the peer ignore faults and failures from the server cert
3256 result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
3257 SSL_CONN_CONFIG(verifyhost)));
3260 connssl->connecting_state = ssl_connect_done;
3265 static Curl_recv ossl_recv;
3266 static Curl_send ossl_send;
3268 static CURLcode ossl_connect_common(struct connectdata *conn,
3274 struct Curl_easy *data = conn->data;
3275 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3276 curl_socket_t sockfd = conn->sock[sockindex];
3280 /* check if the connection has already been established */
3281 if(ssl_connection_complete == connssl->state) {
3286 if(ssl_connect_1 == connssl->connecting_state) {
3287 /* Find out how much more time we're allowed */
3288 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3290 if(timeout_ms < 0) {
3291 /* no need to continue if time already is up */
3292 failf(data, "SSL connection timeout");
3293 return CURLE_OPERATION_TIMEDOUT;
3296 result = ossl_connect_step1(conn, sockindex);
3301 while(ssl_connect_2 == connssl->connecting_state ||
3302 ssl_connect_2_reading == connssl->connecting_state ||
3303 ssl_connect_2_writing == connssl->connecting_state) {
3305 /* check allowed time left */
3306 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3308 if(timeout_ms < 0) {
3309 /* no need to continue if time already is up */
3310 failf(data, "SSL connection timeout");
3311 return CURLE_OPERATION_TIMEDOUT;
3314 /* if ssl is expecting something, check if it's available. */
3315 if(connssl->connecting_state == ssl_connect_2_reading ||
3316 connssl->connecting_state == ssl_connect_2_writing) {
3318 curl_socket_t writefd = ssl_connect_2_writing ==
3319 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3320 curl_socket_t readfd = ssl_connect_2_reading ==
3321 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3323 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
3324 nonblocking?0:timeout_ms);
3327 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
3328 return CURLE_SSL_CONNECT_ERROR;
3336 failf(data, "SSL connection timeout");
3337 return CURLE_OPERATION_TIMEDOUT;
3339 /* socket is readable or writable */
3342 /* Run transaction, and return to the caller if it failed or if this
3343 * connection is done nonblocking and this loop would execute again. This
3344 * permits the owner of a multi handle to abort a connection attempt
3345 * before step2 has completed while ensuring that a client using select()
3346 * or epoll() will always have a valid fdset to wait on.
3348 result = ossl_connect_step2(conn, sockindex);
3349 if(result || (nonblocking &&
3350 (ssl_connect_2 == connssl->connecting_state ||
3351 ssl_connect_2_reading == connssl->connecting_state ||
3352 ssl_connect_2_writing == connssl->connecting_state)))
3355 } /* repeat step2 until all transactions are done. */
3357 if(ssl_connect_3 == connssl->connecting_state) {
3358 result = ossl_connect_step3(conn, sockindex);
3363 if(ssl_connect_done == connssl->connecting_state) {
3364 connssl->state = ssl_connection_complete;
3365 conn->recv[sockindex] = ossl_recv;
3366 conn->send[sockindex] = ossl_send;
3372 /* Reset our connect state machine */
3373 connssl->connecting_state = ssl_connect_1;
3378 static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
3382 return ossl_connect_common(conn, sockindex, TRUE, done);
3385 static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
3390 result = ossl_connect_common(conn, sockindex, FALSE, &done);
3399 static bool Curl_ossl_data_pending(const struct connectdata *conn,
3402 const struct ssl_connect_data *connssl = &conn->ssl[connindex];
3403 const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
3405 if(connssl->backend->handle && SSL_pending(connssl->backend->handle))
3408 if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle))
3414 static size_t Curl_ossl_version(char *buffer, size_t size);
3416 static ssize_t ossl_send(struct connectdata *conn,
3422 /* SSL_write() is said to return 'int' while write() and send() returns
3425 char error_buffer[256];
3426 unsigned long sslerror;
3429 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3433 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3434 rc = SSL_write(BACKEND->handle, mem, memlen);
3437 err = SSL_get_error(BACKEND->handle, rc);
3440 case SSL_ERROR_WANT_READ:
3441 case SSL_ERROR_WANT_WRITE:
3442 /* The operation did not complete; the same TLS/SSL I/O function
3443 should be called again later. This is basically an EWOULDBLOCK
3445 *curlcode = CURLE_AGAIN;
3447 case SSL_ERROR_SYSCALL:
3448 failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
3450 *curlcode = CURLE_SEND_ERROR;
3453 /* A failure in the SSL library occurred, usually a protocol error.
3454 The OpenSSL error queue contains more information on the error. */
3455 sslerror = ERR_get_error();
3456 if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
3457 ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
3458 conn->ssl[sockindex].state == ssl_connection_complete &&
3459 conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
3461 Curl_ossl_version(ver, 120);
3462 failf(conn->data, "Error: %s does not support double SSL tunneling.",
3466 failf(conn->data, "SSL_write() error: %s",
3467 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
3468 *curlcode = CURLE_SEND_ERROR;
3472 failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
3473 SSL_ERROR_to_str(err), SOCKERRNO);
3474 *curlcode = CURLE_SEND_ERROR;
3477 *curlcode = CURLE_OK;
3478 return (ssize_t)rc; /* number of bytes */
3481 static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3482 int num, /* socketindex */
3483 char *buf, /* store read data here */
3484 size_t buffersize, /* max amount to read */
3487 char error_buffer[256];
3488 unsigned long sslerror;
3491 struct ssl_connect_data *connssl = &conn->ssl[num];
3495 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3496 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
3498 /* failed SSL_read */
3499 int err = SSL_get_error(BACKEND->handle, (int)nread);
3502 case SSL_ERROR_NONE: /* this is not an error */
3503 case SSL_ERROR_ZERO_RETURN: /* no more data */
3505 case SSL_ERROR_WANT_READ:
3506 case SSL_ERROR_WANT_WRITE:
3507 /* there's data pending, re-invoke SSL_read() */
3508 *curlcode = CURLE_AGAIN;
3511 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3513 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3514 sslerror = ERR_get_error();
3515 if((nread < 0) || sslerror) {
3516 /* If the return code was negative or there actually is an error in the
3518 failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d",
3520 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)) :
3521 SSL_ERROR_to_str(err)),
3523 *curlcode = CURLE_RECV_ERROR;
3531 static size_t Curl_ossl_version(char *buffer, size_t size)
3533 #ifdef OPENSSL_IS_BORINGSSL
3534 return snprintf(buffer, size, OSSL_PACKAGE);
3535 #else /* OPENSSL_IS_BORINGSSL */
3537 unsigned long ssleay_value;
3540 ssleay_value = OpenSSL_version_num();
3541 if(ssleay_value < 0x906000) {
3542 ssleay_value = SSLEAY_VERSION_NUMBER;
3546 if(ssleay_value&0xff0) {
3547 int minor_ver = (ssleay_value >> 4) & 0xff;
3548 if(minor_ver > 26) {
3549 /* handle extended version introduced for 0.9.8za */
3550 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
3554 sub[0] = (char) (minor_ver + 'a' - 1);
3561 return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
3563 (ssleay_value>>28)&0xf,
3564 (ssleay_value>>20)&0xff,
3565 (ssleay_value>>12)&0xff,
3567 #endif /* OPENSSL_IS_BORINGSSL */
3570 /* can be called with data == NULL */
3571 static CURLcode Curl_ossl_random(struct Curl_easy *data,
3572 unsigned char *entropy, size_t length)
3576 if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
3577 return CURLE_FAILED_INIT; /* couldn't seed for some reason */
3581 return CURLE_FAILED_INIT;
3583 /* RAND_bytes() returns 1 on success, 0 otherwise. */
3584 rc = RAND_bytes(entropy, curlx_uztosi(length));
3585 return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
3588 static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */
3590 unsigned char *md5sum /* output */,
3594 unsigned int len = 0;
3597 mdctx = EVP_MD_CTX_create();
3598 EVP_DigestInit_ex(mdctx, EVP_md5(), NULL);
3599 EVP_DigestUpdate(mdctx, tmp, tmplen);
3600 EVP_DigestFinal_ex(mdctx, md5sum, &len);
3601 EVP_MD_CTX_destroy(mdctx);
3605 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3606 static void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
3608 unsigned char *sha256sum /* output */,
3612 unsigned int len = 0;
3615 mdctx = EVP_MD_CTX_create();
3616 EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL);
3617 EVP_DigestUpdate(mdctx, tmp, tmplen);
3618 EVP_DigestFinal_ex(mdctx, sha256sum, &len);
3619 EVP_MD_CTX_destroy(mdctx);
3623 static bool Curl_ossl_cert_status_request(void)
3625 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3626 !defined(OPENSSL_NO_OCSP)
3633 static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl,
3636 /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
3637 return info == CURLINFO_TLS_SESSION ?
3638 (void *)BACKEND->ctx : (void *)BACKEND->handle;
3641 const struct Curl_ssl Curl_ssl_openssl = {
3642 { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
3644 1, /* have_ca_path */
3645 1, /* have_certinfo */
3646 1, /* have_pinnedpubkey */
3647 1, /* have_ssl_ctx */
3648 1, /* support_https_proxy */
3650 sizeof(struct ssl_backend_data),
3652 Curl_ossl_init, /* init */
3653 Curl_ossl_cleanup, /* cleanup */
3654 Curl_ossl_version, /* version */
3655 Curl_ossl_check_cxn, /* check_cxn */
3656 Curl_ossl_shutdown, /* shutdown */
3657 Curl_ossl_data_pending, /* data_pending */
3658 Curl_ossl_random, /* random */
3659 Curl_ossl_cert_status_request, /* cert_status_request */
3660 Curl_ossl_connect, /* connect */
3661 Curl_ossl_connect_nonblocking, /* connect_nonblocking */
3662 Curl_ossl_get_internals, /* get_internals */
3663 Curl_ossl_close, /* close_one */
3664 Curl_ossl_close_all, /* close_all */
3665 Curl_ossl_session_free, /* session_free */
3666 Curl_ossl_set_engine, /* set_engine */
3667 Curl_ossl_set_engine_default, /* set_engine_default */
3668 Curl_ossl_engines_list, /* engines_list */
3669 Curl_none_false_start, /* false_start */
3670 Curl_ossl_md5sum, /* md5sum */
3671 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3672 Curl_ossl_sha256sum /* sha256sum */
3674 NULL /* sha256sum */
3678 #endif /* USE_OPENSSL */