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