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