VirtualBox

source: vbox/trunk/src/libs/curl-7.64.0/lib/vtls/openssl.c@ 86643

Last change on this file since 86643 was 85671, checked in by vboxsync, 4 years ago

Export out internal curl copy to make it a lot simpler to build VBox (OSE) on Windows. bugref:9814

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette