1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
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.
13 *
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.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ***************************************************************************/
22
23/*
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.
26 */
27
28#include "curl_setup.h"
29
30#ifdef USE_OPENSSL
31
32#include <limits.h>
33
34#include "urldata.h"
35#include "sendf.h"
36#include "formdata.h" /* for the boundary function */
37#include "url.h" /* for the ssl config check function */
38#include "inet_pton.h"
39#include "openssl.h"
40#include "connect.h"
41#include "slist.h"
42#include "select.h"
43#include "vtls.h"
44#include "strcase.h"
45#include "hostcheck.h"
46#include "multiif.h"
47#include "strerror.h"
48#include "curl_printf.h"
49#include <openssl/ssl.h>
50#include <openssl/rand.h>
51#include <openssl/x509v3.h>
52#ifndef OPENSSL_NO_DSA
53#include <openssl/dsa.h>
54#endif
55#include <openssl/dh.h>
56#include <openssl/err.h>
57#include <openssl/md5.h>
58#include <openssl/conf.h>
59#include <openssl/bn.h>
60#include <openssl/rsa.h>
61#include <openssl/bio.h>
62#include <openssl/buffer.h>
63#include <openssl/pkcs12.h>
64
65#ifdef USE_AMISSL
66#include "amigaos.h"
67#endif
68
69#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
70#include <openssl/ocsp.h>
71#endif
72
73#if (OPENSSL_VERSION_NUMBER >= 0x0090700fL) && /* 0.9.7 or later */ \
74 !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
75#define USE_OPENSSL_ENGINE
76#include <openssl/engine.h>
77#endif
78
79#include "warnless.h"
80#include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
81
82/* The last #include files should be: */
83#include "curl_memory.h"
84#include "memdebug.h"
85
86/* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS
87 renegotiations when built with BoringSSL. Renegotiating is non-compliant
88 with HTTP/2 and "an extremely dangerous protocol feature". Beware.
89
90#define ALLOW_RENEG 1
91 */
92
93#ifndef OPENSSL_VERSION_NUMBER
94#error "OPENSSL_VERSION_NUMBER not defined"
95#endif
96
97#ifdef USE_OPENSSL_ENGINE
98#include <openssl/ui.h>
99#endif
100
101#if OPENSSL_VERSION_NUMBER >= 0x00909000L
102#define SSL_METHOD_QUAL const
103#else
104#define SSL_METHOD_QUAL
105#endif
106
107#if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
108#define HAVE_ERR_REMOVE_THREAD_STATE 1
109#endif
110
111#if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
112 OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
113#undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
114#define OPENSSL_NO_SSL2
115#endif
116
117#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
118 !(defined(LIBRESSL_VERSION_NUMBER) && \
119 LIBRESSL_VERSION_NUMBER < 0x20700000L)
120#define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
121#define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
122#define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
123#define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
124#define CONST_EXTS const
125#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
126
127/* funny typecast define due to difference in API */
128#ifdef LIBRESSL_VERSION_NUMBER
129#define ARG2_X509_signature_print (X509_ALGOR *)
130#else
131#define ARG2_X509_signature_print
132#endif
133
134#else
135/* For OpenSSL before 1.1.0 */
136#define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
137#define X509_get0_notBefore(x) X509_get_notBefore(x)
138#define X509_get0_notAfter(x) X509_get_notAfter(x)
139#define CONST_EXTS /* nope */
140#ifndef LIBRESSL_VERSION_NUMBER
141#define OpenSSL_version_num() SSLeay()
142#endif
143#endif
144
145#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
146 !(defined(LIBRESSL_VERSION_NUMBER) && \
147 LIBRESSL_VERSION_NUMBER < 0x20700000L)
148#define HAVE_X509_GET0_SIGNATURE 1
149#endif
150
151#if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) /* 1.0.2 or later */
152#define HAVE_SSL_GET_SHUTDOWN 1
153#endif
154
155#if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
156 OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
157 !defined(OPENSSL_NO_COMP)
158#define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
159#endif
160
161#if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
162/* not present in older OpenSSL */
163#define OPENSSL_load_builtin_modules(x)
164#endif
165
166/*
167 * Whether SSL_CTX_set_keylog_callback is available.
168 * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
169 * BoringSSL: supported since d28f59c27bac (committed 2015-11-19)
170 * LibreSSL: unsupported in at least 2.7.2 (explicitly check for it since it
171 * lies and pretends to be OpenSSL 2.0.0).
172 */
173#if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
174 !defined(LIBRESSL_VERSION_NUMBER)) || \
175 defined(OPENSSL_IS_BORINGSSL)
176#define HAVE_KEYLOG_CALLBACK
177#endif
178
179/* Whether SSL_CTX_set_ciphersuites is available.
180 * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
181 * BoringSSL: no
182 * LibreSSL: no
183 */
184#if ((OPENSSL_VERSION_NUMBER >= 0x10101000L) && \
185 !defined(LIBRESSL_VERSION_NUMBER) && \
186 !defined(OPENSSL_IS_BORINGSSL))
187#define HAVE_SSL_CTX_SET_CIPHERSUITES
188#define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
189#endif
190
191#if defined(LIBRESSL_VERSION_NUMBER)
192#define OSSL_PACKAGE "LibreSSL"
193#elif defined(OPENSSL_IS_BORINGSSL)
194#define OSSL_PACKAGE "BoringSSL"
195#else
196#define OSSL_PACKAGE "OpenSSL"
197#endif
198
199#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
200/* up2date versions of OpenSSL maintain the default reasonably secure without
201 * breaking compatibility, so it is better not to override the default by curl
202 */
203#define DEFAULT_CIPHER_SELECTION NULL
204#else
205/* ... but it is not the case with old versions of OpenSSL */
206#define DEFAULT_CIPHER_SELECTION \
207 "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
208#endif
209
210#define ENABLE_SSLKEYLOGFILE
211
212#ifdef ENABLE_SSLKEYLOGFILE
213typedef struct ssl_tap_state {
214 int master_key_length;
215 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
216 unsigned char client_random[SSL3_RANDOM_SIZE];
217} ssl_tap_state_t;
218#endif /* ENABLE_SSLKEYLOGFILE */
219
220struct ssl_backend_data {
221 /* these ones requires specific SSL-types */
222 SSL_CTX* ctx;
223 SSL* handle;
224 X509* server_cert;
225#ifdef ENABLE_SSLKEYLOGFILE
226 /* tap_state holds the last seen master key if we're logging them */
227 ssl_tap_state_t tap_state;
228#endif
229};
230
231#define BACKEND connssl->backend
232
233/*
234 * Number of bytes to read from the random number seed file. This must be
235 * a finite value (because some entropy "files" like /dev/urandom have
236 * an infinite length), but must be large enough to provide enough
237 * entropy to properly seed OpenSSL's PRNG.
238 */
239#define RAND_LOAD_LENGTH 1024
240
241#ifdef ENABLE_SSLKEYLOGFILE
242/* The fp for the open SSLKEYLOGFILE, or NULL if not open */
243static FILE *keylog_file_fp;
244
245#ifdef HAVE_KEYLOG_CALLBACK
246static void ossl_keylog_callback(const SSL *ssl, const char *line)
247{
248 (void)ssl;
249
250 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
251 may not be thread-safe. */
252 if(keylog_file_fp && line && *line) {
253 char stackbuf[256];
254 char *buf;
255 size_t linelen = strlen(line);
256
257 if(linelen <= sizeof(stackbuf) - 2)
258 buf = stackbuf;
259 else {
260 buf = malloc(linelen + 2);
261 if(!buf)
262 return;
263 }
264 memcpy(buf, line, linelen);
265 buf[linelen] = '\n';
266 buf[linelen + 1] = '\0';
267
268 fputs(buf, keylog_file_fp);
269 if(buf != stackbuf)
270 free(buf);
271 }
272}
273#else
274#define KEYLOG_PREFIX "CLIENT_RANDOM "
275#define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1)
276/*
277 * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL
278 * being used doesn't have native support for doing that.
279 */
280static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state)
281{
282 const char *hex = "0123456789ABCDEF";
283 int pos, i;
284 char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 +
285 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1];
286 const SSL_SESSION *session = SSL_get_session(ssl);
287 unsigned char client_random[SSL3_RANDOM_SIZE];
288 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
289 int master_key_length = 0;
290
291 if(!session || !keylog_file_fp)
292 return;
293
294#if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
295 !(defined(LIBRESSL_VERSION_NUMBER) && \
296 LIBRESSL_VERSION_NUMBER < 0x20700000L)
297 /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
298 * we have a valid SSL context if we have a non-NULL session. */
299 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
300 master_key_length = (int)
301 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
302#else
303 if(ssl->s3 && session->master_key_length > 0) {
304 master_key_length = session->master_key_length;
305 memcpy(master_key, session->master_key, session->master_key_length);
306 memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
307 }
308#endif
309
310 if(master_key_length <= 0)
311 return;
312
313 /* Skip writing keys if there is no key or it did not change. */
314 if(state->master_key_length == master_key_length &&
315 !memcmp(state->master_key, master_key, master_key_length) &&
316 !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) {
317 return;
318 }
319
320 state->master_key_length = master_key_length;
321 memcpy(state->master_key, master_key, master_key_length);
322 memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE);
323
324 memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN);
325 pos = KEYLOG_PREFIX_LEN;
326
327 /* Client Random for SSLv3/TLS */
328 for(i = 0; i < SSL3_RANDOM_SIZE; i++) {
329 line[pos++] = hex[client_random[i] >> 4];
330 line[pos++] = hex[client_random[i] & 0xF];
331 }
332 line[pos++] = ' ';
333
334 /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */
335 for(i = 0; i < master_key_length; i++) {
336 line[pos++] = hex[master_key[i] >> 4];
337 line[pos++] = hex[master_key[i] & 0xF];
338 }
339 line[pos++] = '\n';
340 line[pos] = '\0';
341
342 /* Using fputs here instead of fprintf since libcurl's fprintf replacement
343 may not be thread-safe. */
344 fputs(line, keylog_file_fp);
345}
346#endif /* !HAVE_KEYLOG_CALLBACK */
347#endif /* ENABLE_SSLKEYLOGFILE */
348
349static const char *SSL_ERROR_to_str(int err)
350{
351 switch(err) {
352 case SSL_ERROR_NONE:
353 return "SSL_ERROR_NONE";
354 case SSL_ERROR_SSL:
355 return "SSL_ERROR_SSL";
356 case SSL_ERROR_WANT_READ:
357 return "SSL_ERROR_WANT_READ";
358 case SSL_ERROR_WANT_WRITE:
359 return "SSL_ERROR_WANT_WRITE";
360 case SSL_ERROR_WANT_X509_LOOKUP:
361 return "SSL_ERROR_WANT_X509_LOOKUP";
362 case SSL_ERROR_SYSCALL:
363 return "SSL_ERROR_SYSCALL";
364 case SSL_ERROR_ZERO_RETURN:
365 return "SSL_ERROR_ZERO_RETURN";
366 case SSL_ERROR_WANT_CONNECT:
367 return "SSL_ERROR_WANT_CONNECT";
368 case SSL_ERROR_WANT_ACCEPT:
369 return "SSL_ERROR_WANT_ACCEPT";
370#if defined(SSL_ERROR_WANT_ASYNC)
371 case SSL_ERROR_WANT_ASYNC:
372 return "SSL_ERROR_WANT_ASYNC";
373#endif
374#if defined(SSL_ERROR_WANT_ASYNC_JOB)
375 case SSL_ERROR_WANT_ASYNC_JOB:
376 return "SSL_ERROR_WANT_ASYNC_JOB";
377#endif
378#if defined(SSL_ERROR_WANT_EARLY)
379 case SSL_ERROR_WANT_EARLY:
380 return "SSL_ERROR_WANT_EARLY";
381#endif
382 default:
383 return "SSL_ERROR unknown";
384 }
385}
386
387/* Return error string for last OpenSSL error
388 */
389static char *ossl_strerror(unsigned long error, char *buf, size_t size)
390{
391 if(size)
392 *buf = '\0';
393
394#ifdef OPENSSL_IS_BORINGSSL
395 ERR_error_string_n((uint32_t)error, buf, size);
396#else
397 ERR_error_string_n(error, buf, size);
398#endif
399
400 if(size > 1 && !*buf) {
401 strncpy(buf, (error ? "Unknown error" : "No error"), size);
402 buf[size - 1] = '\0';
403 }
404
405 return buf;
406}
407
408/* Return an extra data index for the connection data.
409 * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
410 */
411static int ossl_get_ssl_conn_index(void)
412{
413 static int ssl_ex_data_conn_index = -1;
414 if(ssl_ex_data_conn_index < 0) {
415 ssl_ex_data_conn_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
416 }
417 return ssl_ex_data_conn_index;
418}
419
420/* Return an extra data index for the sockindex.
421 * This index can be used with SSL_get_ex_data() and SSL_set_ex_data().
422 */
423static int ossl_get_ssl_sockindex_index(void)
424{
425 static int ssl_ex_data_sockindex_index = -1;
426 if(ssl_ex_data_sockindex_index < 0) {
427 ssl_ex_data_sockindex_index = SSL_get_ex_new_index(0, NULL, NULL, NULL,
428 NULL);
429 }
430 return ssl_ex_data_sockindex_index;
431}
432
433static int passwd_callback(char *buf, int num, int encrypting,
434 void *global_passwd)
435{
436 DEBUGASSERT(0 == encrypting);
437
438 if(!encrypting) {
439 int klen = curlx_uztosi(strlen((char *)global_passwd));
440 if(num > klen) {
441 memcpy(buf, global_passwd, klen + 1);
442 return klen;
443 }
444 }
445 return 0;
446}
447
448/*
449 * rand_enough() returns TRUE if we have seeded the random engine properly.
450 */
451static bool rand_enough(void)
452{
453 return (0 != RAND_status()) ? TRUE : FALSE;
454}
455
456static CURLcode Curl_ossl_seed(struct Curl_easy *data)
457{
458 /* we have the "SSL is seeded" boolean static to prevent multiple
459 time-consuming seedings in vain */
460 static bool ssl_seeded = FALSE;
461 char fname[256];
462
463 if(ssl_seeded)
464 return CURLE_OK;
465
466 if(rand_enough()) {
467 /* OpenSSL 1.1.0+ will return here */
468 ssl_seeded = TRUE;
469 return CURLE_OK;
470 }
471
472#ifndef RANDOM_FILE
473 /* if RANDOM_FILE isn't defined, we only perform this if an option tells
474 us to! */
475 if(data->set.str[STRING_SSL_RANDOM_FILE])
476#define RANDOM_FILE "" /* doesn't matter won't be used */
477#endif
478 {
479 /* let the option override the define */
480 RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
481 data->set.str[STRING_SSL_RANDOM_FILE]:
482 RANDOM_FILE),
483 RAND_LOAD_LENGTH);
484 if(rand_enough())
485 return CURLE_OK;
486 }
487
488#if defined(HAVE_RAND_EGD)
489 /* only available in OpenSSL 0.9.5 and later */
490 /* EGD_SOCKET is set at configure time or not at all */
491#ifndef EGD_SOCKET
492 /* If we don't have the define set, we only do this if the egd-option
493 is set */
494 if(data->set.str[STRING_SSL_EGDSOCKET])
495#define EGD_SOCKET "" /* doesn't matter won't be used */
496#endif
497 {
498 /* If there's an option and a define, the option overrides the
499 define */
500 int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
501 data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
502 if(-1 != ret) {
503 if(rand_enough())
504 return CURLE_OK;
505 }
506 }
507#endif
508
509 /* fallback to a custom seeding of the PRNG using a hash based on a current
510 time */
511 do {
512 unsigned char randb[64];
513 size_t len = sizeof(randb);
514 size_t i, i_max;
515 for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
516 struct curltime tv = Curl_now();
517 Curl_wait_ms(1);
518 tv.tv_sec *= i + 1;
519 tv.tv_usec *= (unsigned int)i + 2;
520 tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) *
521 (i + 3)) << 8;
522 tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec +
523 Curl_now().tv_usec) *
524 (i + 4)) << 16;
525 memcpy(&randb[i * sizeof(struct curltime)], &tv,
526 sizeof(struct curltime));
527 }
528 RAND_add(randb, (int)len, (double)len/2);
529 } while(!rand_enough());
530
531 /* generates a default path for the random seed file */
532 fname[0] = 0; /* blank it first */
533 RAND_file_name(fname, sizeof(fname));
534 if(fname[0]) {
535 /* we got a file name to try */
536 RAND_load_file(fname, RAND_LOAD_LENGTH);
537 if(rand_enough())
538 return CURLE_OK;
539 }
540
541 infof(data, "libcurl is now using a weak random seed!\n");
542 return (rand_enough() ? CURLE_OK :
543 CURLE_SSL_CONNECT_ERROR /* confusing error code */);
544}
545
546#ifndef SSL_FILETYPE_ENGINE
547#define SSL_FILETYPE_ENGINE 42
548#endif
549#ifndef SSL_FILETYPE_PKCS12
550#define SSL_FILETYPE_PKCS12 43
551#endif
552static int do_file_type(const char *type)
553{
554 if(!type || !type[0])
555 return SSL_FILETYPE_PEM;
556 if(strcasecompare(type, "PEM"))
557 return SSL_FILETYPE_PEM;
558 if(strcasecompare(type, "DER"))
559 return SSL_FILETYPE_ASN1;
560 if(strcasecompare(type, "ENG"))
561 return SSL_FILETYPE_ENGINE;
562 if(strcasecompare(type, "P12"))
563 return SSL_FILETYPE_PKCS12;
564 return -1;
565}
566
567#ifdef USE_OPENSSL_ENGINE
568/*
569 * Supply default password to the engine user interface conversation.
570 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
571 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
572 */
573static int ssl_ui_reader(UI *ui, UI_STRING *uis)
574{
575 const char *password;
576 switch(UI_get_string_type(uis)) {
577 case UIT_PROMPT:
578 case UIT_VERIFY:
579 password = (const char *)UI_get0_user_data(ui);
580 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
581 UI_set_result(ui, uis, password);
582 return 1;
583 }
584 default:
585 break;
586 }
587 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
588}
589
590/*
591 * Suppress interactive request for a default password if available.
592 */
593static int ssl_ui_writer(UI *ui, UI_STRING *uis)
594{
595 switch(UI_get_string_type(uis)) {
596 case UIT_PROMPT:
597 case UIT_VERIFY:
598 if(UI_get0_user_data(ui) &&
599 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
600 return 1;
601 }
602 default:
603 break;
604 }
605 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
606}
607
608/*
609 * Check if a given string is a PKCS#11 URI
610 */
611static bool is_pkcs11_uri(const char *string)
612{
613 return (string && strncasecompare(string, "pkcs11:", 7));
614}
615
616#endif
617
618static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
619 const char *engine);
620
621static
622int cert_stuff(struct connectdata *conn,
623 SSL_CTX* ctx,
624 char *cert_file,
625 const char *cert_type,
626 char *key_file,
627 const char *key_type,
628 char *key_passwd)
629{
630 struct Curl_easy *data = conn->data;
631 char error_buffer[256];
632 bool check_privkey = TRUE;
633
634 int file_type = do_file_type(cert_type);
635
636 if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
637 SSL *ssl;
638 X509 *x509;
639 int cert_done = 0;
640
641 if(key_passwd) {
642 /* set the password in the callback userdata */
643 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
644 /* Set passwd callback: */
645 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
646 }
647
648
649 switch(file_type) {
650 case SSL_FILETYPE_PEM:
651 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
652 if(SSL_CTX_use_certificate_chain_file(ctx,
653 cert_file) != 1) {
654 failf(data,
655 "could not load PEM client certificate, " OSSL_PACKAGE
656 " error %s, "
657 "(no key found, wrong pass phrase, or wrong file format?)",
658 ossl_strerror(ERR_get_error(), error_buffer,
659 sizeof(error_buffer)) );
660 return 0;
661 }
662 break;
663
664 case SSL_FILETYPE_ASN1:
665 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
666 we use the case above for PEM so this can only be performed with
667 ASN1 files. */
668 if(SSL_CTX_use_certificate_file(ctx,
669 cert_file,
670 file_type) != 1) {
671 failf(data,
672 "could not load ASN1 client certificate, " OSSL_PACKAGE
673 " error %s, "
674 "(no key found, wrong pass phrase, or wrong file format?)",
675 ossl_strerror(ERR_get_error(), error_buffer,
676 sizeof(error_buffer)) );
677 return 0;
678 }
679 break;
680 case SSL_FILETYPE_ENGINE:
681#if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
682 {
683 /* Implicitly use pkcs11 engine if none was provided and the
684 * cert_file is a PKCS#11 URI */
685 if(!data->state.engine) {
686 if(is_pkcs11_uri(cert_file)) {
687 if(Curl_ossl_set_engine(data, "pkcs11") != CURLE_OK) {
688 return 0;
689 }
690 }
691 }
692
693 if(data->state.engine) {
694 const char *cmd_name = "LOAD_CERT_CTRL";
695 struct {
696 const char *cert_id;
697 X509 *cert;
698 } params;
699
700 params.cert_id = cert_file;
701 params.cert = NULL;
702
703 /* Does the engine supports LOAD_CERT_CTRL ? */
704 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
705 0, (void *)cmd_name, NULL)) {
706 failf(data, "ssl engine does not support loading certificates");
707 return 0;
708 }
709
710 /* Load the certificate from the engine */
711 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
712 0, &params, NULL, 1)) {
713 failf(data, "ssl engine cannot load client cert with id"
714 " '%s' [%s]", cert_file,
715 ossl_strerror(ERR_get_error(), error_buffer,
716 sizeof(error_buffer)));
717 return 0;
718 }
719
720 if(!params.cert) {
721 failf(data, "ssl engine didn't initialized the certificate "
722 "properly.");
723 return 0;
724 }
725
726 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
727 failf(data, "unable to set client certificate");
728 X509_free(params.cert);
729 return 0;
730 }
731 X509_free(params.cert); /* we don't need the handle any more... */
732 }
733 else {
734 failf(data, "crypto engine not set, can't load certificate");
735 return 0;
736 }
737 }
738 break;
739#else
740 failf(data, "file type ENG for certificate not implemented");
741 return 0;
742#endif
743
744 case SSL_FILETYPE_PKCS12:
745 {
746 BIO *fp = NULL;
747 PKCS12 *p12 = NULL;
748 EVP_PKEY *pri;
749 STACK_OF(X509) *ca = NULL;
750
751 fp = BIO_new(BIO_s_file());
752 if(fp == NULL) {
753 failf(data,
754 "BIO_new return NULL, " OSSL_PACKAGE
755 " error %s",
756 ossl_strerror(ERR_get_error(), error_buffer,
757 sizeof(error_buffer)) );
758 return 0;
759 }
760
761 if(BIO_read_filename(fp, cert_file) <= 0) {
762 failf(data, "could not open PKCS12 file '%s'", cert_file);
763 BIO_free(fp);
764 return 0;
765 }
766 p12 = d2i_PKCS12_bio(fp, NULL);
767 BIO_free(fp);
768
769 if(!p12) {
770 failf(data, "error reading PKCS12 file '%s'", cert_file);
771 return 0;
772 }
773
774 PKCS12_PBE_add();
775
776 if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
777 &ca)) {
778 failf(data,
779 "could not parse PKCS12 file, check password, " OSSL_PACKAGE
780 " error %s",
781 ossl_strerror(ERR_get_error(), error_buffer,
782 sizeof(error_buffer)) );
783 PKCS12_free(p12);
784 return 0;
785 }
786
787 PKCS12_free(p12);
788
789 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
790 failf(data,
791 "could not load PKCS12 client certificate, " OSSL_PACKAGE
792 " error %s",
793 ossl_strerror(ERR_get_error(), error_buffer,
794 sizeof(error_buffer)) );
795 goto fail;
796 }
797
798 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
799 failf(data, "unable to use private key from PKCS12 file '%s'",
800 cert_file);
801 goto fail;
802 }
803
804 if(!SSL_CTX_check_private_key (ctx)) {
805 failf(data, "private key from PKCS12 file '%s' "
806 "does not match certificate in same file", cert_file);
807 goto fail;
808 }
809 /* Set Certificate Verification chain */
810 if(ca) {
811 while(sk_X509_num(ca)) {
812 /*
813 * Note that sk_X509_pop() is used below to make sure the cert is
814 * removed from the stack properly before getting passed to
815 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
816 * we used sk_X509_value() instead, but then we'd clean it in the
817 * subsequent sk_X509_pop_free() call.
818 */
819 X509 *x = sk_X509_pop(ca);
820 if(!SSL_CTX_add_client_CA(ctx, x)) {
821 X509_free(x);
822 failf(data, "cannot add certificate to client CA list");
823 goto fail;
824 }
825 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
826 X509_free(x);
827 failf(data, "cannot add certificate to certificate chain");
828 goto fail;
829 }
830 }
831 }
832
833 cert_done = 1;
834 fail:
835 EVP_PKEY_free(pri);
836 X509_free(x509);
837#ifdef USE_AMISSL
838 sk_X509_pop_free(ca, Curl_amiga_X509_free);
839#else
840 sk_X509_pop_free(ca, X509_free);
841#endif
842 if(!cert_done)
843 return 0; /* failure! */
844 break;
845 }
846 default:
847 failf(data, "not supported file type '%s' for certificate", cert_type);
848 return 0;
849 }
850
851 if(!key_file)
852 key_file = cert_file;
853 else
854 file_type = do_file_type(key_type);
855
856 switch(file_type) {
857 case SSL_FILETYPE_PEM:
858 if(cert_done)
859 break;
860 /* FALLTHROUGH */
861 case SSL_FILETYPE_ASN1:
862 if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
863 failf(data, "unable to set private key file: '%s' type %s",
864 key_file, key_type?key_type:"PEM");
865 return 0;
866 }
867 break;
868 case SSL_FILETYPE_ENGINE:
869#ifdef USE_OPENSSL_ENGINE
870 { /* XXXX still needs some work */
871 EVP_PKEY *priv_key = NULL;
872
873 /* Implicitly use pkcs11 engine if none was provided and the
874 * key_file is a PKCS#11 URI */
875 if(!data->state.engine) {
876 if(is_pkcs11_uri(key_file)) {
877 if(Curl_ossl_set_engine(data, "pkcs11") != CURLE_OK) {
878 return 0;
879 }
880 }
881 }
882
883 if(data->state.engine) {
884 UI_METHOD *ui_method =
885 UI_create_method((char *)"curl user interface");
886 if(!ui_method) {
887 failf(data, "unable do create " OSSL_PACKAGE
888 " user-interface method");
889 return 0;
890 }
891 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
892 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
893 UI_method_set_reader(ui_method, ssl_ui_reader);
894 UI_method_set_writer(ui_method, ssl_ui_writer);
895 /* the typecast below was added to please mingw32 */
896 priv_key = (EVP_PKEY *)
897 ENGINE_load_private_key(data->state.engine, key_file,
898 ui_method,
899 key_passwd);
900 UI_destroy_method(ui_method);
901 if(!priv_key) {
902 failf(data, "failed to load private key from crypto engine");
903 return 0;
904 }
905 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
906 failf(data, "unable to set private key");
907 EVP_PKEY_free(priv_key);
908 return 0;
909 }
910 EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
911 }
912 else {
913 failf(data, "crypto engine not set, can't load private key");
914 return 0;
915 }
916 }
917 break;
918#else
919 failf(data, "file type ENG for private key not supported");
920 return 0;
921#endif
922 case SSL_FILETYPE_PKCS12:
923 if(!cert_done) {
924 failf(data, "file type P12 for private key not supported");
925 return 0;
926 }
927 break;
928 default:
929 failf(data, "not supported file type for private key");
930 return 0;
931 }
932
933 ssl = SSL_new(ctx);
934 if(!ssl) {
935 failf(data, "unable to create an SSL structure");
936 return 0;
937 }
938
939 x509 = SSL_get_certificate(ssl);
940
941 /* This version was provided by Evan Jordan and is supposed to not
942 leak memory as the previous version: */
943 if(x509) {
944 EVP_PKEY *pktmp = X509_get_pubkey(x509);
945 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
946 EVP_PKEY_free(pktmp);
947 }
948
949#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL)
950 {
951 /* If RSA is used, don't check the private key if its flags indicate
952 * it doesn't support it. */
953 EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
954 int pktype;
955#ifdef HAVE_OPAQUE_EVP_PKEY
956 pktype = EVP_PKEY_id(priv_key);
957#else
958 pktype = priv_key->type;
959#endif
960 if(pktype == EVP_PKEY_RSA) {
961 RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
962 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
963 check_privkey = FALSE;
964 RSA_free(rsa); /* Decrement reference count */
965 }
966 }
967#endif
968
969 SSL_free(ssl);
970
971 /* If we are using DSA, we can copy the parameters from
972 * the private key */
973
974 if(check_privkey == TRUE) {
975 /* Now we know that a key and cert have been set against
976 * the SSL context */
977 if(!SSL_CTX_check_private_key(ctx)) {
978 failf(data, "Private key does not match the certificate public key");
979 return 0;
980 }
981 }
982 }
983 return 1;
984}
985
986/* returns non-zero on failure */
987static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
988{
989#if 0
990 return X509_NAME_oneline(a, buf, size);
991#else
992 BIO *bio_out = BIO_new(BIO_s_mem());
993 BUF_MEM *biomem;
994 int rc;
995
996 if(!bio_out)
997 return 1; /* alloc failed! */
998
999 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
1000 BIO_get_mem_ptr(bio_out, &biomem);
1001
1002 if((size_t)biomem->length < size)
1003 size = biomem->length;
1004 else
1005 size--; /* don't overwrite the buffer end */
1006
1007 memcpy(buf, biomem->data, size);
1008 buf[size] = 0;
1009
1010 BIO_free(bio_out);
1011
1012 return !rc;
1013#endif
1014}
1015
1016/**
1017 * Global SSL init
1018 *
1019 * @retval 0 error initializing SSL
1020 * @retval 1 SSL initialized successfully
1021 */
1022static int Curl_ossl_init(void)
1023{
1024#ifdef ENABLE_SSLKEYLOGFILE
1025 char *keylog_file_name;
1026#endif
1027
1028 OPENSSL_load_builtin_modules();
1029
1030#ifdef USE_OPENSSL_ENGINE
1031 ENGINE_load_builtin_engines();
1032#endif
1033
1034/* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and
1035 0.9.8e */
1036#ifndef CONF_MFLAGS_DEFAULT_SECTION
1037#define CONF_MFLAGS_DEFAULT_SECTION 0x0
1038#endif
1039
1040#ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
1041 CONF_modules_load_file(NULL, NULL,
1042 CONF_MFLAGS_DEFAULT_SECTION|
1043 CONF_MFLAGS_IGNORE_MISSING_FILE);
1044#endif
1045
1046#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
1047 !defined(LIBRESSL_VERSION_NUMBER)
1048 /* OpenSSL 1.1.0+ takes care of initialization itself */
1049#else
1050 /* Lets get nice error messages */
1051 SSL_load_error_strings();
1052
1053 /* Init the global ciphers and digests */
1054 if(!SSLeay_add_ssl_algorithms())
1055 return 0;
1056
1057 OpenSSL_add_all_algorithms();
1058#endif
1059
1060#ifdef ENABLE_SSLKEYLOGFILE
1061 if(!keylog_file_fp) {
1062 keylog_file_name = curl_getenv("SSLKEYLOGFILE");
1063 if(keylog_file_name) {
1064 keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT);
1065 if(keylog_file_fp) {
1066#ifdef WIN32
1067 if(setvbuf(keylog_file_fp, NULL, _IONBF, 0))
1068#else
1069 if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096))
1070#endif
1071 {
1072 fclose(keylog_file_fp);
1073 keylog_file_fp = NULL;
1074 }
1075 }
1076 Curl_safefree(keylog_file_name);
1077 }
1078 }
1079#endif
1080
1081 /* Initialize the extra data indexes */
1082 if(ossl_get_ssl_conn_index() < 0 || ossl_get_ssl_sockindex_index() < 0)
1083 return 0;
1084
1085 return 1;
1086}
1087
1088/* Global cleanup */
1089static void Curl_ossl_cleanup(void)
1090{
1091#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
1092 !defined(LIBRESSL_VERSION_NUMBER)
1093 /* OpenSSL 1.1 deprecates all these cleanup functions and
1094 turns them into no-ops in OpenSSL 1.0 compatibility mode */
1095#else
1096 /* Free ciphers and digests lists */
1097 EVP_cleanup();
1098
1099#ifdef USE_OPENSSL_ENGINE
1100 /* Free engine list */
1101 ENGINE_cleanup();
1102#endif
1103
1104 /* Free OpenSSL error strings */
1105 ERR_free_strings();
1106
1107 /* Free thread local error state, destroying hash upon zero refcount */
1108#ifdef HAVE_ERR_REMOVE_THREAD_STATE
1109 ERR_remove_thread_state(NULL);
1110#else
1111 ERR_remove_state(0);
1112#endif
1113
1114 /* Free all memory allocated by all configuration modules */
1115 CONF_modules_free();
1116
1117#ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
1118 SSL_COMP_free_compression_methods();
1119#endif
1120#endif
1121
1122#ifdef ENABLE_SSLKEYLOGFILE
1123 if(keylog_file_fp) {
1124 fclose(keylog_file_fp);
1125 keylog_file_fp = NULL;
1126 }
1127#endif
1128}
1129
1130/*
1131 * This function is used to determine connection status.
1132 *
1133 * Return codes:
1134 * 1 means the connection is still in place
1135 * 0 means the connection has been closed
1136 * -1 means the connection status is unknown
1137 */
1138static int Curl_ossl_check_cxn(struct connectdata *conn)
1139{
1140 /* SSL_peek takes data out of the raw recv buffer without peeking so we use
1141 recv MSG_PEEK instead. Bug #795 */
1142#ifdef MSG_PEEK
1143 char buf;
1144 ssize_t nread;
1145 nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
1146 (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
1147 if(nread == 0)
1148 return 0; /* connection has been closed */
1149 if(nread == 1)
1150 return 1; /* connection still in place */
1151 else if(nread == -1) {
1152 int err = SOCKERRNO;
1153 if(err == EINPROGRESS ||
1154#if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
1155 err == EAGAIN ||
1156#endif
1157 err == EWOULDBLOCK)
1158 return 1; /* connection still in place */
1159 if(err == ECONNRESET ||
1160#ifdef ECONNABORTED
1161 err == ECONNABORTED ||
1162#endif
1163#ifdef ENETDOWN
1164 err == ENETDOWN ||
1165#endif
1166#ifdef ENETRESET
1167 err == ENETRESET ||
1168#endif
1169#ifdef ESHUTDOWN
1170 err == ESHUTDOWN ||
1171#endif
1172#ifdef ETIMEDOUT
1173 err == ETIMEDOUT ||
1174#endif
1175 err == ENOTCONN)
1176 return 0; /* connection has been closed */
1177 }
1178#endif
1179 return -1; /* connection status unknown */
1180}
1181
1182/* Selects an OpenSSL crypto engine
1183 */
1184static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
1185 const char *engine)
1186{
1187#ifdef USE_OPENSSL_ENGINE
1188 ENGINE *e;
1189
1190#if OPENSSL_VERSION_NUMBER >= 0x00909000L
1191 e = ENGINE_by_id(engine);
1192#else
1193 /* avoid memory leak */
1194 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1195 const char *e_id = ENGINE_get_id(e);
1196 if(!strcmp(engine, e_id))
1197 break;
1198 }
1199#endif
1200
1201 if(!e) {
1202 failf(data, "SSL Engine '%s' not found", engine);
1203 return CURLE_SSL_ENGINE_NOTFOUND;
1204 }
1205
1206 if(data->state.engine) {
1207 ENGINE_finish(data->state.engine);
1208 ENGINE_free(data->state.engine);
1209 data->state.engine = NULL;
1210 }
1211 if(!ENGINE_init(e)) {
1212 char buf[256];
1213
1214 ENGINE_free(e);
1215 failf(data, "Failed to initialise SSL Engine '%s':\n%s",
1216 engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
1217 return CURLE_SSL_ENGINE_INITFAILED;
1218 }
1219 data->state.engine = e;
1220 return CURLE_OK;
1221#else
1222 (void)engine;
1223 failf(data, "SSL Engine not supported");
1224 return CURLE_SSL_ENGINE_NOTFOUND;
1225#endif
1226}
1227
1228/* Sets engine as default for all SSL operations
1229 */
1230static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
1231{
1232#ifdef USE_OPENSSL_ENGINE
1233 if(data->state.engine) {
1234 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
1235 infof(data, "set default crypto engine '%s'\n",
1236 ENGINE_get_id(data->state.engine));
1237 }
1238 else {
1239 failf(data, "set default crypto engine '%s' failed",
1240 ENGINE_get_id(data->state.engine));
1241 return CURLE_SSL_ENGINE_SETFAILED;
1242 }
1243 }
1244#else
1245 (void) data;
1246#endif
1247 return CURLE_OK;
1248}
1249
1250/* Return list of OpenSSL crypto engine names.
1251 */
1252static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
1253{
1254 struct curl_slist *list = NULL;
1255#ifdef USE_OPENSSL_ENGINE
1256 struct curl_slist *beg;
1257 ENGINE *e;
1258
1259 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1260 beg = curl_slist_append(list, ENGINE_get_id(e));
1261 if(!beg) {
1262 curl_slist_free_all(list);
1263 return NULL;
1264 }
1265 list = beg;
1266 }
1267#endif
1268 (void) data;
1269 return list;
1270}
1271
1272
1273static void ossl_close(struct ssl_connect_data *connssl)
1274{
1275 if(BACKEND->handle) {
1276 (void)SSL_shutdown(BACKEND->handle);
1277 SSL_set_connect_state(BACKEND->handle);
1278
1279 SSL_free(BACKEND->handle);
1280 BACKEND->handle = NULL;
1281 }
1282 if(BACKEND->ctx) {
1283 SSL_CTX_free(BACKEND->ctx);
1284 BACKEND->ctx = NULL;
1285 }
1286}
1287
1288/*
1289 * This function is called when an SSL connection is closed.
1290 */
1291static void Curl_ossl_close(struct connectdata *conn, int sockindex)
1292{
1293 ossl_close(&conn->ssl[sockindex]);
1294 ossl_close(&conn->proxy_ssl[sockindex]);
1295}
1296
1297/*
1298 * This function is called to shut down the SSL layer but keep the
1299 * socket open (CCC - Clear Command Channel)
1300 */
1301static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
1302{
1303 int retval = 0;
1304 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1305 struct Curl_easy *data = conn->data;
1306 char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
1307 to be at least 256 bytes long. */
1308 unsigned long sslerror;
1309 ssize_t nread;
1310 int buffsize;
1311 int err;
1312 bool done = FALSE;
1313
1314#ifndef CURL_DISABLE_FTP
1315 /* This has only been tested on the proftpd server, and the mod_tls code
1316 sends a close notify alert without waiting for a close notify alert in
1317 response. Thus we wait for a close notify alert from the server, but
1318 we do not send one. Let's hope other servers do the same... */
1319
1320 if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
1321 (void)SSL_shutdown(BACKEND->handle);
1322#endif
1323
1324 if(BACKEND->handle) {
1325 buffsize = (int)sizeof(buf);
1326 while(!done) {
1327 int what = SOCKET_READABLE(conn->sock[sockindex],
1328 SSL_SHUTDOWN_TIMEOUT);
1329 if(what > 0) {
1330 ERR_clear_error();
1331
1332 /* Something to read, let's do it and hope that it is the close
1333 notify alert from the server */
1334 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
1335 err = SSL_get_error(BACKEND->handle, (int)nread);
1336
1337 switch(err) {
1338 case SSL_ERROR_NONE: /* this is not an error */
1339 case SSL_ERROR_ZERO_RETURN: /* no more data */
1340 /* This is the expected response. There was no data but only
1341 the close notify alert */
1342 done = TRUE;
1343 break;
1344 case SSL_ERROR_WANT_READ:
1345 /* there's data pending, re-invoke SSL_read() */
1346 infof(data, "SSL_ERROR_WANT_READ\n");
1347 break;
1348 case SSL_ERROR_WANT_WRITE:
1349 /* SSL wants a write. Really odd. Let's bail out. */
1350 infof(data, "SSL_ERROR_WANT_WRITE\n");
1351 done = TRUE;
1352 break;
1353 default:
1354 /* openssl/ssl.h says "look at error stack/return value/errno" */
1355 sslerror = ERR_get_error();
1356 failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
1357 (sslerror ?
1358 ossl_strerror(sslerror, buf, sizeof(buf)) :
1359 SSL_ERROR_to_str(err)),
1360 SOCKERRNO);
1361 done = TRUE;
1362 break;
1363 }
1364 }
1365 else if(0 == what) {
1366 /* timeout */
1367 failf(data, "SSL shutdown timeout");
1368 done = TRUE;
1369 }
1370 else {
1371 /* anything that gets here is fatally bad */
1372 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1373 retval = -1;
1374 done = TRUE;
1375 }
1376 } /* while()-loop for the select() */
1377
1378 if(data->set.verbose) {
1379#ifdef HAVE_SSL_GET_SHUTDOWN
1380 switch(SSL_get_shutdown(BACKEND->handle)) {
1381 case SSL_SENT_SHUTDOWN:
1382 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
1383 break;
1384 case SSL_RECEIVED_SHUTDOWN:
1385 infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
1386 break;
1387 case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
1388 infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
1389 "SSL_RECEIVED__SHUTDOWN\n");
1390 break;
1391 }
1392#endif
1393 }
1394
1395 SSL_free(BACKEND->handle);
1396 BACKEND->handle = NULL;
1397 }
1398 return retval;
1399}
1400
1401static void Curl_ossl_session_free(void *ptr)
1402{
1403 /* free the ID */
1404 SSL_SESSION_free(ptr);
1405}
1406
1407/*
1408 * This function is called when the 'data' struct is going away. Close
1409 * down everything and free all resources!
1410 */
1411static void Curl_ossl_close_all(struct Curl_easy *data)
1412{
1413#ifdef USE_OPENSSL_ENGINE
1414 if(data->state.engine) {
1415 ENGINE_finish(data->state.engine);
1416 ENGINE_free(data->state.engine);
1417 data->state.engine = NULL;
1418 }
1419#else
1420 (void)data;
1421#endif
1422#if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
1423 defined(HAVE_ERR_REMOVE_THREAD_STATE)
1424 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
1425 so we need to clean it here in case the thread will be killed. All OpenSSL
1426 code should extract the error in association with the error so clearing
1427 this queue here should be harmless at worst. */
1428 ERR_remove_thread_state(NULL);
1429#endif
1430}
1431
1432/* ====================================================== */
1433
1434/*
1435 * Match subjectAltName against the host name. This requires a conversion
1436 * in CURL_DOES_CONVERSIONS builds.
1437 */
1438static bool subj_alt_hostcheck(struct Curl_easy *data,
1439 const char *match_pattern, const char *hostname,
1440 const char *dispname)
1441#ifdef CURL_DOES_CONVERSIONS
1442{
1443 bool res = FALSE;
1444
1445 /* Curl_cert_hostcheck uses host encoding, but we get ASCII from
1446 OpenSSl.
1447 */
1448 char *match_pattern2 = strdup(match_pattern);
1449
1450 if(match_pattern2) {
1451 if(Curl_convert_from_network(data, match_pattern2,
1452 strlen(match_pattern2)) == CURLE_OK) {
1453 if(Curl_cert_hostcheck(match_pattern2, hostname)) {
1454 res = TRUE;
1455 infof(data,
1456 " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1457 dispname, match_pattern2);
1458 }
1459 }
1460 free(match_pattern2);
1461 }
1462 else {
1463 failf(data,
1464 "SSL: out of memory when allocating temporary for subjectAltName");
1465 }
1466 return res;
1467}
1468#else
1469{
1470#ifdef CURL_DISABLE_VERBOSE_STRINGS
1471 (void)dispname;
1472 (void)data;
1473#endif
1474 if(Curl_cert_hostcheck(match_pattern, hostname)) {
1475 infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
1476 dispname, match_pattern);
1477 return TRUE;
1478 }
1479 return FALSE;
1480}
1481#endif
1482
1483
1484/* Quote from RFC2818 section 3.1 "Server Identity"
1485
1486 If a subjectAltName extension of type dNSName is present, that MUST
1487 be used as the identity. Otherwise, the (most specific) Common Name
1488 field in the Subject field of the certificate MUST be used. Although
1489 the use of the Common Name is existing practice, it is deprecated and
1490 Certification Authorities are encouraged to use the dNSName instead.
1491
1492 Matching is performed using the matching rules specified by
1493 [RFC2459]. If more than one identity of a given type is present in
1494 the certificate (e.g., more than one dNSName name, a match in any one
1495 of the set is considered acceptable.) Names may contain the wildcard
1496 character * which is considered to match any single domain name
1497 component or component fragment. E.g., *.a.com matches foo.a.com but
1498 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
1499
1500 In some cases, the URI is specified as an IP address rather than a
1501 hostname. In this case, the iPAddress subjectAltName must be present
1502 in the certificate and must exactly match the IP in the URI.
1503
1504*/
1505static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
1506{
1507 bool matched = FALSE;
1508 int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
1509 size_t addrlen = 0;
1510 struct Curl_easy *data = conn->data;
1511 STACK_OF(GENERAL_NAME) *altnames;
1512#ifdef ENABLE_IPV6
1513 struct in6_addr addr;
1514#else
1515 struct in_addr addr;
1516#endif
1517 CURLcode result = CURLE_OK;
1518 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
1519 bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
1520 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
1521 conn->host.name;
1522 const char * const dispname = SSL_IS_PROXY() ?
1523 conn->http_proxy.host.dispname : conn->host.dispname;
1524
1525#ifdef ENABLE_IPV6
1526 if(conn->bits.ipv6_ip &&
1527 Curl_inet_pton(AF_INET6, hostname, &addr)) {
1528 target = GEN_IPADD;
1529 addrlen = sizeof(struct in6_addr);
1530 }
1531 else
1532#endif
1533 if(Curl_inet_pton(AF_INET, hostname, &addr)) {
1534 target = GEN_IPADD;
1535 addrlen = sizeof(struct in_addr);
1536 }
1537
1538 /* get a "list" of alternative names */
1539 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
1540
1541 if(altnames) {
1542#ifdef OPENSSL_IS_BORINGSSL
1543 size_t numalts;
1544 size_t i;
1545#else
1546 int numalts;
1547 int i;
1548#endif
1549 bool dnsmatched = FALSE;
1550 bool ipmatched = FALSE;
1551
1552 /* get amount of alternatives, RFC2459 claims there MUST be at least
1553 one, but we don't depend on it... */
1554 numalts = sk_GENERAL_NAME_num(altnames);
1555
1556 /* loop through all alternatives - until a dnsmatch */
1557 for(i = 0; (i < numalts) && !dnsmatched; i++) {
1558 /* get a handle to alternative name number i */
1559 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
1560
1561 if(check->type == GEN_DNS)
1562 dNSName = TRUE;
1563 else if(check->type == GEN_IPADD)
1564 iPAddress = TRUE;
1565
1566 /* only check alternatives of the same type the target is */
1567 if(check->type == target) {
1568 /* get data and length */
1569 const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
1570 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
1571
1572 switch(target) {
1573 case GEN_DNS: /* name/pattern comparison */
1574 /* The OpenSSL man page explicitly says: "In general it cannot be
1575 assumed that the data returned by ASN1_STRING_data() is null
1576 terminated or does not contain embedded nulls." But also that
1577 "The actual format of the data will depend on the actual string
1578 type itself: for example for an IA5String the data will be ASCII"
1579
1580 It has been however verified that in 0.9.6 and 0.9.7, IA5String
1581 is always zero-terminated.
1582 */
1583 if((altlen == strlen(altptr)) &&
1584 /* if this isn't true, there was an embedded zero in the name
1585 string and we cannot match it. */
1586 subj_alt_hostcheck(data, altptr, hostname, dispname)) {
1587 dnsmatched = TRUE;
1588 }
1589 break;
1590
1591 case GEN_IPADD: /* IP address comparison */
1592 /* compare alternative IP address if the data chunk is the same size
1593 our server IP address is */
1594 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
1595 ipmatched = TRUE;
1596 infof(data,
1597 " subjectAltName: host \"%s\" matched cert's IP address!\n",
1598 dispname);
1599 }
1600 break;
1601 }
1602 }
1603 }
1604 GENERAL_NAMES_free(altnames);
1605
1606 if(dnsmatched || ipmatched)
1607 matched = TRUE;
1608 }
1609
1610 if(matched)
1611 /* an alternative name matched */
1612 ;
1613 else if(dNSName || iPAddress) {
1614 infof(data, " subjectAltName does not match %s\n", dispname);
1615 failf(data, "SSL: no alternative certificate subject name matches "
1616 "target host name '%s'", dispname);
1617 result = CURLE_PEER_FAILED_VERIFICATION;
1618 }
1619 else {
1620 /* we have to look to the last occurrence of a commonName in the
1621 distinguished one to get the most significant one. */
1622 int j, i = -1;
1623
1624 /* The following is done because of a bug in 0.9.6b */
1625
1626 unsigned char *nulstr = (unsigned char *)"";
1627 unsigned char *peer_CN = nulstr;
1628
1629 X509_NAME *name = X509_get_subject_name(server_cert);
1630 if(name)
1631 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
1632 i = j;
1633
1634 /* we have the name entry and we will now convert this to a string
1635 that we can use for comparison. Doing this we support BMPstring,
1636 UTF8 etc. */
1637
1638 if(i >= 0) {
1639 ASN1_STRING *tmp =
1640 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
1641
1642 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
1643 is already UTF-8 encoded. We check for this case and copy the raw
1644 string manually to avoid the problem. This code can be made
1645 conditional in the future when OpenSSL has been fixed. */
1646 if(tmp) {
1647 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
1648 j = ASN1_STRING_length(tmp);
1649 if(j >= 0) {
1650 peer_CN = OPENSSL_malloc(j + 1);
1651 if(peer_CN) {
1652 memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
1653 peer_CN[j] = '\0';
1654 }
1655 }
1656 }
1657 else /* not a UTF8 name */
1658 j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
1659
1660 if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
1661 /* there was a terminating zero before the end of string, this
1662 cannot match and we return failure! */
1663 failf(data, "SSL: illegal cert name field");
1664 result = CURLE_PEER_FAILED_VERIFICATION;
1665 }
1666 }
1667 }
1668
1669 if(peer_CN == nulstr)
1670 peer_CN = NULL;
1671 else {
1672 /* convert peer_CN from UTF8 */
1673 CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
1674 strlen((char *)peer_CN));
1675 /* Curl_convert_from_utf8 calls failf if unsuccessful */
1676 if(rc) {
1677 OPENSSL_free(peer_CN);
1678 return rc;
1679 }
1680 }
1681
1682 if(result)
1683 /* error already detected, pass through */
1684 ;
1685 else if(!peer_CN) {
1686 failf(data,
1687 "SSL: unable to obtain common name from peer certificate");
1688 result = CURLE_PEER_FAILED_VERIFICATION;
1689 }
1690 else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
1691 failf(data, "SSL: certificate subject name '%s' does not match "
1692 "target host name '%s'", peer_CN, dispname);
1693 result = CURLE_PEER_FAILED_VERIFICATION;
1694 }
1695 else {
1696 infof(data, " common name: %s (matched)\n", peer_CN);
1697 }
1698 if(peer_CN)
1699 OPENSSL_free(peer_CN);
1700 }
1701
1702 return result;
1703}
1704
1705#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
1706 !defined(OPENSSL_NO_OCSP)
1707static CURLcode verifystatus(struct connectdata *conn,
1708 struct ssl_connect_data *connssl)
1709{
1710 int i, ocsp_status;
1711 unsigned char *status;
1712 const unsigned char *p;
1713 CURLcode result = CURLE_OK;
1714 struct Curl_easy *data = conn->data;
1715
1716 OCSP_RESPONSE *rsp = NULL;
1717 OCSP_BASICRESP *br = NULL;
1718 X509_STORE *st = NULL;
1719 STACK_OF(X509) *ch = NULL;
1720
1721 long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &status);
1722
1723 if(!status) {
1724 failf(data, "No OCSP response received");
1725 result = CURLE_SSL_INVALIDCERTSTATUS;
1726 goto end;
1727 }
1728 p = status;
1729 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1730 if(!rsp) {
1731 failf(data, "Invalid OCSP response");
1732 result = CURLE_SSL_INVALIDCERTSTATUS;
1733 goto end;
1734 }
1735
1736 ocsp_status = OCSP_response_status(rsp);
1737 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1738 failf(data, "Invalid OCSP response status: %s (%d)",
1739 OCSP_response_status_str(ocsp_status), ocsp_status);
1740 result = CURLE_SSL_INVALIDCERTSTATUS;
1741 goto end;
1742 }
1743
1744 br = OCSP_response_get1_basic(rsp);
1745 if(!br) {
1746 failf(data, "Invalid OCSP response");
1747 result = CURLE_SSL_INVALIDCERTSTATUS;
1748 goto end;
1749 }
1750
1751 ch = SSL_get_peer_cert_chain(BACKEND->handle);
1752 st = SSL_CTX_get_cert_store(BACKEND->ctx);
1753
1754#if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
1755 (defined(LIBRESSL_VERSION_NUMBER) && \
1756 LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
1757 /* The authorized responder cert in the OCSP response MUST be signed by the
1758 peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
1759 no problem, but if it's an intermediate cert OpenSSL has a bug where it
1760 expects this issuer to be present in the chain embedded in the OCSP
1761 response. So we add it if necessary. */
1762
1763 /* First make sure the peer cert chain includes both a peer and an issuer,
1764 and the OCSP response contains a responder cert. */
1765 if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
1766 X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
1767
1768 /* Find issuer of responder cert and add it to the OCSP response chain */
1769 for(i = 0; i < sk_X509_num(ch); i++) {
1770 X509 *issuer = sk_X509_value(ch, i);
1771 if(X509_check_issued(issuer, responder) == X509_V_OK) {
1772 if(!OCSP_basic_add1_cert(br, issuer)) {
1773 failf(data, "Could not add issuer cert to OCSP response");
1774 result = CURLE_SSL_INVALIDCERTSTATUS;
1775 goto end;
1776 }
1777 }
1778 }
1779 }
1780#endif
1781
1782 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
1783 failf(data, "OCSP response verification failed");
1784 result = CURLE_SSL_INVALIDCERTSTATUS;
1785 goto end;
1786 }
1787
1788 for(i = 0; i < OCSP_resp_count(br); i++) {
1789 int cert_status, crl_reason;
1790 OCSP_SINGLERESP *single = NULL;
1791
1792 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1793
1794 single = OCSP_resp_get0(br, i);
1795 if(!single)
1796 continue;
1797
1798 cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
1799 &thisupd, &nextupd);
1800
1801 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
1802 failf(data, "OCSP response has expired");
1803 result = CURLE_SSL_INVALIDCERTSTATUS;
1804 goto end;
1805 }
1806
1807 infof(data, "SSL certificate status: %s (%d)\n",
1808 OCSP_cert_status_str(cert_status), cert_status);
1809
1810 switch(cert_status) {
1811 case V_OCSP_CERTSTATUS_GOOD:
1812 break;
1813
1814 case V_OCSP_CERTSTATUS_REVOKED:
1815 result = CURLE_SSL_INVALIDCERTSTATUS;
1816
1817 failf(data, "SSL certificate revocation reason: %s (%d)",
1818 OCSP_crl_reason_str(crl_reason), crl_reason);
1819 goto end;
1820
1821 case V_OCSP_CERTSTATUS_UNKNOWN:
1822 result = CURLE_SSL_INVALIDCERTSTATUS;
1823 goto end;
1824 }
1825 }
1826
1827end:
1828 if(br) OCSP_BASICRESP_free(br);
1829 OCSP_RESPONSE_free(rsp);
1830
1831 return result;
1832}
1833#endif
1834
1835#endif /* USE_OPENSSL */
1836
1837/* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
1838 and thus this cannot be done there. */
1839#ifdef SSL_CTRL_SET_MSG_CALLBACK
1840
1841static const char *ssl_msg_type(int ssl_ver, int msg)
1842{
1843#ifdef SSL2_VERSION_MAJOR
1844 if(ssl_ver == SSL2_VERSION_MAJOR) {
1845 switch(msg) {
1846 case SSL2_MT_ERROR:
1847 return "Error";
1848 case SSL2_MT_CLIENT_HELLO:
1849 return "Client hello";
1850 case SSL2_MT_CLIENT_MASTER_KEY:
1851 return "Client key";
1852 case SSL2_MT_CLIENT_FINISHED:
1853 return "Client finished";
1854 case SSL2_MT_SERVER_HELLO:
1855 return "Server hello";
1856 case SSL2_MT_SERVER_VERIFY:
1857 return "Server verify";
1858 case SSL2_MT_SERVER_FINISHED:
1859 return "Server finished";
1860 case SSL2_MT_REQUEST_CERTIFICATE:
1861 return "Request CERT";
1862 case SSL2_MT_CLIENT_CERTIFICATE:
1863 return "Client CERT";
1864 }
1865 }
1866 else
1867#endif
1868 if(ssl_ver == SSL3_VERSION_MAJOR) {
1869 switch(msg) {
1870 case SSL3_MT_HELLO_REQUEST:
1871 return "Hello request";
1872 case SSL3_MT_CLIENT_HELLO:
1873 return "Client hello";
1874 case SSL3_MT_SERVER_HELLO:
1875 return "Server hello";
1876#ifdef SSL3_MT_NEWSESSION_TICKET
1877 case SSL3_MT_NEWSESSION_TICKET:
1878 return "Newsession Ticket";
1879#endif
1880 case SSL3_MT_CERTIFICATE:
1881 return "Certificate";
1882 case SSL3_MT_SERVER_KEY_EXCHANGE:
1883 return "Server key exchange";
1884 case SSL3_MT_CLIENT_KEY_EXCHANGE:
1885 return "Client key exchange";
1886 case SSL3_MT_CERTIFICATE_REQUEST:
1887 return "Request CERT";
1888 case SSL3_MT_SERVER_DONE:
1889 return "Server finished";
1890 case SSL3_MT_CERTIFICATE_VERIFY:
1891 return "CERT verify";
1892 case SSL3_MT_FINISHED:
1893 return "Finished";
1894#ifdef SSL3_MT_CERTIFICATE_STATUS
1895 case SSL3_MT_CERTIFICATE_STATUS:
1896 return "Certificate Status";
1897#endif
1898#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
1899 case SSL3_MT_ENCRYPTED_EXTENSIONS:
1900 return "Encrypted Extensions";
1901#endif
1902#ifdef SSL3_MT_END_OF_EARLY_DATA
1903 case SSL3_MT_END_OF_EARLY_DATA:
1904 return "End of early data";
1905#endif
1906#ifdef SSL3_MT_KEY_UPDATE
1907 case SSL3_MT_KEY_UPDATE:
1908 return "Key update";
1909#endif
1910#ifdef SSL3_MT_NEXT_PROTO
1911 case SSL3_MT_NEXT_PROTO:
1912 return "Next protocol";
1913#endif
1914#ifdef SSL3_MT_MESSAGE_HASH
1915 case SSL3_MT_MESSAGE_HASH:
1916 return "Message hash";
1917#endif
1918 }
1919 }
1920 return "Unknown";
1921}
1922
1923static const char *tls_rt_type(int type)
1924{
1925 switch(type) {
1926#ifdef SSL3_RT_HEADER
1927 case SSL3_RT_HEADER:
1928 return "TLS header";
1929#endif
1930 case SSL3_RT_CHANGE_CIPHER_SPEC:
1931 return "TLS change cipher";
1932 case SSL3_RT_ALERT:
1933 return "TLS alert";
1934 case SSL3_RT_HANDSHAKE:
1935 return "TLS handshake";
1936 case SSL3_RT_APPLICATION_DATA:
1937 return "TLS app data";
1938 default:
1939 return "TLS Unknown";
1940 }
1941}
1942
1943
1944/*
1945 * Our callback from the SSL/TLS layers.
1946 */
1947static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
1948 const void *buf, size_t len, SSL *ssl,
1949 void *userp)
1950{
1951 struct Curl_easy *data;
1952 char unknown[32];
1953 const char *verstr = NULL;
1954 struct connectdata *conn = userp;
1955
1956 if(!conn || !conn->data || !conn->data->set.fdebug ||
1957 (direction != 0 && direction != 1))
1958 return;
1959
1960 data = conn->data;
1961
1962 switch(ssl_ver) {
1963#ifdef SSL2_VERSION /* removed in recent versions */
1964 case SSL2_VERSION:
1965 verstr = "SSLv2";
1966 break;
1967#endif
1968#ifdef SSL3_VERSION
1969 case SSL3_VERSION:
1970 verstr = "SSLv3";
1971 break;
1972#endif
1973 case TLS1_VERSION:
1974 verstr = "TLSv1.0";
1975 break;
1976#ifdef TLS1_1_VERSION
1977 case TLS1_1_VERSION:
1978 verstr = "TLSv1.1";
1979 break;
1980#endif
1981#ifdef TLS1_2_VERSION
1982 case TLS1_2_VERSION:
1983 verstr = "TLSv1.2";
1984 break;
1985#endif
1986#ifdef TLS1_3_VERSION
1987 case TLS1_3_VERSION:
1988 verstr = "TLSv1.3";
1989 break;
1990#endif
1991 case 0:
1992 break;
1993 default:
1994 msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
1995 verstr = unknown;
1996 break;
1997 }
1998
1999 /* Log progress for interesting records only (like Handshake or Alert), skip
2000 * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
2001 * For TLS 1.3, skip notification of the decrypted inner Content Type.
2002 */
2003 if(ssl_ver
2004#ifdef SSL3_RT_INNER_CONTENT_TYPE
2005 && content_type != SSL3_RT_INNER_CONTENT_TYPE
2006#endif
2007 ) {
2008 const char *msg_name, *tls_rt_name;
2009 char ssl_buf[1024];
2010 int msg_type, txt_len;
2011
2012 /* the info given when the version is zero is not that useful for us */
2013
2014 ssl_ver >>= 8; /* check the upper 8 bits only below */
2015
2016 /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
2017 * always pass-up content-type as 0. But the interesting message-type
2018 * is at 'buf[0]'.
2019 */
2020 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
2021 tls_rt_name = tls_rt_type(content_type);
2022 else
2023 tls_rt_name = "";
2024
2025 if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
2026 msg_type = *(char *)buf;
2027 msg_name = "Change cipher spec";
2028 }
2029 else if(content_type == SSL3_RT_ALERT) {
2030 msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1];
2031 msg_name = SSL_alert_desc_string_long(msg_type);
2032 }
2033 else {
2034 msg_type = *(char *)buf;
2035 msg_name = ssl_msg_type(ssl_ver, msg_type);
2036 }
2037
2038 txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
2039 verstr, direction?"OUT":"IN",
2040 tls_rt_name, msg_name, msg_type);
2041 if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) {
2042 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
2043 }
2044 }
2045
2046 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
2047 CURLINFO_SSL_DATA_IN, (char *)buf, len);
2048 (void) ssl;
2049}
2050#endif
2051
2052#ifdef USE_OPENSSL
2053/* ====================================================== */
2054
2055#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2056# define use_sni(x) sni = (x)
2057#else
2058# define use_sni(x) Curl_nop_stmt
2059#endif
2060
2061/* Check for OpenSSL 1.0.2 which has ALPN support. */
2062#undef HAS_ALPN
2063#if OPENSSL_VERSION_NUMBER >= 0x10002000L \
2064 && !defined(OPENSSL_NO_TLSEXT)
2065# define HAS_ALPN 1
2066#endif
2067
2068/* Check for OpenSSL 1.0.1 which has NPN support. */
2069#undef HAS_NPN
2070#if OPENSSL_VERSION_NUMBER >= 0x10001000L \
2071 && !defined(OPENSSL_NO_TLSEXT) \
2072 && !defined(OPENSSL_NO_NEXTPROTONEG)
2073# define HAS_NPN 1
2074#endif
2075
2076#ifdef HAS_NPN
2077
2078/*
2079 * in is a list of length prefixed strings. this function has to select
2080 * the protocol we want to use from the list and write its string into out.
2081 */
2082
2083static int
2084select_next_protocol(unsigned char **out, unsigned char *outlen,
2085 const unsigned char *in, unsigned int inlen,
2086 const char *key, unsigned int keylen)
2087{
2088 unsigned int i;
2089 for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
2090 if(memcmp(&in[i + 1], key, keylen) == 0) {
2091 *out = (unsigned char *) &in[i + 1];
2092 *outlen = in[i];
2093 return 0;
2094 }
2095 }
2096 return -1;
2097}
2098
2099static int
2100select_next_proto_cb(SSL *ssl,
2101 unsigned char **out, unsigned char *outlen,
2102 const unsigned char *in, unsigned int inlen,
2103 void *arg)
2104{
2105 struct connectdata *conn = (struct connectdata*) arg;
2106
2107 (void)ssl;
2108
2109#ifdef USE_NGHTTP2
2110 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
2111 !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
2112 NGHTTP2_PROTO_VERSION_ID_LEN)) {
2113 infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
2114 NGHTTP2_PROTO_VERSION_ID);
2115 conn->negnpn = CURL_HTTP_VERSION_2;
2116 return SSL_TLSEXT_ERR_OK;
2117 }
2118#endif
2119
2120 if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
2121 ALPN_HTTP_1_1_LENGTH)) {
2122 infof(conn->data, "NPN, negotiated HTTP1.1\n");
2123 conn->negnpn = CURL_HTTP_VERSION_1_1;
2124 return SSL_TLSEXT_ERR_OK;
2125 }
2126
2127 infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
2128 *out = (unsigned char *)ALPN_HTTP_1_1;
2129 *outlen = ALPN_HTTP_1_1_LENGTH;
2130 conn->negnpn = CURL_HTTP_VERSION_1_1;
2131
2132 return SSL_TLSEXT_ERR_OK;
2133}
2134#endif /* HAS_NPN */
2135
2136#ifndef CURL_DISABLE_VERBOSE_STRINGS
2137static const char *
2138get_ssl_version_txt(SSL *ssl)
2139{
2140 if(!ssl)
2141 return "";
2142
2143 switch(SSL_version(ssl)) {
2144#ifdef TLS1_3_VERSION
2145 case TLS1_3_VERSION:
2146 return "TLSv1.3";
2147#endif
2148#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2149 case TLS1_2_VERSION:
2150 return "TLSv1.2";
2151 case TLS1_1_VERSION:
2152 return "TLSv1.1";
2153#endif
2154 case TLS1_VERSION:
2155 return "TLSv1.0";
2156 case SSL3_VERSION:
2157 return "SSLv3";
2158 case SSL2_VERSION:
2159 return "SSLv2";
2160 }
2161 return "unknown";
2162}
2163#endif
2164
2165#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
2166static CURLcode
2167set_ssl_version_min_max(SSL_CTX *ctx, struct connectdata *conn)
2168{
2169 /* first, TLS min version... */
2170 long curl_ssl_version_min = SSL_CONN_CONFIG(version);
2171 long curl_ssl_version_max;
2172
2173 /* convert cURL min SSL version option to OpenSSL constant */
2174#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
2175 uint16_t ossl_ssl_version_min = 0;
2176 uint16_t ossl_ssl_version_max = 0;
2177#else
2178 long ossl_ssl_version_min = 0;
2179 long ossl_ssl_version_max = 0;
2180#endif
2181 switch(curl_ssl_version_min) {
2182 case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
2183 case CURL_SSLVERSION_TLSv1_0:
2184 ossl_ssl_version_min = TLS1_VERSION;
2185 break;
2186 case CURL_SSLVERSION_TLSv1_1:
2187 ossl_ssl_version_min = TLS1_1_VERSION;
2188 break;
2189 case CURL_SSLVERSION_TLSv1_2:
2190 ossl_ssl_version_min = TLS1_2_VERSION;
2191 break;
2192#ifdef TLS1_3_VERSION
2193 case CURL_SSLVERSION_TLSv1_3:
2194 ossl_ssl_version_min = TLS1_3_VERSION;
2195 break;
2196#endif
2197 }
2198
2199 /* CURL_SSLVERSION_DEFAULT means that no option was selected.
2200 We don't want to pass 0 to SSL_CTX_set_min_proto_version as
2201 it would enable all versions down to the lowest supported by
2202 the library.
2203 So we skip this, and stay with the OS default
2204 */
2205 if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
2206 if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
2207 return CURLE_SSL_CONNECT_ERROR;
2208 }
2209 }
2210
2211 /* ... then, TLS max version */
2212 curl_ssl_version_max = SSL_CONN_CONFIG(version_max);
2213
2214 /* convert cURL max SSL version option to OpenSSL constant */
2215 ossl_ssl_version_max = 0;
2216 switch(curl_ssl_version_max) {
2217 case CURL_SSLVERSION_MAX_TLSv1_0:
2218 ossl_ssl_version_max = TLS1_VERSION;
2219 break;
2220 case CURL_SSLVERSION_MAX_TLSv1_1:
2221 ossl_ssl_version_max = TLS1_1_VERSION;
2222 break;
2223 case CURL_SSLVERSION_MAX_TLSv1_2:
2224 ossl_ssl_version_max = TLS1_2_VERSION;
2225 break;
2226#ifdef TLS1_3_VERSION
2227 case CURL_SSLVERSION_MAX_TLSv1_3:
2228 ossl_ssl_version_max = TLS1_3_VERSION;
2229 break;
2230#endif
2231 case CURL_SSLVERSION_MAX_NONE: /* none selected */
2232 case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
2233 default:
2234 /* SSL_CTX_set_max_proto_version states that:
2235 setting the maximum to 0 will enable
2236 protocol versions up to the highest version
2237 supported by the library */
2238 ossl_ssl_version_max = 0;
2239 break;
2240 }
2241
2242 if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
2243 return CURLE_SSL_CONNECT_ERROR;
2244 }
2245
2246 return CURLE_OK;
2247}
2248#endif
2249
2250#ifdef OPENSSL_IS_BORINGSSL
2251typedef uint32_t ctx_option_t;
2252#else
2253typedef long ctx_option_t;
2254#endif
2255
2256#if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */
2257static CURLcode
2258set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
2259 struct connectdata *conn, int sockindex)
2260{
2261#if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION)
2262 /* convoluted #if condition just to avoid compiler warnings on unused
2263 variable */
2264 struct Curl_easy *data = conn->data;
2265#endif
2266 long ssl_version = SSL_CONN_CONFIG(version);
2267 long ssl_version_max = SSL_CONN_CONFIG(version_max);
2268
2269 switch(ssl_version) {
2270 case CURL_SSLVERSION_TLSv1_3:
2271#ifdef TLS1_3_VERSION
2272 {
2273 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2274 SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION);
2275 *ctx_options |= SSL_OP_NO_TLSv1_2;
2276 }
2277#else
2278 (void)sockindex;
2279 (void)ctx_options;
2280 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2281 return CURLE_NOT_BUILT_IN;
2282#endif
2283 /* FALLTHROUGH */
2284 case CURL_SSLVERSION_TLSv1_2:
2285#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2286 *ctx_options |= SSL_OP_NO_TLSv1_1;
2287#else
2288 failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
2289 return CURLE_NOT_BUILT_IN;
2290#endif
2291 /* FALLTHROUGH */
2292 case CURL_SSLVERSION_TLSv1_1:
2293#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2294 *ctx_options |= SSL_OP_NO_TLSv1;
2295#else
2296 failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
2297 return CURLE_NOT_BUILT_IN;
2298#endif
2299 /* FALLTHROUGH */
2300 case CURL_SSLVERSION_TLSv1_0:
2301 case CURL_SSLVERSION_TLSv1:
2302 break;
2303 }
2304
2305 switch(ssl_version_max) {
2306 case CURL_SSLVERSION_MAX_TLSv1_0:
2307#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2308 *ctx_options |= SSL_OP_NO_TLSv1_1;
2309#endif
2310 /* FALLTHROUGH */
2311 case CURL_SSLVERSION_MAX_TLSv1_1:
2312#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2313 *ctx_options |= SSL_OP_NO_TLSv1_2;
2314#endif
2315 /* FALLTHROUGH */
2316 case CURL_SSLVERSION_MAX_TLSv1_2:
2317#ifdef TLS1_3_VERSION
2318 *ctx_options |= SSL_OP_NO_TLSv1_3;
2319#endif
2320 break;
2321 case CURL_SSLVERSION_MAX_TLSv1_3:
2322#ifdef TLS1_3_VERSION
2323 break;
2324#else
2325 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2326 return CURLE_NOT_BUILT_IN;
2327#endif
2328 }
2329 return CURLE_OK;
2330}
2331#endif
2332
2333/* The "new session" callback must return zero if the session can be removed
2334 * or non-zero if the session has been put into the session cache.
2335 */
2336static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
2337{
2338 int res = 0;
2339 struct connectdata *conn;
2340 struct Curl_easy *data;
2341 int sockindex;
2342 curl_socket_t *sockindex_ptr;
2343 int connectdata_idx = ossl_get_ssl_conn_index();
2344 int sockindex_idx = ossl_get_ssl_sockindex_index();
2345
2346 if(connectdata_idx < 0 || sockindex_idx < 0)
2347 return 0;
2348
2349 conn = (struct connectdata*) SSL_get_ex_data(ssl, connectdata_idx);
2350 if(!conn)
2351 return 0;
2352
2353 data = conn->data;
2354
2355 /* The sockindex has been stored as a pointer to an array element */
2356 sockindex_ptr = (curl_socket_t*) SSL_get_ex_data(ssl, sockindex_idx);
2357 sockindex = (int)(sockindex_ptr - conn->sock);
2358
2359 if(SSL_SET_OPTION(primary.sessionid)) {
2360 bool incache;
2361 void *old_ssl_sessionid = NULL;
2362
2363 Curl_ssl_sessionid_lock(conn);
2364 incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
2365 sockindex));
2366 if(incache) {
2367 if(old_ssl_sessionid != ssl_sessionid) {
2368 infof(data, "old SSL session ID is stale, removing\n");
2369 Curl_ssl_delsessionid(conn, old_ssl_sessionid);
2370 incache = FALSE;
2371 }
2372 }
2373
2374 if(!incache) {
2375 if(!Curl_ssl_addsessionid(conn, ssl_sessionid,
2376 0 /* unknown size */, sockindex)) {
2377 /* the session has been put into the session cache */
2378 res = 1;
2379 }
2380 else
2381 failf(data, "failed to store ssl session");
2382 }
2383 Curl_ssl_sessionid_unlock(conn);
2384 }
2385
2386 return res;
2387}
2388
2389static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
2390{
2391 CURLcode result = CURLE_OK;
2392 char *ciphers;
2393 struct Curl_easy *data = conn->data;
2394 SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
2395 X509_LOOKUP *lookup = NULL;
2396 curl_socket_t sockfd = conn->sock[sockindex];
2397 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2398 ctx_option_t ctx_options = 0;
2399
2400#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2401 bool sni;
2402 const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
2403 conn->host.name;
2404#ifdef ENABLE_IPV6
2405 struct in6_addr addr;
2406#else
2407 struct in_addr addr;
2408#endif
2409#endif
2410 long * const certverifyresult = SSL_IS_PROXY() ?
2411 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2412 const long int ssl_version = SSL_CONN_CONFIG(version);
2413#ifdef USE_TLS_SRP
2414 const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
2415#endif
2416 char * const ssl_cert = SSL_SET_OPTION(cert);
2417 const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
2418 const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
2419 const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
2420 const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
2421 const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
2422 char error_buffer[256];
2423
2424 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
2425
2426 /* Make funny stuff to get random input */
2427 result = Curl_ossl_seed(data);
2428 if(result)
2429 return result;
2430
2431 *certverifyresult = !X509_V_OK;
2432
2433 /* check to see if we've been told to use an explicit SSL/TLS version */
2434
2435 switch(ssl_version) {
2436 case CURL_SSLVERSION_DEFAULT:
2437 case CURL_SSLVERSION_TLSv1:
2438 case CURL_SSLVERSION_TLSv1_0:
2439 case CURL_SSLVERSION_TLSv1_1:
2440 case CURL_SSLVERSION_TLSv1_2:
2441 case CURL_SSLVERSION_TLSv1_3:
2442 /* it will be handled later with the context options */
2443#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
2444 req_method = TLS_client_method();
2445#else
2446 req_method = SSLv23_client_method();
2447#endif
2448 use_sni(TRUE);
2449 break;
2450 case CURL_SSLVERSION_SSLv2:
2451#ifdef OPENSSL_NO_SSL2
2452 failf(data, OSSL_PACKAGE " was built without SSLv2 support");
2453 return CURLE_NOT_BUILT_IN;
2454#else
2455#ifdef USE_TLS_SRP
2456 if(ssl_authtype == CURL_TLSAUTH_SRP)
2457 return CURLE_SSL_CONNECT_ERROR;
2458#endif
2459 req_method = SSLv2_client_method();
2460 use_sni(FALSE);
2461 break;
2462#endif
2463 case CURL_SSLVERSION_SSLv3:
2464#ifdef OPENSSL_NO_SSL3_METHOD
2465 failf(data, OSSL_PACKAGE " was built without SSLv3 support");
2466 return CURLE_NOT_BUILT_IN;
2467#else
2468#ifdef USE_TLS_SRP
2469 if(ssl_authtype == CURL_TLSAUTH_SRP)
2470 return CURLE_SSL_CONNECT_ERROR;
2471#endif
2472 req_method = SSLv3_client_method();
2473 use_sni(FALSE);
2474 break;
2475#endif
2476 default:
2477 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2478 return CURLE_SSL_CONNECT_ERROR;
2479 }
2480
2481 if(BACKEND->ctx)
2482 SSL_CTX_free(BACKEND->ctx);
2483 BACKEND->ctx = SSL_CTX_new(req_method);
2484
2485 if(!BACKEND->ctx) {
2486 failf(data, "SSL: couldn't create a context: %s",
2487 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
2488 return CURLE_OUT_OF_MEMORY;
2489 }
2490
2491#ifdef SSL_MODE_RELEASE_BUFFERS
2492 SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS);
2493#endif
2494
2495#ifdef SSL_CTRL_SET_MSG_CALLBACK
2496 if(data->set.fdebug && data->set.verbose) {
2497 /* the SSL trace callback is only used for verbose logging */
2498 SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace);
2499 SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn);
2500 }
2501#endif
2502
2503 /* OpenSSL contains code to work-around lots of bugs and flaws in various
2504 SSL-implementations. SSL_CTX_set_options() is used to enabled those
2505 work-arounds. The man page for this option states that SSL_OP_ALL enables
2506 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
2507 enable the bug workaround options if compatibility with somewhat broken
2508 implementations is desired."
2509
2510 The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
2511 disable "rfc4507bis session ticket support". rfc4507bis was later turned
2512 into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
2513
2514 The enabled extension concerns the session management. I wonder how often
2515 libcurl stops a connection and then resumes a TLS session. also, sending
2516 the session data is some overhead. .I suggest that you just use your
2517 proposed patch (which explicitly disables TICKET).
2518
2519 If someone writes an application with libcurl and openssl who wants to
2520 enable the feature, one can do this in the SSL callback.
2521
2522 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
2523 interoperability with web server Netscape Enterprise Server 2.0.1 which
2524 was released back in 1996.
2525
2526 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
2527 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
2528 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
2529 this option regardless of OpenSSL version and SSL_OP_ALL definition.
2530
2531 OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
2532 (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
2533 SSL_OP_ALL that _disables_ that work-around despite the fact that
2534 SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
2535 keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
2536 must not be set.
2537 */
2538
2539 ctx_options = SSL_OP_ALL;
2540
2541#ifdef SSL_OP_NO_TICKET
2542 ctx_options |= SSL_OP_NO_TICKET;
2543#endif
2544
2545#ifdef SSL_OP_NO_COMPRESSION
2546 ctx_options |= SSL_OP_NO_COMPRESSION;
2547#endif
2548
2549#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2550 /* mitigate CVE-2010-4180 */
2551 ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
2552#endif
2553
2554#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2555 /* unless the user explicitly ask to allow the protocol vulnerability we
2556 use the work-around */
2557 if(!SSL_SET_OPTION(enable_beast))
2558 ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2559#endif
2560
2561 switch(ssl_version) {
2562 /* "--sslv2" option means SSLv2 only, disable all others */
2563 case CURL_SSLVERSION_SSLv2:
2564#if OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0 */
2565 SSL_CTX_set_min_proto_version(BACKEND->ctx, SSL2_VERSION);
2566 SSL_CTX_set_max_proto_version(BACKEND->ctx, SSL2_VERSION);
2567#else
2568 ctx_options |= SSL_OP_NO_SSLv3;
2569 ctx_options |= SSL_OP_NO_TLSv1;
2570# if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2571 ctx_options |= SSL_OP_NO_TLSv1_1;
2572 ctx_options |= SSL_OP_NO_TLSv1_2;
2573# ifdef TLS1_3_VERSION
2574 ctx_options |= SSL_OP_NO_TLSv1_3;
2575# endif
2576# endif
2577#endif
2578 break;
2579
2580 /* "--sslv3" option means SSLv3 only, disable all others */
2581 case CURL_SSLVERSION_SSLv3:
2582#if OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0 */
2583 SSL_CTX_set_min_proto_version(BACKEND->ctx, SSL3_VERSION);
2584 SSL_CTX_set_max_proto_version(BACKEND->ctx, SSL3_VERSION);
2585#else
2586 ctx_options |= SSL_OP_NO_SSLv2;
2587 ctx_options |= SSL_OP_NO_TLSv1;
2588# if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2589 ctx_options |= SSL_OP_NO_TLSv1_1;
2590 ctx_options |= SSL_OP_NO_TLSv1_2;
2591# ifdef TLS1_3_VERSION
2592 ctx_options |= SSL_OP_NO_TLSv1_3;
2593# endif
2594# endif
2595#endif
2596 break;
2597
2598 /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
2599 case CURL_SSLVERSION_DEFAULT:
2600 case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
2601 case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
2602 case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
2603 case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
2604 case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
2605 /* asking for any TLS version as the minimum, means no SSL versions
2606 allowed */
2607 ctx_options |= SSL_OP_NO_SSLv2;
2608 ctx_options |= SSL_OP_NO_SSLv3;
2609
2610#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
2611 result = set_ssl_version_min_max(BACKEND->ctx, conn);
2612#else
2613 result = set_ssl_version_min_max_legacy(&ctx_options, conn, sockindex);
2614#endif
2615 if(result != CURLE_OK)
2616 return result;
2617 break;
2618
2619 default:
2620 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2621 return CURLE_SSL_CONNECT_ERROR;
2622 }
2623
2624 SSL_CTX_set_options(BACKEND->ctx, ctx_options);
2625
2626#ifdef HAS_NPN
2627 if(conn->bits.tls_enable_npn)
2628 SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn);
2629#endif
2630
2631#ifdef HAS_ALPN
2632 if(conn->bits.tls_enable_alpn) {
2633 int cur = 0;
2634 unsigned char protocols[128];
2635
2636#ifdef USE_NGHTTP2
2637 if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
2638 (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
2639 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
2640
2641 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
2642 NGHTTP2_PROTO_VERSION_ID_LEN);
2643 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
2644 infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
2645 }
2646#endif
2647
2648 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2649 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2650 cur += ALPN_HTTP_1_1_LENGTH;
2651 infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
2652
2653 /* expects length prefixed preference ordered list of protocols in wire
2654 * format
2655 */
2656 SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur);
2657 }
2658#endif
2659
2660 if(ssl_cert || ssl_cert_type) {
2661 if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type,
2662 SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
2663 SSL_SET_OPTION(key_passwd))) {
2664 /* failf() is already done in cert_stuff() */
2665 return CURLE_SSL_CERTPROBLEM;
2666 }
2667 }
2668
2669 ciphers = SSL_CONN_CONFIG(cipher_list);
2670 if(!ciphers)
2671 ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2672 if(ciphers) {
2673 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
2674 failf(data, "failed setting cipher list: %s", ciphers);
2675 return CURLE_SSL_CIPHER;
2676 }
2677 infof(data, "Cipher selection: %s\n", ciphers);
2678 }
2679
2680#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
2681 {
2682 char *ciphers13 = SSL_CONN_CONFIG(cipher_list13);
2683 if(ciphers13) {
2684 if(!SSL_CTX_set_ciphersuites(BACKEND->ctx, ciphers13)) {
2685 failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
2686 return CURLE_SSL_CIPHER;
2687 }
2688 infof(data, "TLS 1.3 cipher selection: %s\n", ciphers13);
2689 }
2690 }
2691#endif
2692
2693#ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
2694 /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
2695 SSL_CTX_set_post_handshake_auth(BACKEND->ctx, 1);
2696#endif
2697
2698#ifdef USE_TLS_SRP
2699 if(ssl_authtype == CURL_TLSAUTH_SRP) {
2700 char * const ssl_username = SSL_SET_OPTION(username);
2701
2702 infof(data, "Using TLS-SRP username: %s\n", ssl_username);
2703
2704 if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) {
2705 failf(data, "Unable to set SRP user name");
2706 return CURLE_BAD_FUNCTION_ARGUMENT;
2707 }
2708 if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) {
2709 failf(data, "failed setting SRP password");
2710 return CURLE_BAD_FUNCTION_ARGUMENT;
2711 }
2712 if(!SSL_CONN_CONFIG(cipher_list)) {
2713 infof(data, "Setting cipher list SRP\n");
2714
2715 if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) {
2716 failf(data, "failed setting SRP cipher list");
2717 return CURLE_SSL_CIPHER;
2718 }
2719 }
2720 }
2721#endif
2722
2723 if(ssl_cafile || ssl_capath) {
2724 /* tell SSL where to find CA certificates that are used to verify
2725 the servers certificate. */
2726 if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) {
2727 if(verifypeer) {
2728 /* Fail if we insist on successfully verifying the server. */
2729 failf(data, "error setting certificate verify locations:\n"
2730 " CAfile: %s\n CApath: %s",
2731 ssl_cafile ? ssl_cafile : "none",
2732 ssl_capath ? ssl_capath : "none");
2733 return CURLE_SSL_CACERT_BADFILE;
2734 }
2735 /* Just continue with a warning if no strict certificate verification
2736 is required. */
2737 infof(data, "error setting certificate verify locations,"
2738 " continuing anyway:\n");
2739 }
2740 else {
2741 /* Everything is fine. */
2742 infof(data, "successfully set certificate verify locations:\n");
2743 }
2744 infof(data,
2745 " CAfile: %s\n"
2746 " CApath: %s\n",
2747 ssl_cafile ? ssl_cafile : "none",
2748 ssl_capath ? ssl_capath : "none");
2749 }
2750#ifdef CURL_CA_FALLBACK
2751 else if(verifypeer) {
2752 /* verifying the peer without any CA certificates won't
2753 work so use openssl's built in default as fallback */
2754 SSL_CTX_set_default_verify_paths(BACKEND->ctx);
2755 }
2756#endif
2757
2758 if(ssl_crlfile) {
2759 /* tell SSL where to find CRL file that is used to check certificate
2760 * revocation */
2761 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx),
2762 X509_LOOKUP_file());
2763 if(!lookup ||
2764 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
2765 failf(data, "error loading CRL file: %s", ssl_crlfile);
2766 return CURLE_SSL_CRL_BADFILE;
2767 }
2768 /* Everything is fine. */
2769 infof(data, "successfully load CRL file:\n");
2770 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2771 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2772
2773 infof(data, " CRLfile: %s\n", ssl_crlfile);
2774 }
2775
2776 if(verifypeer) {
2777 /* Try building a chain using issuers in the trusted store first to avoid
2778 problems with server-sent legacy intermediates. Newer versions of
2779 OpenSSL do alternate chain checking by default which gives us the same
2780 fix without as much of a performance hit (slight), so we prefer that if
2781 available.
2782 https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
2783 */
2784#if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
2785 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2786 X509_V_FLAG_TRUSTED_FIRST);
2787#endif
2788#ifdef X509_V_FLAG_PARTIAL_CHAIN
2789 if(!SSL_SET_OPTION(no_partialchain)) {
2790 /* Have intermediate certificates in the trust store be treated as
2791 trust-anchors, in the same way as self-signed root CA certificates
2792 are. This allows users to verify servers using the intermediate cert
2793 only, instead of needing the whole chain. */
2794 X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
2795 X509_V_FLAG_PARTIAL_CHAIN);
2796 }
2797#endif
2798 }
2799
2800 /* SSL always tries to verify the peer, this only says whether it should
2801 * fail to connect if the verification fails, or if it should continue
2802 * anyway. In the latter case the result of the verification is checked with
2803 * SSL_get_verify_result() below. */
2804 SSL_CTX_set_verify(BACKEND->ctx,
2805 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
2806
2807 /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
2808#if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK)
2809 if(keylog_file_fp) {
2810 SSL_CTX_set_keylog_callback(BACKEND->ctx, ossl_keylog_callback);
2811 }
2812#endif
2813
2814 /* Enable the session cache because it's a prerequisite for the "new session"
2815 * callback. Use the "external storage" mode to avoid that OpenSSL creates
2816 * an internal session cache.
2817 */
2818 SSL_CTX_set_session_cache_mode(BACKEND->ctx,
2819 SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
2820 SSL_CTX_sess_set_new_cb(BACKEND->ctx, ossl_new_session_cb);
2821
2822 /* give application a chance to interfere with SSL set up. */
2823 if(data->set.ssl.fsslctx) {
2824 Curl_set_in_callback(data, true);
2825 result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
2826 data->set.ssl.fsslctxp);
2827 Curl_set_in_callback(data, false);
2828 if(result) {
2829 failf(data, "error signaled by ssl ctx callback");
2830 return result;
2831 }
2832 }
2833
2834 /* Lets make an SSL structure */
2835 if(BACKEND->handle)
2836 SSL_free(BACKEND->handle);
2837 BACKEND->handle = SSL_new(BACKEND->ctx);
2838 if(!BACKEND->handle) {
2839 failf(data, "SSL: couldn't create a context (handle)!");
2840 return CURLE_OUT_OF_MEMORY;
2841 }
2842
2843#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
2844 !defined(OPENSSL_NO_OCSP)
2845 if(SSL_CONN_CONFIG(verifystatus))
2846 SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp);
2847#endif
2848
2849#if defined(OPENSSL_IS_BORINGSSL) && defined(ALLOW_RENEG)
2850 SSL_set_renegotiate_mode(BACKEND->handle, ssl_renegotiate_freely);
2851#endif
2852
2853 SSL_set_connect_state(BACKEND->handle);
2854
2855 BACKEND->server_cert = 0x0;
2856#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2857 if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
2858#ifdef ENABLE_IPV6
2859 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
2860#endif
2861 sni &&
2862 !SSL_set_tlsext_host_name(BACKEND->handle, hostname))
2863 infof(data, "WARNING: failed to configure server name indication (SNI) "
2864 "TLS extension\n");
2865#endif
2866
2867 /* Check if there's a cached ID we can/should use here! */
2868 if(SSL_SET_OPTION(primary.sessionid)) {
2869 void *ssl_sessionid = NULL;
2870 int connectdata_idx = ossl_get_ssl_conn_index();
2871 int sockindex_idx = ossl_get_ssl_sockindex_index();
2872
2873 if(connectdata_idx >= 0 && sockindex_idx >= 0) {
2874 /* Store the data needed for the "new session" callback.
2875 * The sockindex is stored as a pointer to an array element. */
2876 SSL_set_ex_data(BACKEND->handle, connectdata_idx, conn);
2877 SSL_set_ex_data(BACKEND->handle, sockindex_idx, conn->sock + sockindex);
2878 }
2879
2880 Curl_ssl_sessionid_lock(conn);
2881 if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
2882 /* we got a session id, use it! */
2883 if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
2884 Curl_ssl_sessionid_unlock(conn);
2885 failf(data, "SSL: SSL_set_session failed: %s",
2886 ossl_strerror(ERR_get_error(), error_buffer,
2887 sizeof(error_buffer)));
2888 return CURLE_SSL_CONNECT_ERROR;
2889 }
2890 /* Informational message */
2891 infof(data, "SSL re-using session ID\n");
2892 }
2893 Curl_ssl_sessionid_unlock(conn);
2894 }
2895
2896 if(conn->proxy_ssl[sockindex].use) {
2897 BIO *const bio = BIO_new(BIO_f_ssl());
2898 SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
2899 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2900 DEBUGASSERT(handle != NULL);
2901 DEBUGASSERT(bio != NULL);
2902 BIO_set_ssl(bio, handle, FALSE);
2903 SSL_set_bio(BACKEND->handle, bio, bio);
2904 }
2905 else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
2906 /* pass the raw socket into the SSL layers */
2907 failf(data, "SSL: SSL_set_fd failed: %s",
2908 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
2909 return CURLE_SSL_CONNECT_ERROR;
2910 }
2911
2912 connssl->connecting_state = ssl_connect_2;
2913
2914 return CURLE_OK;
2915}
2916
2917static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
2918{
2919 struct Curl_easy *data = conn->data;
2920 int err;
2921 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2922 long * const certverifyresult = SSL_IS_PROXY() ?
2923 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
2924 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
2925 || ssl_connect_2_reading == connssl->connecting_state
2926 || ssl_connect_2_writing == connssl->connecting_state);
2927
2928 ERR_clear_error();
2929
2930 err = SSL_connect(BACKEND->handle);
2931 /* If keylogging is enabled but the keylog callback is not supported then log
2932 secrets here, immediately after SSL_connect by using tap_ssl_key. */
2933#if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK)
2934 tap_ssl_key(BACKEND->handle, &BACKEND->tap_state);
2935#endif
2936
2937 /* 1 is fine
2938 0 is "not successful but was shut down controlled"
2939 <0 is "handshake was not successful, because a fatal error occurred" */
2940 if(1 != err) {
2941 int detail = SSL_get_error(BACKEND->handle, err);
2942
2943 if(SSL_ERROR_WANT_READ == detail) {
2944 connssl->connecting_state = ssl_connect_2_reading;
2945 return CURLE_OK;
2946 }
2947 if(SSL_ERROR_WANT_WRITE == detail) {
2948 connssl->connecting_state = ssl_connect_2_writing;
2949 return CURLE_OK;
2950 }
2951#ifdef SSL_ERROR_WANT_ASYNC
2952 if(SSL_ERROR_WANT_ASYNC == detail) {
2953 connssl->connecting_state = ssl_connect_2;
2954 return CURLE_OK;
2955 }
2956#endif
2957 else {
2958 /* untreated error */
2959 unsigned long errdetail;
2960 char error_buffer[256]="";
2961 CURLcode result;
2962 long lerr;
2963 int lib;
2964 int reason;
2965
2966 /* the connection failed, we're not waiting for anything else. */
2967 connssl->connecting_state = ssl_connect_2;
2968
2969 /* Get the earliest error code from the thread's error queue and removes
2970 the entry. */
2971 errdetail = ERR_get_error();
2972
2973 /* Extract which lib and reason */
2974 lib = ERR_GET_LIB(errdetail);
2975 reason = ERR_GET_REASON(errdetail);
2976
2977 if((lib == ERR_LIB_SSL) &&
2978 (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
2979 result = CURLE_PEER_FAILED_VERIFICATION;
2980
2981 lerr = SSL_get_verify_result(BACKEND->handle);
2982 if(lerr != X509_V_OK) {
2983 *certverifyresult = lerr;
2984 msnprintf(error_buffer, sizeof(error_buffer),
2985 "SSL certificate problem: %s",
2986 X509_verify_cert_error_string(lerr));
2987 }
2988 else
2989 /* strcpy() is fine here as long as the string fits within
2990 error_buffer */
2991 strcpy(error_buffer, "SSL certificate verification failed");
2992 }
2993 else {
2994 result = CURLE_SSL_CONNECT_ERROR;
2995 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
2996 }
2997
2998 /* detail is already set to the SSL error above */
2999
3000 /* If we e.g. use SSLv2 request-method and the server doesn't like us
3001 * (RST connection etc.), OpenSSL gives no explanation whatsoever and
3002 * the SO_ERROR is also lost.
3003 */
3004 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
3005 const char * const hostname = SSL_IS_PROXY() ?
3006 conn->http_proxy.host.name : conn->host.name;
3007 const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
3008 char extramsg[80]="";
3009 int sockerr = SOCKERRNO;
3010 if(sockerr && detail == SSL_ERROR_SYSCALL)
3011 Curl_strerror(sockerr, extramsg, sizeof(extramsg));
3012 failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
3013 extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
3014 hostname, port);
3015 return result;
3016 }
3017
3018 /* Could be a CERT problem */
3019 failf(data, "%s", error_buffer);
3020
3021 return result;
3022 }
3023 }
3024 else {
3025 /* we have been connected fine, we're not waiting for anything else. */
3026 connssl->connecting_state = ssl_connect_3;
3027
3028 /* Informational message */
3029 infof(data, "SSL connection using %s / %s\n",
3030 get_ssl_version_txt(BACKEND->handle),
3031 SSL_get_cipher(BACKEND->handle));
3032
3033#ifdef HAS_ALPN
3034 /* Sets data and len to negotiated protocol, len is 0 if no protocol was
3035 * negotiated
3036 */
3037 if(conn->bits.tls_enable_alpn) {
3038 const unsigned char *neg_protocol;
3039 unsigned int len;
3040 SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len);
3041 if(len != 0) {
3042 infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
3043
3044#ifdef USE_NGHTTP2
3045 if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
3046 !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
3047 conn->negnpn = CURL_HTTP_VERSION_2;
3048 }
3049 else
3050#endif
3051 if(len == ALPN_HTTP_1_1_LENGTH &&
3052 !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
3053 conn->negnpn = CURL_HTTP_VERSION_1_1;
3054 }
3055 }
3056 else
3057 infof(data, "ALPN, server did not agree to a protocol\n");
3058
3059 Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
3060 BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
3061 }
3062#endif
3063
3064 return CURLE_OK;
3065 }
3066}
3067
3068static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
3069{
3070 int i, ilen;
3071
3072 ilen = (int)len;
3073 if(ilen < 0)
3074 return 1; /* buffer too big */
3075
3076 i = i2t_ASN1_OBJECT(buf, ilen, a);
3077
3078 if(i >= ilen)
3079 return 1; /* buffer too small */
3080
3081 return 0;
3082}
3083
3084#define push_certinfo(_label, _num) \
3085do { \
3086 long info_len = BIO_get_mem_data(mem, &ptr); \
3087 Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
3088 if(1 != BIO_reset(mem)) \
3089 break; \
3090} while(0)
3091
3092static void pubkey_show(struct Curl_easy *data,
3093 BIO *mem,
3094 int num,
3095 const char *type,
3096 const char *name,
3097#ifdef HAVE_OPAQUE_RSA_DSA_DH
3098 const
3099#endif
3100 BIGNUM *bn)
3101{
3102 char *ptr;
3103 char namebuf[32];
3104
3105 msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
3106
3107 if(bn)
3108 BN_print(mem, bn);
3109 push_certinfo(namebuf, num);
3110}
3111
3112#ifdef HAVE_OPAQUE_RSA_DSA_DH
3113#define print_pubkey_BN(_type, _name, _num) \
3114 pubkey_show(data, mem, _num, #_type, #_name, _name)
3115
3116#else
3117#define print_pubkey_BN(_type, _name, _num) \
3118do { \
3119 if(_type->_name) { \
3120 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
3121 } \
3122} while(0)
3123#endif
3124
3125static int X509V3_ext(struct Curl_easy *data,
3126 int certnum,
3127 CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
3128{
3129 int i;
3130 size_t j;
3131
3132 if((int)sk_X509_EXTENSION_num(exts) <= 0)
3133 /* no extensions, bail out */
3134 return 1;
3135
3136 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
3137 ASN1_OBJECT *obj;
3138 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
3139 BUF_MEM *biomem;
3140 char buf[512];
3141 char *ptr = buf;
3142 char namebuf[128];
3143 BIO *bio_out = BIO_new(BIO_s_mem());
3144
3145 if(!bio_out)
3146 return 1;
3147
3148 obj = X509_EXTENSION_get_object(ext);
3149
3150 asn1_object_dump(obj, namebuf, sizeof(namebuf));
3151
3152 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
3153 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
3154
3155 BIO_get_mem_ptr(bio_out, &biomem);
3156
3157 for(j = 0; j < (size_t)biomem->length; j++) {
3158 const char *sep = "";
3159 if(biomem->data[j] == '\n') {
3160 sep = ", ";
3161 j++; /* skip the newline */
3162 };
3163 while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
3164 j++;
3165 if(j<(size_t)biomem->length)
3166 ptr += msnprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
3167 biomem->data[j]);
3168 }
3169
3170 Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
3171
3172 BIO_free(bio_out);
3173
3174 }
3175 return 0; /* all is fine */
3176}
3177
3178#ifdef OPENSSL_IS_BORINGSSL
3179typedef size_t numcert_t;
3180#else
3181typedef int numcert_t;
3182#endif
3183
3184static CURLcode get_cert_chain(struct connectdata *conn,
3185 struct ssl_connect_data *connssl)
3186
3187{
3188 CURLcode result;
3189 STACK_OF(X509) *sk;
3190 int i;
3191 struct Curl_easy *data = conn->data;
3192 numcert_t numcerts;
3193 BIO *mem;
3194
3195 sk = SSL_get_peer_cert_chain(BACKEND->handle);
3196 if(!sk) {
3197 return CURLE_OUT_OF_MEMORY;
3198 }
3199
3200 numcerts = sk_X509_num(sk);
3201
3202 result = Curl_ssl_init_certinfo(data, (int)numcerts);
3203 if(result) {
3204 return result;
3205 }
3206
3207 mem = BIO_new(BIO_s_mem());
3208
3209 for(i = 0; i < (int)numcerts; i++) {
3210 ASN1_INTEGER *num;
3211 X509 *x = sk_X509_value(sk, i);
3212 EVP_PKEY *pubkey = NULL;
3213 int j;
3214 char *ptr;
3215 const ASN1_BIT_STRING *psig = NULL;
3216
3217 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
3218 push_certinfo("Subject", i);
3219
3220 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
3221 push_certinfo("Issuer", i);
3222
3223 BIO_printf(mem, "%lx", X509_get_version(x));
3224 push_certinfo("Version", i);
3225
3226 num = X509_get_serialNumber(x);
3227 if(num->type == V_ASN1_NEG_INTEGER)
3228 BIO_puts(mem, "-");
3229 for(j = 0; j < num->length; j++)
3230 BIO_printf(mem, "%02x", num->data[j]);
3231 push_certinfo("Serial Number", i);
3232
3233#if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
3234 {
3235 const X509_ALGOR *sigalg = NULL;
3236 X509_PUBKEY *xpubkey = NULL;
3237 ASN1_OBJECT *pubkeyoid = NULL;
3238
3239 X509_get0_signature(&psig, &sigalg, x);
3240 if(sigalg) {
3241 i2a_ASN1_OBJECT(mem, sigalg->algorithm);
3242 push_certinfo("Signature Algorithm", i);
3243 }
3244
3245 xpubkey = X509_get_X509_PUBKEY(x);
3246 if(xpubkey) {
3247 X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
3248 if(pubkeyoid) {
3249 i2a_ASN1_OBJECT(mem, pubkeyoid);
3250 push_certinfo("Public Key Algorithm", i);
3251 }
3252 }
3253
3254 X509V3_ext(data, i, X509_get0_extensions(x));
3255 }
3256#else
3257 {
3258 /* before OpenSSL 1.0.2 */
3259 X509_CINF *cinf = x->cert_info;
3260
3261 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
3262 push_certinfo("Signature Algorithm", i);
3263
3264 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
3265 push_certinfo("Public Key Algorithm", i);
3266
3267 X509V3_ext(data, i, cinf->extensions);
3268
3269 psig = x->signature;
3270 }
3271#endif
3272
3273 ASN1_TIME_print(mem, X509_get0_notBefore(x));
3274 push_certinfo("Start date", i);
3275
3276 ASN1_TIME_print(mem, X509_get0_notAfter(x));
3277 push_certinfo("Expire date", i);
3278
3279 pubkey = X509_get_pubkey(x);
3280 if(!pubkey)
3281 infof(data, " Unable to load public key\n");
3282 else {
3283 int pktype;
3284#ifdef HAVE_OPAQUE_EVP_PKEY
3285 pktype = EVP_PKEY_id(pubkey);
3286#else
3287 pktype = pubkey->type;
3288#endif
3289 switch(pktype) {
3290 case EVP_PKEY_RSA:
3291 {
3292 RSA *rsa;
3293#ifdef HAVE_OPAQUE_EVP_PKEY
3294 rsa = EVP_PKEY_get0_RSA(pubkey);
3295#else
3296 rsa = pubkey->pkey.rsa;
3297#endif
3298
3299#ifdef HAVE_OPAQUE_RSA_DSA_DH
3300 {
3301 const BIGNUM *n;
3302 const BIGNUM *e;
3303
3304 RSA_get0_key(rsa, &n, &e, NULL);
3305 BIO_printf(mem, "%d", BN_num_bits(n));
3306 push_certinfo("RSA Public Key", i);
3307 print_pubkey_BN(rsa, n, i);
3308 print_pubkey_BN(rsa, e, i);
3309 }
3310#else
3311 BIO_printf(mem, "%d", BN_num_bits(rsa->n));
3312 push_certinfo("RSA Public Key", i);
3313 print_pubkey_BN(rsa, n, i);
3314 print_pubkey_BN(rsa, e, i);
3315#endif
3316
3317 break;
3318 }
3319 case EVP_PKEY_DSA:
3320 {
3321#ifndef OPENSSL_NO_DSA
3322 DSA *dsa;
3323#ifdef HAVE_OPAQUE_EVP_PKEY
3324 dsa = EVP_PKEY_get0_DSA(pubkey);
3325#else
3326 dsa = pubkey->pkey.dsa;
3327#endif
3328#ifdef HAVE_OPAQUE_RSA_DSA_DH
3329 {
3330 const BIGNUM *p;
3331 const BIGNUM *q;
3332 const BIGNUM *g;
3333 const BIGNUM *pub_key;
3334
3335 DSA_get0_pqg(dsa, &p, &q, &g);
3336 DSA_get0_key(dsa, &pub_key, NULL);
3337
3338 print_pubkey_BN(dsa, p, i);
3339 print_pubkey_BN(dsa, q, i);
3340 print_pubkey_BN(dsa, g, i);
3341 print_pubkey_BN(dsa, pub_key, i);
3342 }
3343#else
3344 print_pubkey_BN(dsa, p, i);
3345 print_pubkey_BN(dsa, q, i);
3346 print_pubkey_BN(dsa, g, i);
3347 print_pubkey_BN(dsa, pub_key, i);
3348#endif
3349#endif /* !OPENSSL_NO_DSA */
3350 break;
3351 }
3352 case EVP_PKEY_DH:
3353 {
3354 DH *dh;
3355#ifdef HAVE_OPAQUE_EVP_PKEY
3356 dh = EVP_PKEY_get0_DH(pubkey);
3357#else
3358 dh = pubkey->pkey.dh;
3359#endif
3360#ifdef HAVE_OPAQUE_RSA_DSA_DH
3361 {
3362 const BIGNUM *p;
3363 const BIGNUM *q;
3364 const BIGNUM *g;
3365 const BIGNUM *pub_key;
3366 DH_get0_pqg(dh, &p, &q, &g);
3367 DH_get0_key(dh, &pub_key, NULL);
3368 print_pubkey_BN(dh, p, i);
3369 print_pubkey_BN(dh, q, i);
3370 print_pubkey_BN(dh, g, i);
3371 print_pubkey_BN(dh, pub_key, i);
3372 }
3373#else
3374 print_pubkey_BN(dh, p, i);
3375 print_pubkey_BN(dh, g, i);
3376 print_pubkey_BN(dh, pub_key, i);
3377#endif
3378 break;
3379 }
3380 }
3381 EVP_PKEY_free(pubkey);
3382 }
3383
3384 if(psig) {
3385 for(j = 0; j < psig->length; j++)
3386 BIO_printf(mem, "%02x:", psig->data[j]);
3387 push_certinfo("Signature", i);
3388 }
3389
3390 PEM_write_bio_X509(mem, x);
3391 push_certinfo("Cert", i);
3392 }
3393
3394 BIO_free(mem);
3395
3396 return CURLE_OK;
3397}
3398
3399/*
3400 * Heavily modified from:
3401 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
3402 */
3403static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
3404 const char *pinnedpubkey)
3405{
3406 /* Scratch */
3407 int len1 = 0, len2 = 0;
3408 unsigned char *buff1 = NULL, *temp = NULL;
3409
3410 /* Result is returned to caller */
3411 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
3412
3413 /* if a path wasn't specified, don't pin */
3414 if(!pinnedpubkey)
3415 return CURLE_OK;
3416
3417 if(!cert)
3418 return result;
3419
3420 do {
3421 /* Begin Gyrations to get the subjectPublicKeyInfo */
3422 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
3423
3424 /* https://groups.google.com/group/mailing.openssl.users/browse_thread
3425 /thread/d61858dae102c6c7 */
3426 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
3427 if(len1 < 1)
3428 break; /* failed */
3429
3430 buff1 = temp = malloc(len1);
3431 if(!buff1)
3432 break; /* failed */
3433
3434 /* https://www.openssl.org/docs/crypto/d2i_X509.html */
3435 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
3436
3437 /*
3438 * These checks are verifying we got back the same values as when we
3439 * sized the buffer. It's pretty weak since they should always be the
3440 * same. But it gives us something to test.
3441 */
3442 if((len1 != len2) || !temp || ((temp - buff1) != len1))
3443 break; /* failed */
3444
3445 /* End Gyrations */
3446
3447 /* The one good exit point */
3448 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
3449 } while(0);
3450
3451 if(buff1)
3452 free(buff1);
3453
3454 return result;
3455}
3456
3457/*
3458 * Get the server cert, verify it and show it etc, only call failf() if the
3459 * 'strict' argument is TRUE as otherwise all this is for informational
3460 * purposes only!
3461 *
3462 * We check certificates to authenticate the server; otherwise we risk
3463 * man-in-the-middle attack.
3464 */
3465static CURLcode servercert(struct connectdata *conn,
3466 struct ssl_connect_data *connssl,
3467 bool strict)
3468{
3469 CURLcode result = CURLE_OK;
3470 int rc;
3471 long lerr;
3472 struct Curl_easy *data = conn->data;
3473 X509 *issuer;
3474 BIO *fp = NULL;
3475 char error_buffer[256]="";
3476 char buffer[2048];
3477 const char *ptr;
3478 long * const certverifyresult = SSL_IS_PROXY() ?
3479 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
3480 BIO *mem = BIO_new(BIO_s_mem());
3481
3482 if(data->set.ssl.certinfo)
3483 /* we've been asked to gather certificate info! */
3484 (void)get_cert_chain(conn, connssl);
3485
3486 BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle);
3487 if(!BACKEND->server_cert) {
3488 BIO_free(mem);
3489 if(!strict)
3490 return CURLE_OK;
3491
3492 failf(data, "SSL: couldn't get peer certificate!");
3493 return CURLE_PEER_FAILED_VERIFICATION;
3494 }
3495
3496 infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
3497
3498 rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert),
3499 buffer, sizeof(buffer));
3500 infof(data, " subject: %s\n", rc?"[NONE]":buffer);
3501
3502#ifndef CURL_DISABLE_VERBOSE_STRINGS
3503 {
3504 long len;
3505 ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert));
3506 len = BIO_get_mem_data(mem, (char **) &ptr);
3507 infof(data, " start date: %.*s\n", len, ptr);
3508 (void)BIO_reset(mem);
3509
3510 ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert));
3511 len = BIO_get_mem_data(mem, (char **) &ptr);
3512 infof(data, " expire date: %.*s\n", len, ptr);
3513 (void)BIO_reset(mem);
3514 }
3515#endif
3516
3517 BIO_free(mem);
3518
3519 if(SSL_CONN_CONFIG(verifyhost)) {
3520 result = verifyhost(conn, BACKEND->server_cert);
3521 if(result) {
3522 X509_free(BACKEND->server_cert);
3523 BACKEND->server_cert = NULL;
3524 return result;
3525 }
3526 }
3527
3528 rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert),
3529 buffer, sizeof(buffer));
3530 if(rc) {
3531 if(strict)
3532 failf(data, "SSL: couldn't get X509-issuer name!");
3533 result = CURLE_PEER_FAILED_VERIFICATION;
3534 }
3535 else {
3536 infof(data, " issuer: %s\n", buffer);
3537
3538 /* We could do all sorts of certificate verification stuff here before
3539 deallocating the certificate. */
3540
3541 /* e.g. match issuer name with provided issuer certificate */
3542 if(SSL_SET_OPTION(issuercert)) {
3543 fp = BIO_new(BIO_s_file());
3544 if(fp == NULL) {
3545 failf(data,
3546 "BIO_new return NULL, " OSSL_PACKAGE
3547 " error %s",
3548 ossl_strerror(ERR_get_error(), error_buffer,
3549 sizeof(error_buffer)) );
3550 X509_free(BACKEND->server_cert);
3551 BACKEND->server_cert = NULL;
3552 return CURLE_OUT_OF_MEMORY;
3553 }
3554
3555 if(BIO_read_filename(fp, SSL_SET_OPTION(issuercert)) <= 0) {
3556 if(strict)
3557 failf(data, "SSL: Unable to open issuer cert (%s)",
3558 SSL_SET_OPTION(issuercert));
3559 BIO_free(fp);
3560 X509_free(BACKEND->server_cert);
3561 BACKEND->server_cert = NULL;
3562 return CURLE_SSL_ISSUER_ERROR;
3563 }
3564
3565 issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
3566 if(!issuer) {
3567 if(strict)
3568 failf(data, "SSL: Unable to read issuer cert (%s)",
3569 SSL_SET_OPTION(issuercert));
3570 BIO_free(fp);
3571 X509_free(issuer);
3572 X509_free(BACKEND->server_cert);
3573 BACKEND->server_cert = NULL;
3574 return CURLE_SSL_ISSUER_ERROR;
3575 }
3576
3577 if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) {
3578 if(strict)
3579 failf(data, "SSL: Certificate issuer check failed (%s)",
3580 SSL_SET_OPTION(issuercert));
3581 BIO_free(fp);
3582 X509_free(issuer);
3583 X509_free(BACKEND->server_cert);
3584 BACKEND->server_cert = NULL;
3585 return CURLE_SSL_ISSUER_ERROR;
3586 }
3587
3588 infof(data, " SSL certificate issuer check ok (%s)\n",
3589 SSL_SET_OPTION(issuercert));
3590 BIO_free(fp);
3591 X509_free(issuer);
3592 }
3593
3594 lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle);
3595
3596 if(*certverifyresult != X509_V_OK) {
3597 if(SSL_CONN_CONFIG(verifypeer)) {
3598 /* We probably never reach this, because SSL_connect() will fail
3599 and we return earlier if verifypeer is set? */
3600 if(strict)
3601 failf(data, "SSL certificate verify result: %s (%ld)",
3602 X509_verify_cert_error_string(lerr), lerr);
3603 result = CURLE_PEER_FAILED_VERIFICATION;
3604 }
3605 else
3606 infof(data, " SSL certificate verify result: %s (%ld),"
3607 " continuing anyway.\n",
3608 X509_verify_cert_error_string(lerr), lerr);
3609 }
3610 else
3611 infof(data, " SSL certificate verify ok.\n");
3612 }
3613
3614#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3615 !defined(OPENSSL_NO_OCSP)
3616 if(SSL_CONN_CONFIG(verifystatus)) {
3617 result = verifystatus(conn, connssl);
3618 if(result) {
3619 X509_free(BACKEND->server_cert);
3620 BACKEND->server_cert = NULL;
3621 return result;
3622 }
3623 }
3624#endif
3625
3626 if(!strict)
3627 /* when not strict, we don't bother about the verify cert problems */
3628 result = CURLE_OK;
3629
3630 ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
3631 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
3632 if(!result && ptr) {
3633 result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr);
3634 if(result)
3635 failf(data, "SSL: public key does not match pinned public key!");
3636 }
3637
3638 X509_free(BACKEND->server_cert);
3639 BACKEND->server_cert = NULL;
3640 connssl->connecting_state = ssl_connect_done;
3641
3642 return result;
3643}
3644
3645static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
3646{
3647 CURLcode result = CURLE_OK;
3648 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3649
3650 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
3651
3652 /*
3653 * We check certificates to authenticate the server; otherwise we risk
3654 * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
3655 * verify the peer ignore faults and failures from the server cert
3656 * operations.
3657 */
3658
3659 result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
3660 SSL_CONN_CONFIG(verifyhost)));
3661
3662 if(!result)
3663 connssl->connecting_state = ssl_connect_done;
3664
3665 return result;
3666}
3667
3668static Curl_recv ossl_recv;
3669static Curl_send ossl_send;
3670
3671static CURLcode ossl_connect_common(struct connectdata *conn,
3672 int sockindex,
3673 bool nonblocking,
3674 bool *done)
3675{
3676 CURLcode result;
3677 struct Curl_easy *data = conn->data;
3678 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3679 curl_socket_t sockfd = conn->sock[sockindex];
3680 timediff_t timeout_ms;
3681 int what;
3682
3683 /* check if the connection has already been established */
3684 if(ssl_connection_complete == connssl->state) {
3685 *done = TRUE;
3686 return CURLE_OK;
3687 }
3688
3689 if(ssl_connect_1 == connssl->connecting_state) {
3690 /* Find out how much more time we're allowed */
3691 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3692
3693 if(timeout_ms < 0) {
3694 /* no need to continue if time already is up */
3695 failf(data, "SSL connection timeout");
3696 return CURLE_OPERATION_TIMEDOUT;
3697 }
3698
3699 result = ossl_connect_step1(conn, sockindex);
3700 if(result)
3701 return result;
3702 }
3703
3704 while(ssl_connect_2 == connssl->connecting_state ||
3705 ssl_connect_2_reading == connssl->connecting_state ||
3706 ssl_connect_2_writing == connssl->connecting_state) {
3707
3708 /* check allowed time left */
3709 timeout_ms = Curl_timeleft(data, NULL, TRUE);
3710
3711 if(timeout_ms < 0) {
3712 /* no need to continue if time already is up */
3713 failf(data, "SSL connection timeout");
3714 return CURLE_OPERATION_TIMEDOUT;
3715 }
3716
3717 /* if ssl is expecting something, check if it's available. */
3718 if(connssl->connecting_state == ssl_connect_2_reading ||
3719 connssl->connecting_state == ssl_connect_2_writing) {
3720
3721 curl_socket_t writefd = ssl_connect_2_writing ==
3722 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3723 curl_socket_t readfd = ssl_connect_2_reading ==
3724 connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
3725
3726 what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
3727 nonblocking?0:(time_t)timeout_ms);
3728 if(what < 0) {
3729 /* fatal error */
3730 failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
3731 return CURLE_SSL_CONNECT_ERROR;
3732 }
3733 if(0 == what) {
3734 if(nonblocking) {
3735 *done = FALSE;
3736 return CURLE_OK;
3737 }
3738 /* timeout */
3739 failf(data, "SSL connection timeout");
3740 return CURLE_OPERATION_TIMEDOUT;
3741 }
3742 /* socket is readable or writable */
3743 }
3744
3745 /* Run transaction, and return to the caller if it failed or if this
3746 * connection is done nonblocking and this loop would execute again. This
3747 * permits the owner of a multi handle to abort a connection attempt
3748 * before step2 has completed while ensuring that a client using select()
3749 * or epoll() will always have a valid fdset to wait on.
3750 */
3751 result = ossl_connect_step2(conn, sockindex);
3752 if(result || (nonblocking &&
3753 (ssl_connect_2 == connssl->connecting_state ||
3754 ssl_connect_2_reading == connssl->connecting_state ||
3755 ssl_connect_2_writing == connssl->connecting_state)))
3756 return result;
3757
3758 } /* repeat step2 until all transactions are done. */
3759
3760 if(ssl_connect_3 == connssl->connecting_state) {
3761 result = ossl_connect_step3(conn, sockindex);
3762 if(result)
3763 return result;
3764 }
3765
3766 if(ssl_connect_done == connssl->connecting_state) {
3767 connssl->state = ssl_connection_complete;
3768 conn->recv[sockindex] = ossl_recv;
3769 conn->send[sockindex] = ossl_send;
3770 *done = TRUE;
3771 }
3772 else
3773 *done = FALSE;
3774
3775 /* Reset our connect state machine */
3776 connssl->connecting_state = ssl_connect_1;
3777
3778 return CURLE_OK;
3779}
3780
3781static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
3782 int sockindex,
3783 bool *done)
3784{
3785 return ossl_connect_common(conn, sockindex, TRUE, done);
3786}
3787
3788static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
3789{
3790 CURLcode result;
3791 bool done = FALSE;
3792
3793 result = ossl_connect_common(conn, sockindex, FALSE, &done);
3794 if(result)
3795 return result;
3796
3797 DEBUGASSERT(done);
3798
3799 return CURLE_OK;
3800}
3801
3802static bool Curl_ossl_data_pending(const struct connectdata *conn,
3803 int connindex)
3804{
3805 const struct ssl_connect_data *connssl = &conn->ssl[connindex];
3806 const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
3807
3808 if(connssl->backend->handle && SSL_pending(connssl->backend->handle))
3809 return TRUE;
3810
3811 if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle))
3812 return TRUE;
3813
3814 return FALSE;
3815}
3816
3817static size_t Curl_ossl_version(char *buffer, size_t size);
3818
3819static ssize_t ossl_send(struct connectdata *conn,
3820 int sockindex,
3821 const void *mem,
3822 size_t len,
3823 CURLcode *curlcode)
3824{
3825 /* SSL_write() is said to return 'int' while write() and send() returns
3826 'size_t' */
3827 int err;
3828 char error_buffer[256];
3829 unsigned long sslerror;
3830 int memlen;
3831 int rc;
3832 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3833
3834 ERR_clear_error();
3835
3836 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
3837 rc = SSL_write(BACKEND->handle, mem, memlen);
3838
3839 if(rc <= 0) {
3840 err = SSL_get_error(BACKEND->handle, rc);
3841
3842 switch(err) {
3843 case SSL_ERROR_WANT_READ:
3844 case SSL_ERROR_WANT_WRITE:
3845 /* The operation did not complete; the same TLS/SSL I/O function
3846 should be called again later. This is basically an EWOULDBLOCK
3847 equivalent. */
3848 *curlcode = CURLE_AGAIN;
3849 return -1;
3850 case SSL_ERROR_SYSCALL:
3851 {
3852 int sockerr = SOCKERRNO;
3853 sslerror = ERR_get_error();
3854 if(sslerror)
3855 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
3856 else if(sockerr)
3857 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
3858 else {
3859 strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
3860 error_buffer[sizeof(error_buffer) - 1] = '\0';
3861 }
3862 failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
3863 error_buffer, sockerr);
3864 *curlcode = CURLE_SEND_ERROR;
3865 return -1;
3866 }
3867 case SSL_ERROR_SSL:
3868 /* A failure in the SSL library occurred, usually a protocol error.
3869 The OpenSSL error queue contains more information on the error. */
3870 sslerror = ERR_get_error();
3871 if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
3872 ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
3873 conn->ssl[sockindex].state == ssl_connection_complete &&
3874 conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
3875 char ver[120];
3876 Curl_ossl_version(ver, 120);
3877 failf(conn->data, "Error: %s does not support double SSL tunneling.",
3878 ver);
3879 }
3880 else
3881 failf(conn->data, "SSL_write() error: %s",
3882 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
3883 *curlcode = CURLE_SEND_ERROR;
3884 return -1;
3885 }
3886 /* a true error */
3887 failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
3888 SSL_ERROR_to_str(err), SOCKERRNO);
3889 *curlcode = CURLE_SEND_ERROR;
3890 return -1;
3891 }
3892 *curlcode = CURLE_OK;
3893 return (ssize_t)rc; /* number of bytes */
3894}
3895
3896static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
3897 int num, /* socketindex */
3898 char *buf, /* store read data here */
3899 size_t buffersize, /* max amount to read */
3900 CURLcode *curlcode)
3901{
3902 char error_buffer[256];
3903 unsigned long sslerror;
3904 ssize_t nread;
3905 int buffsize;
3906 struct ssl_connect_data *connssl = &conn->ssl[num];
3907
3908 ERR_clear_error();
3909
3910 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
3911 nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
3912 if(nread <= 0) {
3913 /* failed SSL_read */
3914 int err = SSL_get_error(BACKEND->handle, (int)nread);
3915
3916 switch(err) {
3917 case SSL_ERROR_NONE: /* this is not an error */
3918 break;
3919 case SSL_ERROR_ZERO_RETURN: /* no more data */
3920 /* close_notify alert */
3921 if(num == FIRSTSOCKET)
3922 /* mark the connection for close if it is indeed the control
3923 connection */
3924 connclose(conn, "TLS close_notify");
3925 break;
3926 case SSL_ERROR_WANT_READ:
3927 case SSL_ERROR_WANT_WRITE:
3928 /* there's data pending, re-invoke SSL_read() */
3929 *curlcode = CURLE_AGAIN;
3930 return -1;
3931 default:
3932 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
3933 value/errno" */
3934 /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
3935 sslerror = ERR_get_error();
3936 if((nread < 0) || sslerror) {
3937 /* If the return code was negative or there actually is an error in the
3938 queue */
3939 int sockerr = SOCKERRNO;
3940 if(sslerror)
3941 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
3942 else if(sockerr && err == SSL_ERROR_SYSCALL)
3943 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
3944 else {
3945 strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
3946 error_buffer[sizeof(error_buffer) - 1] = '\0';
3947 }
3948 failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d",
3949 error_buffer, sockerr);
3950 *curlcode = CURLE_RECV_ERROR;
3951 return -1;
3952 }
3953 /* For debug builds be a little stricter and error on any
3954 SSL_ERROR_SYSCALL. For example a server may have closed the connection
3955 abruptly without a close_notify alert. For compatibility with older
3956 peers we don't do this by default. #4624
3957
3958 We can use this to gauge how many users may be affected, and
3959 if it goes ok eventually transition to allow in dev and release with
3960 the newest OpenSSL: #if (OPENSSL_VERSION_NUMBER >= 0x10101000L) */
3961#ifdef DEBUGBUILD
3962 if(err == SSL_ERROR_SYSCALL) {
3963 int sockerr = SOCKERRNO;
3964 if(sockerr)
3965 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
3966 else {
3967 msnprintf(error_buffer, sizeof(error_buffer),
3968 "Connection closed abruptly");
3969 }
3970 failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d"
3971 " (Fatal because this is a curl debug build)",
3972 error_buffer, sockerr);
3973 *curlcode = CURLE_RECV_ERROR;
3974 return -1;
3975 }
3976#endif
3977 }
3978 }
3979 return nread;
3980}
3981
3982static size_t Curl_ossl_version(char *buffer, size_t size)
3983{
3984#ifdef LIBRESSL_VERSION_NUMBER
3985#if LIBRESSL_VERSION_NUMBER < 0x2070100fL
3986 return msnprintf(buffer, size, "%s/%lx.%lx.%lx",
3987 OSSL_PACKAGE,
3988 (LIBRESSL_VERSION_NUMBER>>28)&0xf,
3989 (LIBRESSL_VERSION_NUMBER>>20)&0xff,
3990 (LIBRESSL_VERSION_NUMBER>>12)&0xff);
3991#else /* OpenSSL_version() first appeared in LibreSSL 2.7.1 */
3992 char *p;
3993 int count;
3994 const char *ver = OpenSSL_version(OPENSSL_VERSION);
3995 const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
3996 if(Curl_strncasecompare(ver, expected, sizeof(expected) - 1)) {
3997 ver += sizeof(expected) - 1;
3998 }
3999 count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
4000 for(p = buffer; *p; ++p) {
4001 if(ISSPACE(*p))
4002 *p = '_';
4003 }
4004 return count;
4005#endif
4006#elif defined(OPENSSL_IS_BORINGSSL)
4007 return msnprintf(buffer, size, OSSL_PACKAGE);
4008#elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING)
4009 return msnprintf(buffer, size, "%s/%s",
4010 OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
4011#else
4012 /* not LibreSSL, BoringSSL and not using OpenSSL_version */
4013
4014 char sub[3];
4015 unsigned long ssleay_value;
4016 sub[2]='\0';
4017 sub[1]='\0';
4018 ssleay_value = OpenSSL_version_num();
4019 if(ssleay_value < 0x906000) {
4020 ssleay_value = SSLEAY_VERSION_NUMBER;
4021 sub[0]='\0';
4022 }
4023 else {
4024 if(ssleay_value&0xff0) {
4025 int minor_ver = (ssleay_value >> 4) & 0xff;
4026 if(minor_ver > 26) {
4027 /* handle extended version introduced for 0.9.8za */
4028 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
4029 sub[0] = 'z';
4030 }
4031 else {
4032 sub[0] = (char) (minor_ver + 'a' - 1);
4033 }
4034 }
4035 else
4036 sub[0]='\0';
4037 }
4038
4039 return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
4040#ifdef OPENSSL_FIPS
4041 "-fips"
4042#endif
4043 ,
4044 OSSL_PACKAGE,
4045 (ssleay_value>>28)&0xf,
4046 (ssleay_value>>20)&0xff,
4047 (ssleay_value>>12)&0xff,
4048 sub);
4049#endif /* OPENSSL_IS_BORINGSSL */
4050}
4051
4052/* can be called with data == NULL */
4053static CURLcode Curl_ossl_random(struct Curl_easy *data,
4054 unsigned char *entropy, size_t length)
4055{
4056 int rc;
4057 if(data) {
4058 if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
4059 return CURLE_FAILED_INIT; /* couldn't seed for some reason */
4060 }
4061 else {
4062 if(!rand_enough())
4063 return CURLE_FAILED_INIT;
4064 }
4065 /* RAND_bytes() returns 1 on success, 0 otherwise. */
4066 rc = RAND_bytes(entropy, curlx_uztosi(length));
4067 return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
4068}
4069
4070static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */
4071 size_t tmplen,
4072 unsigned char *md5sum /* output */,
4073 size_t unused)
4074{
4075 EVP_MD_CTX *mdctx;
4076 unsigned int len = 0;
4077 (void) unused;
4078
4079 mdctx = EVP_MD_CTX_create();
4080 EVP_DigestInit_ex(mdctx, EVP_md5(), NULL);
4081 EVP_DigestUpdate(mdctx, tmp, tmplen);
4082 EVP_DigestFinal_ex(mdctx, md5sum, &len);
4083 EVP_MD_CTX_destroy(mdctx);
4084 return CURLE_OK;
4085}
4086
4087#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
4088static CURLcode Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
4089 size_t tmplen,
4090 unsigned char *sha256sum /* output */,
4091 size_t unused)
4092{
4093 EVP_MD_CTX *mdctx;
4094 unsigned int len = 0;
4095 (void) unused;
4096
4097 mdctx = EVP_MD_CTX_create();
4098 EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL);
4099 EVP_DigestUpdate(mdctx, tmp, tmplen);
4100 EVP_DigestFinal_ex(mdctx, sha256sum, &len);
4101 EVP_MD_CTX_destroy(mdctx);
4102 return CURLE_OK;
4103}
4104#endif
4105
4106static bool Curl_ossl_cert_status_request(void)
4107{
4108#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
4109 !defined(OPENSSL_NO_OCSP)
4110 return TRUE;
4111#else
4112 return FALSE;
4113#endif
4114}
4115
4116static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl,
4117 CURLINFO info)
4118{
4119 /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
4120 return info == CURLINFO_TLS_SESSION ?
4121 (void *)BACKEND->ctx : (void *)BACKEND->handle;
4122}
4123
4124const struct Curl_ssl Curl_ssl_openssl = {
4125 { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
4126
4127 SSLSUPP_CA_PATH |
4128 SSLSUPP_CERTINFO |
4129 SSLSUPP_PINNEDPUBKEY |
4130 SSLSUPP_SSL_CTX |
4131#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
4132 SSLSUPP_TLS13_CIPHERSUITES |
4133#endif
4134 SSLSUPP_HTTPS_PROXY,
4135
4136 sizeof(struct ssl_backend_data),
4137
4138 Curl_ossl_init, /* init */
4139 Curl_ossl_cleanup, /* cleanup */
4140 Curl_ossl_version, /* version */
4141 Curl_ossl_check_cxn, /* check_cxn */
4142 Curl_ossl_shutdown, /* shutdown */
4143 Curl_ossl_data_pending, /* data_pending */
4144 Curl_ossl_random, /* random */
4145 Curl_ossl_cert_status_request, /* cert_status_request */
4146 Curl_ossl_connect, /* connect */
4147 Curl_ossl_connect_nonblocking, /* connect_nonblocking */
4148 Curl_ossl_get_internals, /* get_internals */
4149 Curl_ossl_close, /* close_one */
4150 Curl_ossl_close_all, /* close_all */
4151 Curl_ossl_session_free, /* session_free */
4152 Curl_ossl_set_engine, /* set_engine */
4153 Curl_ossl_set_engine_default, /* set_engine_default */
4154 Curl_ossl_engines_list, /* engines_list */
4155 Curl_none_false_start, /* false_start */
4156 Curl_ossl_md5sum, /* md5sum */
4157#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
4158 Curl_ossl_sha256sum /* sha256sum */
4159#else
4160 NULL /* sha256sum */
4161#endif
4162};
4163
4164#endif /* USE_OPENSSL */
4165