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