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