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