• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 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 the default reasonably secure without
213  * breaking compatibility, so it is better not to override the default by 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   /* Lets 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_END_OF_EARLY_DATA
2064       case SSL3_MT_END_OF_EARLY_DATA:
2065         return "End of early data";
2066 #endif
2067 #ifdef SSL3_MT_KEY_UPDATE
2068       case SSL3_MT_KEY_UPDATE:
2069         return "Key update";
2070 #endif
2071 #ifdef SSL3_MT_NEXT_PROTO
2072       case SSL3_MT_NEXT_PROTO:
2073         return "Next protocol";
2074 #endif
2075 #ifdef SSL3_MT_MESSAGE_HASH
2076       case SSL3_MT_MESSAGE_HASH:
2077         return "Message hash";
2078 #endif
2079     }
2080   }
2081   return "Unknown";
2082 }
2083 
tls_rt_type(int type)2084 static const char *tls_rt_type(int type)
2085 {
2086   switch(type) {
2087 #ifdef SSL3_RT_HEADER
2088   case SSL3_RT_HEADER:
2089     return "TLS header";
2090 #endif
2091   case SSL3_RT_CHANGE_CIPHER_SPEC:
2092     return "TLS change cipher";
2093   case SSL3_RT_ALERT:
2094     return "TLS alert";
2095   case SSL3_RT_HANDSHAKE:
2096     return "TLS handshake";
2097   case SSL3_RT_APPLICATION_DATA:
2098     return "TLS app data";
2099   default:
2100     return "TLS Unknown";
2101   }
2102 }
2103 
2104 /*
2105  * Our callback from the SSL/TLS layers.
2106  */
ossl_trace(int direction,int ssl_ver,int content_type,const void * buf,size_t len,SSL * ssl,void * userp)2107 static void ossl_trace(int direction, int ssl_ver, int content_type,
2108                        const void *buf, size_t len, SSL *ssl,
2109                        void *userp)
2110 {
2111   char unknown[32];
2112   const char *verstr = NULL;
2113   struct connectdata *conn = userp;
2114   struct ssl_connect_data *connssl = &conn->ssl[0];
2115   struct ssl_backend_data *backend = connssl->backend;
2116   struct Curl_easy *data = backend->logger;
2117 
2118   if(!conn || !data || !data->set.fdebug ||
2119      (direction != 0 && direction != 1))
2120     return;
2121 
2122   switch(ssl_ver) {
2123 #ifdef SSL2_VERSION /* removed in recent versions */
2124   case SSL2_VERSION:
2125     verstr = "SSLv2";
2126     break;
2127 #endif
2128 #ifdef SSL3_VERSION
2129   case SSL3_VERSION:
2130     verstr = "SSLv3";
2131     break;
2132 #endif
2133   case TLS1_VERSION:
2134     verstr = "TLSv1.0";
2135     break;
2136 #ifdef TLS1_1_VERSION
2137   case TLS1_1_VERSION:
2138     verstr = "TLSv1.1";
2139     break;
2140 #endif
2141 #ifdef TLS1_2_VERSION
2142   case TLS1_2_VERSION:
2143     verstr = "TLSv1.2";
2144     break;
2145 #endif
2146 #ifdef TLS1_3_VERSION
2147   case TLS1_3_VERSION:
2148     verstr = "TLSv1.3";
2149     break;
2150 #endif
2151   case 0:
2152     break;
2153   default:
2154     msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
2155     verstr = unknown;
2156     break;
2157   }
2158 
2159   /* Log progress for interesting records only (like Handshake or Alert), skip
2160    * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
2161    * For TLS 1.3, skip notification of the decrypted inner Content Type.
2162    */
2163   if(ssl_ver
2164 #ifdef SSL3_RT_INNER_CONTENT_TYPE
2165      && content_type != SSL3_RT_INNER_CONTENT_TYPE
2166 #endif
2167     ) {
2168     const char *msg_name, *tls_rt_name;
2169     char ssl_buf[1024];
2170     int msg_type, txt_len;
2171 
2172     /* the info given when the version is zero is not that useful for us */
2173 
2174     ssl_ver >>= 8; /* check the upper 8 bits only below */
2175 
2176     /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
2177      * always pass-up content-type as 0. But the interesting message-type
2178      * is at 'buf[0]'.
2179      */
2180     if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
2181       tls_rt_name = tls_rt_type(content_type);
2182     else
2183       tls_rt_name = "";
2184 
2185     if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
2186       msg_type = *(char *)buf;
2187       msg_name = "Change cipher spec";
2188     }
2189     else if(content_type == SSL3_RT_ALERT) {
2190       msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1];
2191       msg_name = SSL_alert_desc_string_long(msg_type);
2192     }
2193     else {
2194       msg_type = *(char *)buf;
2195       msg_name = ssl_msg_type(ssl_ver, msg_type);
2196     }
2197 
2198     txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
2199                         verstr, direction?"OUT":"IN",
2200                         tls_rt_name, msg_name, msg_type);
2201     if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) {
2202       Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
2203     }
2204   }
2205 
2206   Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
2207              CURLINFO_SSL_DATA_IN, (char *)buf, len);
2208   (void) ssl;
2209 }
2210 #endif
2211 
2212 #ifdef USE_OPENSSL
2213 /* ====================================================== */
2214 
2215 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2216 #  define use_sni(x)  sni = (x)
2217 #else
2218 #  define use_sni(x)  Curl_nop_stmt
2219 #endif
2220 
2221 /* Check for OpenSSL 1.0.2 which has ALPN support. */
2222 #undef HAS_ALPN
2223 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
2224     && !defined(OPENSSL_NO_TLSEXT)
2225 #  define HAS_ALPN 1
2226 #endif
2227 
2228 /* Check for OpenSSL 1.0.1 which has NPN support. */
2229 #undef HAS_NPN
2230 #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
2231     && !defined(OPENSSL_NO_TLSEXT) \
2232     && !defined(OPENSSL_NO_NEXTPROTONEG)
2233 #  define HAS_NPN 1
2234 #endif
2235 
2236 #ifdef HAS_NPN
2237 
2238 /*
2239  * in is a list of length prefixed strings. this function has to select
2240  * the protocol we want to use from the list and write its string into out.
2241  */
2242 
2243 static int
select_next_protocol(unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,const char * key,unsigned int keylen)2244 select_next_protocol(unsigned char **out, unsigned char *outlen,
2245                      const unsigned char *in, unsigned int inlen,
2246                      const char *key, unsigned int keylen)
2247 {
2248   unsigned int i;
2249   for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
2250     if(memcmp(&in[i + 1], key, keylen) == 0) {
2251       *out = (unsigned char *) &in[i + 1];
2252       *outlen = in[i];
2253       return 0;
2254     }
2255   }
2256   return -1;
2257 }
2258 
2259 static int
select_next_proto_cb(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)2260 select_next_proto_cb(SSL *ssl,
2261                      unsigned char **out, unsigned char *outlen,
2262                      const unsigned char *in, unsigned int inlen,
2263                      void *arg)
2264 {
2265   struct Curl_easy *data = (struct Curl_easy *)arg;
2266   struct connectdata *conn = data->conn;
2267   (void)ssl;
2268 
2269 #ifdef USE_HTTP2
2270   if(data->state.httpwant >= CURL_HTTP_VERSION_2 &&
2271      !select_next_protocol(out, outlen, in, inlen, ALPN_H2, ALPN_H2_LENGTH)) {
2272     infof(data, "NPN, negotiated HTTP2 (%s)", ALPN_H2);
2273     conn->negnpn = CURL_HTTP_VERSION_2;
2274     return SSL_TLSEXT_ERR_OK;
2275   }
2276 #endif
2277 
2278   if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
2279                            ALPN_HTTP_1_1_LENGTH)) {
2280     infof(data, "NPN, negotiated HTTP1.1");
2281     conn->negnpn = CURL_HTTP_VERSION_1_1;
2282     return SSL_TLSEXT_ERR_OK;
2283   }
2284 
2285   infof(data, "NPN, no overlap, use HTTP1.1");
2286   *out = (unsigned char *)ALPN_HTTP_1_1;
2287   *outlen = ALPN_HTTP_1_1_LENGTH;
2288   conn->negnpn = CURL_HTTP_VERSION_1_1;
2289 
2290   return SSL_TLSEXT_ERR_OK;
2291 }
2292 #endif /* HAS_NPN */
2293 
2294 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
2295 static CURLcode
set_ssl_version_min_max(SSL_CTX * ctx,struct connectdata * conn)2296 set_ssl_version_min_max(SSL_CTX *ctx, struct connectdata *conn)
2297 {
2298   /* first, TLS min version... */
2299   long curl_ssl_version_min = SSL_CONN_CONFIG(version);
2300   long curl_ssl_version_max;
2301 
2302   /* convert cURL min SSL version option to OpenSSL constant */
2303 #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
2304   uint16_t ossl_ssl_version_min = 0;
2305   uint16_t ossl_ssl_version_max = 0;
2306 #else
2307   long ossl_ssl_version_min = 0;
2308   long ossl_ssl_version_max = 0;
2309 #endif
2310   switch(curl_ssl_version_min) {
2311     case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
2312     case CURL_SSLVERSION_TLSv1_0:
2313       ossl_ssl_version_min = TLS1_VERSION;
2314       break;
2315     case CURL_SSLVERSION_TLSv1_1:
2316       ossl_ssl_version_min = TLS1_1_VERSION;
2317       break;
2318     case CURL_SSLVERSION_TLSv1_2:
2319       ossl_ssl_version_min = TLS1_2_VERSION;
2320       break;
2321 #ifdef TLS1_3_VERSION
2322     case CURL_SSLVERSION_TLSv1_3:
2323       ossl_ssl_version_min = TLS1_3_VERSION;
2324       break;
2325 #endif
2326   }
2327 
2328   /* CURL_SSLVERSION_DEFAULT means that no option was selected.
2329      We don't want to pass 0 to SSL_CTX_set_min_proto_version as
2330      it would enable all versions down to the lowest supported by
2331      the library.
2332      So we skip this, and stay with the OS default
2333   */
2334   if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
2335     if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
2336       return CURLE_SSL_CONNECT_ERROR;
2337     }
2338   }
2339 
2340   /* ... then, TLS max version */
2341   curl_ssl_version_max = SSL_CONN_CONFIG(version_max);
2342 
2343   /* convert cURL max SSL version option to OpenSSL constant */
2344   switch(curl_ssl_version_max) {
2345     case CURL_SSLVERSION_MAX_TLSv1_0:
2346       ossl_ssl_version_max = TLS1_VERSION;
2347       break;
2348     case CURL_SSLVERSION_MAX_TLSv1_1:
2349       ossl_ssl_version_max = TLS1_1_VERSION;
2350       break;
2351     case CURL_SSLVERSION_MAX_TLSv1_2:
2352       ossl_ssl_version_max = TLS1_2_VERSION;
2353       break;
2354 #ifdef TLS1_3_VERSION
2355     case CURL_SSLVERSION_MAX_TLSv1_3:
2356       ossl_ssl_version_max = TLS1_3_VERSION;
2357       break;
2358 #endif
2359     case CURL_SSLVERSION_MAX_NONE:  /* none selected */
2360     case CURL_SSLVERSION_MAX_DEFAULT:  /* max selected */
2361     default:
2362       /* SSL_CTX_set_max_proto_version states that:
2363         setting the maximum to 0 will enable
2364         protocol versions up to the highest version
2365         supported by the library */
2366       ossl_ssl_version_max = 0;
2367       break;
2368   }
2369 
2370   if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
2371     return CURLE_SSL_CONNECT_ERROR;
2372   }
2373 
2374   return CURLE_OK;
2375 }
2376 #endif
2377 
2378 #ifdef OPENSSL_IS_BORINGSSL
2379 typedef uint32_t ctx_option_t;
2380 #else
2381 typedef long ctx_option_t;
2382 #endif
2383 
2384 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */
2385 static CURLcode
set_ssl_version_min_max_legacy(ctx_option_t * ctx_options,struct Curl_easy * data,struct connectdata * conn,int sockindex)2386 set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
2387                                struct Curl_easy *data,
2388                                struct connectdata *conn, int sockindex)
2389 {
2390   long ssl_version = SSL_CONN_CONFIG(version);
2391   long ssl_version_max = SSL_CONN_CONFIG(version_max);
2392 
2393   (void) data; /* In case it's unused. */
2394 
2395   switch(ssl_version) {
2396     case CURL_SSLVERSION_TLSv1_3:
2397 #ifdef TLS1_3_VERSION
2398     {
2399       struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2400       SSL_CTX_set_max_proto_version(backend->ctx, TLS1_3_VERSION);
2401       *ctx_options |= SSL_OP_NO_TLSv1_2;
2402     }
2403 #else
2404       (void)sockindex;
2405       (void)ctx_options;
2406       failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2407       return CURLE_NOT_BUILT_IN;
2408 #endif
2409       /* FALLTHROUGH */
2410     case CURL_SSLVERSION_TLSv1_2:
2411 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2412       *ctx_options |= SSL_OP_NO_TLSv1_1;
2413 #else
2414       failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
2415       return CURLE_NOT_BUILT_IN;
2416 #endif
2417       /* FALLTHROUGH */
2418     case CURL_SSLVERSION_TLSv1_1:
2419 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2420       *ctx_options |= SSL_OP_NO_TLSv1;
2421 #else
2422       failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
2423       return CURLE_NOT_BUILT_IN;
2424 #endif
2425       /* FALLTHROUGH */
2426     case CURL_SSLVERSION_TLSv1_0:
2427     case CURL_SSLVERSION_TLSv1:
2428       break;
2429   }
2430 
2431   switch(ssl_version_max) {
2432     case CURL_SSLVERSION_MAX_TLSv1_0:
2433 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2434       *ctx_options |= SSL_OP_NO_TLSv1_1;
2435 #endif
2436       /* FALLTHROUGH */
2437     case CURL_SSLVERSION_MAX_TLSv1_1:
2438 #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
2439       *ctx_options |= SSL_OP_NO_TLSv1_2;
2440 #endif
2441       /* FALLTHROUGH */
2442     case CURL_SSLVERSION_MAX_TLSv1_2:
2443 #ifdef TLS1_3_VERSION
2444       *ctx_options |= SSL_OP_NO_TLSv1_3;
2445 #endif
2446       break;
2447     case CURL_SSLVERSION_MAX_TLSv1_3:
2448 #ifdef TLS1_3_VERSION
2449       break;
2450 #else
2451       failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2452       return CURLE_NOT_BUILT_IN;
2453 #endif
2454   }
2455   return CURLE_OK;
2456 }
2457 #endif
2458 
2459 /* The "new session" callback must return zero if the session can be removed
2460  * or non-zero if the session has been put into the session cache.
2461  */
ossl_new_session_cb(SSL * ssl,SSL_SESSION * ssl_sessionid)2462 static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
2463 {
2464   int res = 0;
2465   struct connectdata *conn;
2466   struct Curl_easy *data;
2467   int sockindex;
2468   curl_socket_t *sockindex_ptr;
2469   int data_idx = ossl_get_ssl_data_index();
2470   int connectdata_idx = ossl_get_ssl_conn_index();
2471   int sockindex_idx = ossl_get_ssl_sockindex_index();
2472   int proxy_idx = ossl_get_proxy_index();
2473   bool isproxy;
2474 
2475   if(data_idx < 0 || connectdata_idx < 0 || sockindex_idx < 0 || proxy_idx < 0)
2476     return 0;
2477 
2478   conn = (struct connectdata*) SSL_get_ex_data(ssl, connectdata_idx);
2479   if(!conn)
2480     return 0;
2481 
2482   data = (struct Curl_easy *) SSL_get_ex_data(ssl, data_idx);
2483 
2484   /* The sockindex has been stored as a pointer to an array element */
2485   sockindex_ptr = (curl_socket_t*) SSL_get_ex_data(ssl, sockindex_idx);
2486   sockindex = (int)(sockindex_ptr - conn->sock);
2487 
2488   isproxy = SSL_get_ex_data(ssl, proxy_idx) ? TRUE : FALSE;
2489 
2490   if(SSL_SET_OPTION(primary.sessionid)) {
2491     bool incache;
2492     void *old_ssl_sessionid = NULL;
2493 
2494     Curl_ssl_sessionid_lock(data);
2495     if(isproxy)
2496       incache = FALSE;
2497     else
2498       incache = !(Curl_ssl_getsessionid(data, conn, isproxy,
2499                                         &old_ssl_sessionid, NULL, sockindex));
2500     if(incache) {
2501       if(old_ssl_sessionid != ssl_sessionid) {
2502         infof(data, "old SSL session ID is stale, removing");
2503         Curl_ssl_delsessionid(data, old_ssl_sessionid);
2504         incache = FALSE;
2505       }
2506     }
2507 
2508     if(!incache) {
2509       if(!Curl_ssl_addsessionid(data, conn, isproxy, ssl_sessionid,
2510                                 0 /* unknown size */, sockindex)) {
2511         /* the session has been put into the session cache */
2512         res = 1;
2513       }
2514       else
2515         failf(data, "failed to store ssl session");
2516     }
2517     Curl_ssl_sessionid_unlock(data);
2518   }
2519 
2520   return res;
2521 }
2522 
load_cacert_from_memory(SSL_CTX * ctx,const struct curl_blob * ca_info_blob)2523 static CURLcode load_cacert_from_memory(SSL_CTX *ctx,
2524                                         const struct curl_blob *ca_info_blob)
2525 {
2526   /* these need freed at the end */
2527   BIO *cbio = NULL;
2528   STACK_OF(X509_INFO) *inf = NULL;
2529 
2530   /* everything else is just a reference */
2531   int i, count = 0;
2532   X509_STORE *cts = NULL;
2533   X509_INFO *itmp = NULL;
2534 
2535   if(ca_info_blob->len > (size_t)INT_MAX)
2536     return CURLE_SSL_CACERT_BADFILE;
2537 
2538   cts = SSL_CTX_get_cert_store(ctx);
2539   if(!cts)
2540     return CURLE_OUT_OF_MEMORY;
2541 
2542   cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
2543   if(!cbio)
2544     return CURLE_OUT_OF_MEMORY;
2545 
2546   inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
2547   if(!inf) {
2548     BIO_free(cbio);
2549     return CURLE_SSL_CACERT_BADFILE;
2550   }
2551 
2552   /* add each entry from PEM file to x509_store */
2553   for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
2554     itmp = sk_X509_INFO_value(inf, i);
2555     if(itmp->x509) {
2556       if(X509_STORE_add_cert(cts, itmp->x509)) {
2557         ++count;
2558       }
2559       else {
2560         /* set count to 0 to return an error */
2561         count = 0;
2562         break;
2563       }
2564     }
2565     if(itmp->crl) {
2566       if(X509_STORE_add_crl(cts, itmp->crl)) {
2567         ++count;
2568       }
2569       else {
2570         /* set count to 0 to return an error */
2571         count = 0;
2572         break;
2573       }
2574     }
2575   }
2576 
2577   sk_X509_INFO_pop_free(inf, X509_INFO_free);
2578   BIO_free(cbio);
2579 
2580   /* if we didn't end up importing anything, treat that as an error */
2581   return (count > 0 ? CURLE_OK : CURLE_SSL_CACERT_BADFILE);
2582 }
2583 
ossl_connect_step1(struct Curl_easy * data,struct connectdata * conn,int sockindex)2584 static CURLcode ossl_connect_step1(struct Curl_easy *data,
2585                                    struct connectdata *conn, int sockindex)
2586 {
2587   CURLcode result = CURLE_OK;
2588   char *ciphers;
2589   SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
2590   X509_LOOKUP *lookup = NULL;
2591   curl_socket_t sockfd = conn->sock[sockindex];
2592   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2593   ctx_option_t ctx_options = 0;
2594   void *ssl_sessionid = NULL;
2595 
2596 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2597   bool sni;
2598   const char * const hostname = SSL_HOST_NAME();
2599 
2600 #ifdef ENABLE_IPV6
2601   struct in6_addr addr;
2602 #else
2603   struct in_addr addr;
2604 #endif
2605 #endif
2606   const long int ssl_version = SSL_CONN_CONFIG(version);
2607 #ifdef USE_OPENSSL_SRP
2608   const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(primary.authtype);
2609 #endif
2610   char * const ssl_cert = SSL_SET_OPTION(primary.clientcert);
2611   const struct curl_blob *ssl_cert_blob = SSL_SET_OPTION(primary.cert_blob);
2612   const struct curl_blob *ca_info_blob = SSL_CONN_CONFIG(ca_info_blob);
2613   const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
2614   const char * const ssl_cafile =
2615     /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
2616     (ca_info_blob ? NULL : SSL_CONN_CONFIG(CAfile));
2617   const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
2618   const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
2619   const char * const ssl_crlfile = SSL_SET_OPTION(primary.CRLfile);
2620   char error_buffer[256];
2621   struct ssl_backend_data *backend = connssl->backend;
2622   bool imported_native_ca = false;
2623 
2624   DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
2625 
2626   /* Make funny stuff to get random input */
2627   result = ossl_seed(data);
2628   if(result)
2629     return result;
2630 
2631   SSL_SET_OPTION_LVALUE(certverifyresult) = !X509_V_OK;
2632 
2633   /* check to see if we've been told to use an explicit SSL/TLS version */
2634 
2635   switch(ssl_version) {
2636   case CURL_SSLVERSION_DEFAULT:
2637   case CURL_SSLVERSION_TLSv1:
2638   case CURL_SSLVERSION_TLSv1_0:
2639   case CURL_SSLVERSION_TLSv1_1:
2640   case CURL_SSLVERSION_TLSv1_2:
2641   case CURL_SSLVERSION_TLSv1_3:
2642     /* it will be handled later with the context options */
2643 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
2644     req_method = TLS_client_method();
2645 #else
2646     req_method = SSLv23_client_method();
2647 #endif
2648     use_sni(TRUE);
2649     break;
2650   case CURL_SSLVERSION_SSLv2:
2651     failf(data, "No SSLv2 support");
2652     return CURLE_NOT_BUILT_IN;
2653   case CURL_SSLVERSION_SSLv3:
2654     failf(data, "No SSLv3 support");
2655     return CURLE_NOT_BUILT_IN;
2656   default:
2657     failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2658     return CURLE_SSL_CONNECT_ERROR;
2659   }
2660 
2661   if(backend->ctx)
2662     SSL_CTX_free(backend->ctx);
2663   backend->ctx = SSL_CTX_new(req_method);
2664 
2665   if(!backend->ctx) {
2666     failf(data, "SSL: couldn't create a context: %s",
2667           ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
2668     return CURLE_OUT_OF_MEMORY;
2669   }
2670 
2671 #ifdef SSL_MODE_RELEASE_BUFFERS
2672   SSL_CTX_set_mode(backend->ctx, SSL_MODE_RELEASE_BUFFERS);
2673 #endif
2674 
2675 #ifdef SSL_CTRL_SET_MSG_CALLBACK
2676   if(data->set.fdebug && data->set.verbose) {
2677     /* the SSL trace callback is only used for verbose logging */
2678     SSL_CTX_set_msg_callback(backend->ctx, ossl_trace);
2679     SSL_CTX_set_msg_callback_arg(backend->ctx, conn);
2680     set_logger(conn, data);
2681   }
2682 #endif
2683 
2684   /* OpenSSL contains code to work-around lots of bugs and flaws in various
2685      SSL-implementations. SSL_CTX_set_options() is used to enabled those
2686      work-arounds. The man page for this option states that SSL_OP_ALL enables
2687      all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
2688      enable the bug workaround options if compatibility with somewhat broken
2689      implementations is desired."
2690 
2691      The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
2692      disable "rfc4507bis session ticket support".  rfc4507bis was later turned
2693      into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
2694 
2695      The enabled extension concerns the session management. I wonder how often
2696      libcurl stops a connection and then resumes a TLS session. also, sending
2697      the session data is some overhead. .I suggest that you just use your
2698      proposed patch (which explicitly disables TICKET).
2699 
2700      If someone writes an application with libcurl and openssl who wants to
2701      enable the feature, one can do this in the SSL callback.
2702 
2703      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
2704      interoperability with web server Netscape Enterprise Server 2.0.1 which
2705      was released back in 1996.
2706 
2707      Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
2708      become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
2709      CVE-2010-4180 when using previous OpenSSL versions we no longer enable
2710      this option regardless of OpenSSL version and SSL_OP_ALL definition.
2711 
2712      OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
2713      (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
2714      SSL_OP_ALL that _disables_ that work-around despite the fact that
2715      SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
2716      keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
2717      must not be set.
2718   */
2719 
2720   ctx_options = SSL_OP_ALL;
2721 
2722 #ifdef SSL_OP_NO_TICKET
2723   ctx_options |= SSL_OP_NO_TICKET;
2724 #endif
2725 
2726 #ifdef SSL_OP_NO_COMPRESSION
2727   ctx_options |= SSL_OP_NO_COMPRESSION;
2728 #endif
2729 
2730 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2731   /* mitigate CVE-2010-4180 */
2732   ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
2733 #endif
2734 
2735 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2736   /* unless the user explicitly ask to allow the protocol vulnerability we
2737      use the work-around */
2738   if(!SSL_SET_OPTION(enable_beast))
2739     ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2740 #endif
2741 
2742   switch(ssl_version) {
2743     case CURL_SSLVERSION_SSLv2:
2744     case CURL_SSLVERSION_SSLv3:
2745       return CURLE_NOT_BUILT_IN;
2746 
2747     /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
2748     case CURL_SSLVERSION_DEFAULT:
2749     case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
2750     case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
2751     case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
2752     case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
2753     case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
2754       /* asking for any TLS version as the minimum, means no SSL versions
2755         allowed */
2756       ctx_options |= SSL_OP_NO_SSLv2;
2757       ctx_options |= SSL_OP_NO_SSLv3;
2758 
2759 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
2760       result = set_ssl_version_min_max(backend->ctx, conn);
2761 #else
2762       result = set_ssl_version_min_max_legacy(&ctx_options, data, conn,
2763                                               sockindex);
2764 #endif
2765       if(result != CURLE_OK)
2766         return result;
2767       break;
2768 
2769     default:
2770       failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
2771       return CURLE_SSL_CONNECT_ERROR;
2772   }
2773 
2774   SSL_CTX_set_options(backend->ctx, ctx_options);
2775 
2776 #ifdef HAS_NPN
2777   if(conn->bits.tls_enable_npn)
2778     SSL_CTX_set_next_proto_select_cb(backend->ctx, select_next_proto_cb, data);
2779 #endif
2780 
2781 #ifdef HAS_ALPN
2782   if(conn->bits.tls_enable_alpn) {
2783     int cur = 0;
2784     unsigned char protocols[128];
2785 
2786 #ifdef USE_HTTP2
2787     if(data->state.httpwant >= CURL_HTTP_VERSION_2
2788 #ifndef CURL_DISABLE_PROXY
2789        && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)
2790 #endif
2791       ) {
2792       protocols[cur++] = ALPN_H2_LENGTH;
2793 
2794       memcpy(&protocols[cur], ALPN_H2, ALPN_H2_LENGTH);
2795       cur += ALPN_H2_LENGTH;
2796       infof(data, "ALPN, offering %s", ALPN_H2);
2797     }
2798 #endif
2799 
2800     protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2801     memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2802     cur += ALPN_HTTP_1_1_LENGTH;
2803     infof(data, "ALPN, offering %s", ALPN_HTTP_1_1);
2804 
2805     /* expects length prefixed preference ordered list of protocols in wire
2806      * format
2807      */
2808     if(SSL_CTX_set_alpn_protos(backend->ctx, protocols, cur)) {
2809       failf(data, "Error setting ALPN");
2810       return CURLE_SSL_CONNECT_ERROR;
2811     }
2812   }
2813 #endif
2814 
2815   if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
2816     if(!result &&
2817        !cert_stuff(data, backend->ctx,
2818                    ssl_cert, ssl_cert_blob, ssl_cert_type,
2819                    SSL_SET_OPTION(key), SSL_SET_OPTION(key_blob),
2820                    SSL_SET_OPTION(key_type), SSL_SET_OPTION(key_passwd)))
2821       result = CURLE_SSL_CERTPROBLEM;
2822     if(result)
2823       /* failf() is already done in cert_stuff() */
2824       return result;
2825   }
2826 
2827   ciphers = SSL_CONN_CONFIG(cipher_list);
2828   if(!ciphers)
2829     ciphers = (char *)DEFAULT_CIPHER_SELECTION;
2830   if(ciphers) {
2831     if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {
2832       failf(data, "failed setting cipher list: %s", ciphers);
2833       return CURLE_SSL_CIPHER;
2834     }
2835     infof(data, "Cipher selection: %s", ciphers);
2836   }
2837 
2838 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
2839   {
2840     char *ciphers13 = SSL_CONN_CONFIG(cipher_list13);
2841     if(ciphers13) {
2842       if(!SSL_CTX_set_ciphersuites(backend->ctx, ciphers13)) {
2843         failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
2844         return CURLE_SSL_CIPHER;
2845       }
2846       infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
2847     }
2848   }
2849 #endif
2850 
2851 #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
2852   /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
2853   SSL_CTX_set_post_handshake_auth(backend->ctx, 1);
2854 #endif
2855 
2856 #ifdef HAVE_SSL_CTX_SET_EC_CURVES
2857   {
2858     char *curves = SSL_CONN_CONFIG(curves);
2859     if(curves) {
2860       if(!SSL_CTX_set1_curves_list(backend->ctx, curves)) {
2861         failf(data, "failed setting curves list: '%s'", curves);
2862         return CURLE_SSL_CIPHER;
2863       }
2864     }
2865   }
2866 #endif
2867 
2868 #ifdef USE_OPENSSL_SRP
2869   if((ssl_authtype == CURL_TLSAUTH_SRP) &&
2870      Curl_allow_auth_to_host(data)) {
2871     char * const ssl_username = SSL_SET_OPTION(primary.username);
2872     char * const ssl_password = SSL_SET_OPTION(primary.password);
2873     infof(data, "Using TLS-SRP username: %s", ssl_username);
2874 
2875     if(!SSL_CTX_set_srp_username(backend->ctx, ssl_username)) {
2876       failf(data, "Unable to set SRP user name");
2877       return CURLE_BAD_FUNCTION_ARGUMENT;
2878     }
2879     if(!SSL_CTX_set_srp_password(backend->ctx, ssl_password)) {
2880       failf(data, "failed setting SRP password");
2881       return CURLE_BAD_FUNCTION_ARGUMENT;
2882     }
2883     if(!SSL_CONN_CONFIG(cipher_list)) {
2884       infof(data, "Setting cipher list SRP");
2885 
2886       if(!SSL_CTX_set_cipher_list(backend->ctx, "SRP")) {
2887         failf(data, "failed setting SRP cipher list");
2888         return CURLE_SSL_CIPHER;
2889       }
2890     }
2891   }
2892 #endif
2893 
2894 
2895 #if defined(USE_WIN32_CRYPTO)
2896   /* Import certificates from the Windows root certificate store if requested.
2897      https://stackoverflow.com/questions/9507184/
2898      https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
2899      https://tools.ietf.org/html/rfc5280 */
2900   if((SSL_CONN_CONFIG(verifypeer) || SSL_CONN_CONFIG(verifyhost)) &&
2901      (SSL_SET_OPTION(native_ca_store))) {
2902     X509_STORE *store = SSL_CTX_get_cert_store(backend->ctx);
2903     HCERTSTORE hStore = CertOpenSystemStore(0, TEXT("ROOT"));
2904 
2905     if(hStore) {
2906       PCCERT_CONTEXT pContext = NULL;
2907       /* The array of enhanced key usage OIDs will vary per certificate and is
2908          declared outside of the loop so that rather than malloc/free each
2909          iteration we can grow it with realloc, when necessary. */
2910       CERT_ENHKEY_USAGE *enhkey_usage = NULL;
2911       DWORD enhkey_usage_size = 0;
2912 
2913       /* This loop makes a best effort to import all valid certificates from
2914          the MS root store. If a certificate cannot be imported it is skipped.
2915          'result' is used to store only hard-fail conditions (such as out of
2916          memory) that cause an early break. */
2917       result = CURLE_OK;
2918       for(;;) {
2919         X509 *x509;
2920         FILETIME now;
2921         BYTE key_usage[2];
2922         DWORD req_size;
2923         const unsigned char *encoded_cert;
2924 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
2925         char cert_name[256];
2926 #endif
2927 
2928         pContext = CertEnumCertificatesInStore(hStore, pContext);
2929         if(!pContext)
2930           break;
2931 
2932 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
2933         if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
2934                                NULL, cert_name, sizeof(cert_name))) {
2935           strcpy(cert_name, "Unknown");
2936         }
2937         infof(data, "SSL: Checking cert %s\"\n", cert_name);
2938 #endif
2939 
2940         encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
2941         if(!encoded_cert)
2942           continue;
2943 
2944         GetSystemTimeAsFileTime(&now);
2945         if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
2946            CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
2947           continue;
2948 
2949         /* If key usage exists check for signing attribute */
2950         if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
2951                                    pContext->pCertInfo,
2952                                    key_usage, sizeof(key_usage))) {
2953           if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
2954             continue;
2955         }
2956         else if(GetLastError())
2957           continue;
2958 
2959         /* If enhanced key usage exists check for server auth attribute.
2960          *
2961          * Note "In a Microsoft environment, a certificate might also have EKU
2962          * extended properties that specify valid uses for the certificate."
2963          * The call below checks both, and behavior varies depending on what is
2964          * found. For more details see CertGetEnhancedKeyUsage doc.
2965          */
2966         if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
2967           if(req_size && req_size > enhkey_usage_size) {
2968             void *tmp = realloc(enhkey_usage, req_size);
2969 
2970             if(!tmp) {
2971               failf(data, "SSL: Out of memory allocating for OID list");
2972               result = CURLE_OUT_OF_MEMORY;
2973               break;
2974             }
2975 
2976             enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
2977             enhkey_usage_size = req_size;
2978           }
2979 
2980           if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
2981             if(!enhkey_usage->cUsageIdentifier) {
2982               /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate is
2983                  good for all uses. If it returns zero, the certificate has no
2984                  valid uses." */
2985               if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
2986                 continue;
2987             }
2988             else {
2989               DWORD i;
2990               bool found = false;
2991 
2992               for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
2993                 if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
2994                            enhkey_usage->rgpszUsageIdentifier[i])) {
2995                   found = true;
2996                   break;
2997                 }
2998               }
2999 
3000               if(!found)
3001                 continue;
3002             }
3003           }
3004           else
3005             continue;
3006         }
3007         else
3008           continue;
3009 
3010         x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
3011         if(!x509)
3012           continue;
3013 
3014         /* Try to import the certificate. This may fail for legitimate reasons
3015            such as duplicate certificate, which is allowed by MS but not
3016            OpenSSL. */
3017         if(X509_STORE_add_cert(store, x509) == 1) {
3018 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
3019           infof(data, "SSL: Imported cert \"%s\"", cert_name);
3020 #endif
3021           imported_native_ca = true;
3022         }
3023         X509_free(x509);
3024       }
3025 
3026       free(enhkey_usage);
3027       CertFreeCertificateContext(pContext);
3028       CertCloseStore(hStore, 0);
3029 
3030       if(result)
3031         return result;
3032     }
3033     if(imported_native_ca)
3034       infof(data, "successfully imported windows ca store");
3035     else
3036       infof(data, "error importing windows ca store, continuing anyway");
3037   }
3038 #endif
3039 
3040   if(ca_info_blob) {
3041     result = load_cacert_from_memory(backend->ctx, ca_info_blob);
3042     if(result) {
3043       if(result == CURLE_OUT_OF_MEMORY ||
3044          (verifypeer && !imported_native_ca)) {
3045         failf(data, "error importing CA certificate blob");
3046         return result;
3047       }
3048       /* Only warning if no certificate verification is required. */
3049       infof(data, "error importing CA certificate blob, continuing anyway");
3050     }
3051   }
3052 
3053 #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
3054   /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
3055   {
3056     if(ssl_cafile) {
3057       if(!SSL_CTX_load_verify_file(backend->ctx, ssl_cafile)) {
3058         if(verifypeer && !imported_native_ca) {
3059           /* Fail if we insist on successfully verifying the server. */
3060           failf(data, "error setting certificate file: %s", ssl_cafile);
3061           return CURLE_SSL_CACERT_BADFILE;
3062         }
3063         /* Continue with a warning if no certificate verif is required. */
3064         infof(data, "error setting certificate file, continuing anyway");
3065       }
3066       infof(data, " CAfile: %s", ssl_cafile);
3067     }
3068     if(ssl_capath) {
3069       if(!SSL_CTX_load_verify_dir(backend->ctx, ssl_capath)) {
3070         if(verifypeer && !imported_native_ca) {
3071           /* Fail if we insist on successfully verifying the server. */
3072           failf(data, "error setting certificate path: %s", ssl_capath);
3073           return CURLE_SSL_CACERT_BADFILE;
3074         }
3075         /* Continue with a warning if no certificate verif is required. */
3076         infof(data, "error setting certificate path, continuing anyway");
3077       }
3078       infof(data, " CApath: %s", ssl_capath);
3079     }
3080   }
3081 #else
3082   if(ssl_cafile || ssl_capath) {
3083     /* tell SSL where to find CA certificates that are used to verify
3084        the servers certificate. */
3085     if(!SSL_CTX_load_verify_locations(backend->ctx, ssl_cafile, ssl_capath)) {
3086       if(verifypeer && !imported_native_ca) {
3087         /* Fail if we insist on successfully verifying the server. */
3088         failf(data, "error setting certificate verify locations:"
3089               "  CAfile: %s CApath: %s",
3090               ssl_cafile ? ssl_cafile : "none",
3091               ssl_capath ? ssl_capath : "none");
3092         return CURLE_SSL_CACERT_BADFILE;
3093       }
3094       /* Just continue with a warning if no strict certificate verification
3095          is required. */
3096       infof(data, "error setting certificate verify locations,"
3097             " continuing anyway:");
3098     }
3099     else {
3100       /* Everything is fine. */
3101       infof(data, "successfully set certificate verify locations:");
3102     }
3103     infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
3104     infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
3105   }
3106 #endif
3107 
3108 #ifdef CURL_CA_FALLBACK
3109   if(verifypeer &&
3110      !ca_info_blob && !ssl_cafile && !ssl_capath && !imported_native_ca) {
3111     /* verifying the peer without any CA certificates won't
3112        work so use openssl's built in default as fallback */
3113     SSL_CTX_set_default_verify_paths(backend->ctx);
3114   }
3115 #endif
3116 
3117   if(ssl_crlfile) {
3118     /* tell SSL where to find CRL file that is used to check certificate
3119      * revocation */
3120     lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(backend->ctx),
3121                                  X509_LOOKUP_file());
3122     if(!lookup ||
3123        (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
3124       failf(data, "error loading CRL file: %s", ssl_crlfile);
3125       return CURLE_SSL_CRL_BADFILE;
3126     }
3127     /* Everything is fine. */
3128     infof(data, "successfully load CRL file:");
3129     X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
3130                          X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3131 
3132     infof(data, "  CRLfile: %s", ssl_crlfile);
3133   }
3134 
3135   if(verifypeer) {
3136     /* Try building a chain using issuers in the trusted store first to avoid
3137        problems with server-sent legacy intermediates.  Newer versions of
3138        OpenSSL do alternate chain checking by default but we do not know how to
3139        determine that in a reliable manner.
3140        https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
3141     */
3142 #if defined(X509_V_FLAG_TRUSTED_FIRST)
3143     X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
3144                          X509_V_FLAG_TRUSTED_FIRST);
3145 #endif
3146 #ifdef X509_V_FLAG_PARTIAL_CHAIN
3147     if(!SSL_SET_OPTION(no_partialchain) && !ssl_crlfile) {
3148       /* Have intermediate certificates in the trust store be treated as
3149          trust-anchors, in the same way as self-signed root CA certificates
3150          are. This allows users to verify servers using the intermediate cert
3151          only, instead of needing the whole chain.
3152 
3153          Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
3154          cannot do partial chains with CRL check.
3155       */
3156       X509_STORE_set_flags(SSL_CTX_get_cert_store(backend->ctx),
3157                            X509_V_FLAG_PARTIAL_CHAIN);
3158     }
3159 #endif
3160   }
3161 
3162   /* SSL always tries to verify the peer, this only says whether it should
3163    * fail to connect if the verification fails, or if it should continue
3164    * anyway. In the latter case the result of the verification is checked with
3165    * SSL_get_verify_result() below. */
3166   SSL_CTX_set_verify(backend->ctx,
3167                      verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
3168 
3169   /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
3170 #ifdef HAVE_KEYLOG_CALLBACK
3171   if(Curl_tls_keylog_enabled()) {
3172     SSL_CTX_set_keylog_callback(backend->ctx, ossl_keylog_callback);
3173   }
3174 #endif
3175 
3176   /* Enable the session cache because it's a prerequisite for the "new session"
3177    * callback. Use the "external storage" mode to avoid that OpenSSL creates
3178    * an internal session cache.
3179    */
3180   SSL_CTX_set_session_cache_mode(backend->ctx,
3181       SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
3182   SSL_CTX_sess_set_new_cb(backend->ctx, ossl_new_session_cb);
3183 
3184   /* give application a chance to interfere with SSL set up. */
3185   if(data->set.ssl.fsslctx) {
3186     Curl_set_in_callback(data, true);
3187     result = (*data->set.ssl.fsslctx)(data, backend->ctx,
3188                                       data->set.ssl.fsslctxp);
3189     Curl_set_in_callback(data, false);
3190     if(result) {
3191       failf(data, "error signaled by ssl ctx callback");
3192       return result;
3193     }
3194   }
3195 
3196   /* Lets make an SSL structure */
3197   if(backend->handle)
3198     SSL_free(backend->handle);
3199   backend->handle = SSL_new(backend->ctx);
3200   if(!backend->handle) {
3201     failf(data, "SSL: couldn't create a context (handle)!");
3202     return CURLE_OUT_OF_MEMORY;
3203   }
3204 
3205 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3206     !defined(OPENSSL_NO_OCSP)
3207   if(SSL_CONN_CONFIG(verifystatus))
3208     SSL_set_tlsext_status_type(backend->handle, TLSEXT_STATUSTYPE_ocsp);
3209 #endif
3210 
3211 #if defined(OPENSSL_IS_BORINGSSL) && defined(ALLOW_RENEG)
3212   SSL_set_renegotiate_mode(backend->handle, ssl_renegotiate_freely);
3213 #endif
3214 
3215   SSL_set_connect_state(backend->handle);
3216 
3217   backend->server_cert = 0x0;
3218 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3219   if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
3220 #ifdef ENABLE_IPV6
3221      (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
3222 #endif
3223      sni) {
3224     size_t nlen = strlen(hostname);
3225     if((long)nlen >= data->set.buffer_size)
3226       /* this is seriously messed up */
3227       return CURLE_SSL_CONNECT_ERROR;
3228 
3229     /* RFC 6066 section 3 says the SNI field is case insensitive, but browsers
3230        send the data lowercase and subsequently there are now numerous servers
3231        out there that don't work unless the name is lowercased */
3232     Curl_strntolower(data->state.buffer, hostname, nlen);
3233     data->state.buffer[nlen] = 0;
3234     if(!SSL_set_tlsext_host_name(backend->handle, data->state.buffer))
3235       infof(data, "WARNING: failed to configure server name indication (SNI) "
3236             "TLS extension");
3237   }
3238 #endif
3239 
3240   ossl_associate_connection(data, conn, sockindex);
3241 
3242   Curl_ssl_sessionid_lock(data);
3243   if(!Curl_ssl_getsessionid(data, conn, SSL_IS_PROXY() ? TRUE : FALSE,
3244                             &ssl_sessionid, NULL, sockindex)) {
3245     /* we got a session id, use it! */
3246     if(!SSL_set_session(backend->handle, ssl_sessionid)) {
3247       Curl_ssl_sessionid_unlock(data);
3248       failf(data, "SSL: SSL_set_session failed: %s",
3249             ossl_strerror(ERR_get_error(), error_buffer,
3250                           sizeof(error_buffer)));
3251       return CURLE_SSL_CONNECT_ERROR;
3252     }
3253     /* Informational message */
3254     infof(data, "SSL re-using session ID");
3255   }
3256   Curl_ssl_sessionid_unlock(data);
3257 
3258 #ifndef CURL_DISABLE_PROXY
3259   if(conn->proxy_ssl[sockindex].use) {
3260     BIO *const bio = BIO_new(BIO_f_ssl());
3261     SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
3262     DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
3263     DEBUGASSERT(handle != NULL);
3264     DEBUGASSERT(bio != NULL);
3265     BIO_set_ssl(bio, handle, FALSE);
3266     SSL_set_bio(backend->handle, bio, bio);
3267   }
3268   else
3269 #endif
3270     if(!SSL_set_fd(backend->handle, (int)sockfd)) {
3271     /* pass the raw socket into the SSL layers */
3272     failf(data, "SSL: SSL_set_fd failed: %s",
3273           ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
3274     return CURLE_SSL_CONNECT_ERROR;
3275   }
3276 
3277   connssl->connecting_state = ssl_connect_2;
3278 
3279   return CURLE_OK;
3280 }
3281 
ossl_connect_step2(struct Curl_easy * data,struct connectdata * conn,int sockindex)3282 static CURLcode ossl_connect_step2(struct Curl_easy *data,
3283                                    struct connectdata *conn, int sockindex)
3284 {
3285   int err;
3286   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
3287   struct ssl_backend_data *backend = connssl->backend;
3288   DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
3289               || ssl_connect_2_reading == connssl->connecting_state
3290               || ssl_connect_2_writing == connssl->connecting_state);
3291 
3292   ERR_clear_error();
3293 
3294   err = SSL_connect(backend->handle);
3295 #ifndef HAVE_KEYLOG_CALLBACK
3296   if(Curl_tls_keylog_enabled()) {
3297     /* If key logging is enabled, wait for the handshake to complete and then
3298      * proceed with logging secrets (for TLS 1.2 or older).
3299      */
3300     ossl_log_tls12_secret(backend->handle, &backend->keylog_done);
3301   }
3302 #endif
3303 
3304   /* 1  is fine
3305      0  is "not successful but was shut down controlled"
3306      <0 is "handshake was not successful, because a fatal error occurred" */
3307   if(1 != err) {
3308     int detail = SSL_get_error(backend->handle, err);
3309 
3310     if(SSL_ERROR_WANT_READ == detail) {
3311       connssl->connecting_state = ssl_connect_2_reading;
3312       return CURLE_OK;
3313     }
3314     if(SSL_ERROR_WANT_WRITE == detail) {
3315       connssl->connecting_state = ssl_connect_2_writing;
3316       return CURLE_OK;
3317     }
3318 #ifdef SSL_ERROR_WANT_ASYNC
3319     if(SSL_ERROR_WANT_ASYNC == detail) {
3320       connssl->connecting_state = ssl_connect_2;
3321       return CURLE_OK;
3322     }
3323 #endif
3324     else {
3325       /* untreated error */
3326       unsigned long errdetail;
3327       char error_buffer[256]="";
3328       CURLcode result;
3329       long lerr;
3330       int lib;
3331       int reason;
3332 
3333       /* the connection failed, we're not waiting for anything else. */
3334       connssl->connecting_state = ssl_connect_2;
3335 
3336       /* Get the earliest error code from the thread's error queue and removes
3337          the entry. */
3338       errdetail = ERR_get_error();
3339 
3340       /* Extract which lib and reason */
3341       lib = ERR_GET_LIB(errdetail);
3342       reason = ERR_GET_REASON(errdetail);
3343 
3344       if((lib == ERR_LIB_SSL) &&
3345          ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
3346           (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
3347         result = CURLE_PEER_FAILED_VERIFICATION;
3348 
3349         lerr = SSL_get_verify_result(backend->handle);
3350         if(lerr != X509_V_OK) {
3351           SSL_SET_OPTION_LVALUE(certverifyresult) = lerr;
3352           msnprintf(error_buffer, sizeof(error_buffer),
3353                     "SSL certificate problem: %s",
3354                     X509_verify_cert_error_string(lerr));
3355         }
3356         else
3357           /* strcpy() is fine here as long as the string fits within
3358              error_buffer */
3359           strcpy(error_buffer, "SSL certificate verification failed");
3360       }
3361 #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
3362     !defined(LIBRESSL_VERSION_NUMBER) && \
3363     !defined(OPENSSL_IS_BORINGSSL))
3364       /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
3365          OpenSSL version above v1.1.1, not Libre SSL nor BoringSSL */
3366       else if((lib == ERR_LIB_SSL) &&
3367               (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
3368           /* If client certificate is required, communicate the
3369              error to client */
3370           result = CURLE_SSL_CLIENTCERT;
3371           ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
3372       }
3373 #endif
3374       else {
3375         result = CURLE_SSL_CONNECT_ERROR;
3376         ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
3377       }
3378 
3379       /* detail is already set to the SSL error above */
3380 
3381       /* If we e.g. use SSLv2 request-method and the server doesn't like us
3382        * (RST connection etc.), OpenSSL gives no explanation whatsoever and
3383        * the SO_ERROR is also lost.
3384        */
3385       if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
3386         const char * const hostname = SSL_HOST_NAME();
3387         const long int port = SSL_HOST_PORT();
3388         char extramsg[80]="";
3389         int sockerr = SOCKERRNO;
3390         if(sockerr && detail == SSL_ERROR_SYSCALL)
3391           Curl_strerror(sockerr, extramsg, sizeof(extramsg));
3392         failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
3393               extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
3394               hostname, port);
3395         return result;
3396       }
3397 
3398       /* Could be a CERT problem */
3399       failf(data, "%s", error_buffer);
3400 
3401       return result;
3402     }
3403   }
3404   else {
3405     /* we have been connected fine, we're not waiting for anything else. */
3406     connssl->connecting_state = ssl_connect_3;
3407 
3408     /* Informational message */
3409     infof(data, "SSL connection using %s / %s",
3410           SSL_get_version(backend->handle),
3411           SSL_get_cipher(backend->handle));
3412 
3413 #ifdef HAS_ALPN
3414     /* Sets data and len to negotiated protocol, len is 0 if no protocol was
3415      * negotiated
3416      */
3417     if(conn->bits.tls_enable_alpn) {
3418       const unsigned char *neg_protocol;
3419       unsigned int len;
3420       SSL_get0_alpn_selected(backend->handle, &neg_protocol, &len);
3421       if(len) {
3422         infof(data, "ALPN, server accepted to use %.*s", len, neg_protocol);
3423 
3424 #ifdef USE_HTTP2
3425         if(len == ALPN_H2_LENGTH &&
3426            !memcmp(ALPN_H2, neg_protocol, len)) {
3427           conn->negnpn = CURL_HTTP_VERSION_2;
3428         }
3429         else
3430 #endif
3431         if(len == ALPN_HTTP_1_1_LENGTH &&
3432            !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
3433           conn->negnpn = CURL_HTTP_VERSION_1_1;
3434         }
3435       }
3436       else
3437         infof(data, "ALPN, server did not agree to a protocol");
3438 
3439       Curl_multiuse_state(data, conn->negnpn == CURL_HTTP_VERSION_2 ?
3440                           BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
3441     }
3442 #endif
3443 
3444     return CURLE_OK;
3445   }
3446 }
3447 
asn1_object_dump(ASN1_OBJECT * a,char * buf,size_t len)3448 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
3449 {
3450   int i, ilen;
3451 
3452   ilen = (int)len;
3453   if(ilen < 0)
3454     return 1; /* buffer too big */
3455 
3456   i = i2t_ASN1_OBJECT(buf, ilen, a);
3457 
3458   if(i >= ilen)
3459     return 1; /* buffer too small */
3460 
3461   return 0;
3462 }
3463 
3464 #define push_certinfo(_label, _num) \
3465 do {                              \
3466   long info_len = BIO_get_mem_data(mem, &ptr); \
3467   Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
3468   if(1 != BIO_reset(mem))                                        \
3469     break;                                                       \
3470 } while(0)
3471 
pubkey_show(struct Curl_easy * data,BIO * mem,int num,const char * type,const char * name,const BIGNUM * bn)3472 static void pubkey_show(struct Curl_easy *data,
3473                         BIO *mem,
3474                         int num,
3475                         const char *type,
3476                         const char *name,
3477 #ifdef HAVE_OPAQUE_RSA_DSA_DH
3478                         const
3479 #endif
3480                         BIGNUM *bn)
3481 {
3482   char *ptr;
3483   char namebuf[32];
3484 
3485   msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
3486 
3487   if(bn)
3488     BN_print(mem, bn);
3489   push_certinfo(namebuf, num);
3490 }
3491 
3492 #ifdef HAVE_OPAQUE_RSA_DSA_DH
3493 #define print_pubkey_BN(_type, _name, _num)              \
3494   pubkey_show(data, mem, _num, #_type, #_name, _name)
3495 
3496 #else
3497 #define print_pubkey_BN(_type, _name, _num)    \
3498 do {                              \
3499   if(_type->_name) { \
3500     pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
3501   } \
3502 } while(0)
3503 #endif
3504 
X509V3_ext(struct Curl_easy * data,int certnum,CONST_EXTS STACK_OF (X509_EXTENSION)* exts)3505 static void X509V3_ext(struct Curl_easy *data,
3506                       int certnum,
3507                       CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
3508 {
3509   int i;
3510 
3511   if((int)sk_X509_EXTENSION_num(exts) <= 0)
3512     /* no extensions, bail out */
3513     return;
3514 
3515   for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
3516     ASN1_OBJECT *obj;
3517     X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
3518     BUF_MEM *biomem;
3519     char namebuf[128];
3520     BIO *bio_out = BIO_new(BIO_s_mem());
3521 
3522     if(!bio_out)
3523       return;
3524 
3525     obj = X509_EXTENSION_get_object(ext);
3526 
3527     asn1_object_dump(obj, namebuf, sizeof(namebuf));
3528 
3529     if(!X509V3_EXT_print(bio_out, ext, 0, 0))
3530       ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
3531 
3532     BIO_get_mem_ptr(bio_out, &biomem);
3533     Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
3534                                biomem->length);
3535     BIO_free(bio_out);
3536   }
3537 }
3538 
3539 #ifdef OPENSSL_IS_BORINGSSL
3540 typedef size_t numcert_t;
3541 #else
3542 typedef int numcert_t;
3543 #endif
3544 
3545 #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
3546 #define OSSL3_CONST const
3547 #else
3548 #define OSSL3_CONST
3549 #endif
3550 
get_cert_chain(struct Curl_easy * data,struct ssl_connect_data * connssl)3551 static CURLcode get_cert_chain(struct Curl_easy *data,
3552                                struct ssl_connect_data *connssl)
3553 {
3554   CURLcode result;
3555   STACK_OF(X509) *sk;
3556   int i;
3557   numcert_t numcerts;
3558   BIO *mem;
3559   struct ssl_backend_data *backend = connssl->backend;
3560 
3561   sk = SSL_get_peer_cert_chain(backend->handle);
3562   if(!sk) {
3563     return CURLE_OUT_OF_MEMORY;
3564   }
3565 
3566   numcerts = sk_X509_num(sk);
3567 
3568   result = Curl_ssl_init_certinfo(data, (int)numcerts);
3569   if(result) {
3570     return result;
3571   }
3572 
3573   mem = BIO_new(BIO_s_mem());
3574 
3575   for(i = 0; i < (int)numcerts; i++) {
3576     ASN1_INTEGER *num;
3577     X509 *x = sk_X509_value(sk, i);
3578     EVP_PKEY *pubkey = NULL;
3579     int j;
3580     char *ptr;
3581     const ASN1_BIT_STRING *psig = NULL;
3582 
3583     X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
3584     push_certinfo("Subject", i);
3585 
3586     X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
3587     push_certinfo("Issuer", i);
3588 
3589     BIO_printf(mem, "%lx", X509_get_version(x));
3590     push_certinfo("Version", i);
3591 
3592     num = X509_get_serialNumber(x);
3593     if(num->type == V_ASN1_NEG_INTEGER)
3594       BIO_puts(mem, "-");
3595     for(j = 0; j < num->length; j++)
3596       BIO_printf(mem, "%02x", num->data[j]);
3597     push_certinfo("Serial Number", i);
3598 
3599 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
3600     {
3601       const X509_ALGOR *sigalg = NULL;
3602       X509_PUBKEY *xpubkey = NULL;
3603       ASN1_OBJECT *pubkeyoid = NULL;
3604 
3605       X509_get0_signature(&psig, &sigalg, x);
3606       if(sigalg) {
3607         i2a_ASN1_OBJECT(mem, sigalg->algorithm);
3608         push_certinfo("Signature Algorithm", i);
3609       }
3610 
3611       xpubkey = X509_get_X509_PUBKEY(x);
3612       if(xpubkey) {
3613         X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
3614         if(pubkeyoid) {
3615           i2a_ASN1_OBJECT(mem, pubkeyoid);
3616           push_certinfo("Public Key Algorithm", i);
3617         }
3618       }
3619 
3620       X509V3_ext(data, i, X509_get0_extensions(x));
3621     }
3622 #else
3623     {
3624       /* before OpenSSL 1.0.2 */
3625       X509_CINF *cinf = x->cert_info;
3626 
3627       i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
3628       push_certinfo("Signature Algorithm", i);
3629 
3630       i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
3631       push_certinfo("Public Key Algorithm", i);
3632 
3633       X509V3_ext(data, i, cinf->extensions);
3634 
3635       psig = x->signature;
3636     }
3637 #endif
3638 
3639     ASN1_TIME_print(mem, X509_get0_notBefore(x));
3640     push_certinfo("Start date", i);
3641 
3642     ASN1_TIME_print(mem, X509_get0_notAfter(x));
3643     push_certinfo("Expire date", i);
3644 
3645     pubkey = X509_get_pubkey(x);
3646     if(!pubkey)
3647       infof(data, "   Unable to load public key");
3648     else {
3649       int pktype;
3650 #ifdef HAVE_OPAQUE_EVP_PKEY
3651       pktype = EVP_PKEY_id(pubkey);
3652 #else
3653       pktype = pubkey->type;
3654 #endif
3655       switch(pktype) {
3656       case EVP_PKEY_RSA:
3657       {
3658         OSSL3_CONST RSA *rsa;
3659 #ifdef HAVE_OPAQUE_EVP_PKEY
3660         rsa = EVP_PKEY_get0_RSA(pubkey);
3661 #else
3662         rsa = pubkey->pkey.rsa;
3663 #endif
3664 
3665 #ifdef HAVE_OPAQUE_RSA_DSA_DH
3666         {
3667           const BIGNUM *n;
3668           const BIGNUM *e;
3669 
3670           RSA_get0_key(rsa, &n, &e, NULL);
3671           BIO_printf(mem, "%d", BN_num_bits(n));
3672           push_certinfo("RSA Public Key", i);
3673           print_pubkey_BN(rsa, n, i);
3674           print_pubkey_BN(rsa, e, i);
3675         }
3676 #else
3677         BIO_printf(mem, "%d", BN_num_bits(rsa->n));
3678         push_certinfo("RSA Public Key", i);
3679         print_pubkey_BN(rsa, n, i);
3680         print_pubkey_BN(rsa, e, i);
3681 #endif
3682 
3683         break;
3684       }
3685       case EVP_PKEY_DSA:
3686       {
3687 #ifndef OPENSSL_NO_DSA
3688         OSSL3_CONST DSA *dsa;
3689 #ifdef HAVE_OPAQUE_EVP_PKEY
3690         dsa = EVP_PKEY_get0_DSA(pubkey);
3691 #else
3692         dsa = pubkey->pkey.dsa;
3693 #endif
3694 #ifdef HAVE_OPAQUE_RSA_DSA_DH
3695         {
3696           const BIGNUM *p;
3697           const BIGNUM *q;
3698           const BIGNUM *g;
3699           const BIGNUM *pub_key;
3700 
3701           DSA_get0_pqg(dsa, &p, &q, &g);
3702           DSA_get0_key(dsa, &pub_key, NULL);
3703 
3704           print_pubkey_BN(dsa, p, i);
3705           print_pubkey_BN(dsa, q, i);
3706           print_pubkey_BN(dsa, g, i);
3707           print_pubkey_BN(dsa, pub_key, i);
3708         }
3709 #else
3710         print_pubkey_BN(dsa, p, i);
3711         print_pubkey_BN(dsa, q, i);
3712         print_pubkey_BN(dsa, g, i);
3713         print_pubkey_BN(dsa, pub_key, i);
3714 #endif
3715 #endif /* !OPENSSL_NO_DSA */
3716         break;
3717       }
3718       case EVP_PKEY_DH:
3719       {
3720         OSSL3_CONST DH *dh;
3721 #ifdef HAVE_OPAQUE_EVP_PKEY
3722         dh = EVP_PKEY_get0_DH(pubkey);
3723 #else
3724         dh = pubkey->pkey.dh;
3725 #endif
3726 #ifdef HAVE_OPAQUE_RSA_DSA_DH
3727         {
3728           const BIGNUM *p;
3729           const BIGNUM *q;
3730           const BIGNUM *g;
3731           const BIGNUM *pub_key;
3732           DH_get0_pqg(dh, &p, &q, &g);
3733           DH_get0_key(dh, &pub_key, NULL);
3734           print_pubkey_BN(dh, p, i);
3735           print_pubkey_BN(dh, q, i);
3736           print_pubkey_BN(dh, g, i);
3737           print_pubkey_BN(dh, pub_key, i);
3738        }
3739 #else
3740         print_pubkey_BN(dh, p, i);
3741         print_pubkey_BN(dh, g, i);
3742         print_pubkey_BN(dh, pub_key, i);
3743 #endif
3744         break;
3745       }
3746       }
3747       EVP_PKEY_free(pubkey);
3748     }
3749 
3750     if(psig) {
3751       for(j = 0; j < psig->length; j++)
3752         BIO_printf(mem, "%02x:", psig->data[j]);
3753       push_certinfo("Signature", i);
3754     }
3755 
3756     PEM_write_bio_X509(mem, x);
3757     push_certinfo("Cert", i);
3758   }
3759 
3760   BIO_free(mem);
3761 
3762   return CURLE_OK;
3763 }
3764 
3765 /*
3766  * Heavily modified from:
3767  * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
3768  */
pkp_pin_peer_pubkey(struct Curl_easy * data,X509 * cert,const char * pinnedpubkey)3769 static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
3770                                     const char *pinnedpubkey)
3771 {
3772   /* Scratch */
3773   int len1 = 0, len2 = 0;
3774   unsigned char *buff1 = NULL, *temp = NULL;
3775 
3776   /* Result is returned to caller */
3777   CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
3778 
3779   /* if a path wasn't specified, don't pin */
3780   if(!pinnedpubkey)
3781     return CURLE_OK;
3782 
3783   if(!cert)
3784     return result;
3785 
3786   do {
3787     /* Begin Gyrations to get the subjectPublicKeyInfo     */
3788     /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
3789 
3790     /* https://groups.google.com/group/mailing.openssl.users/browse_thread
3791      /thread/d61858dae102c6c7 */
3792     len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
3793     if(len1 < 1)
3794       break; /* failed */
3795 
3796     buff1 = temp = malloc(len1);
3797     if(!buff1)
3798       break; /* failed */
3799 
3800     /* https://www.openssl.org/docs/crypto/d2i_X509.html */
3801     len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
3802 
3803     /*
3804      * These checks are verifying we got back the same values as when we
3805      * sized the buffer. It's pretty weak since they should always be the
3806      * same. But it gives us something to test.
3807      */
3808     if((len1 != len2) || !temp || ((temp - buff1) != len1))
3809       break; /* failed */
3810 
3811     /* End Gyrations */
3812 
3813     /* The one good exit point */
3814     result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
3815   } while(0);
3816 
3817   if(buff1)
3818     free(buff1);
3819 
3820   return result;
3821 }
3822 
3823 /*
3824  * Get the server cert, verify it and show it etc, only call failf() if the
3825  * 'strict' argument is TRUE as otherwise all this is for informational
3826  * purposes only!
3827  *
3828  * We check certificates to authenticate the server; otherwise we risk
3829  * man-in-the-middle attack.
3830  */
servercert(struct Curl_easy * data,struct connectdata * conn,struct ssl_connect_data * connssl,bool strict)3831 static CURLcode servercert(struct Curl_easy *data,
3832                            struct connectdata *conn,
3833                            struct ssl_connect_data *connssl,
3834                            bool strict)
3835 {
3836   CURLcode result = CURLE_OK;
3837   int rc;
3838   long lerr;
3839   X509 *issuer;
3840   BIO *fp = NULL;
3841   char error_buffer[256]="";
3842   char buffer[2048];
3843   const char *ptr;
3844   BIO *mem = BIO_new(BIO_s_mem());
3845   struct ssl_backend_data *backend = connssl->backend;
3846 
3847   if(data->set.ssl.certinfo)
3848     /* we've been asked to gather certificate info! */
3849     (void)get_cert_chain(data, connssl);
3850 
3851   backend->server_cert = SSL_get_peer_certificate(backend->handle);
3852   if(!backend->server_cert) {
3853     BIO_free(mem);
3854     if(!strict)
3855       return CURLE_OK;
3856 
3857     failf(data, "SSL: couldn't get peer certificate!");
3858     return CURLE_PEER_FAILED_VERIFICATION;
3859   }
3860 
3861   infof(data, "%s certificate:", SSL_IS_PROXY() ? "Proxy" : "Server");
3862 
3863   rc = x509_name_oneline(X509_get_subject_name(backend->server_cert),
3864                          buffer, sizeof(buffer));
3865   infof(data, " subject: %s", rc?"[NONE]":buffer);
3866 
3867 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3868   {
3869     long len;
3870     ASN1_TIME_print(mem, X509_get0_notBefore(backend->server_cert));
3871     len = BIO_get_mem_data(mem, (char **) &ptr);
3872     infof(data, " start date: %.*s", (int)len, ptr);
3873     (void)BIO_reset(mem);
3874 
3875     ASN1_TIME_print(mem, X509_get0_notAfter(backend->server_cert));
3876     len = BIO_get_mem_data(mem, (char **) &ptr);
3877     infof(data, " expire date: %.*s", (int)len, ptr);
3878     (void)BIO_reset(mem);
3879   }
3880 #endif
3881 
3882   BIO_free(mem);
3883 
3884   if(SSL_CONN_CONFIG(verifyhost)) {
3885     result = verifyhost(data, conn, backend->server_cert);
3886     if(result) {
3887       X509_free(backend->server_cert);
3888       backend->server_cert = NULL;
3889       return result;
3890     }
3891   }
3892 
3893   rc = x509_name_oneline(X509_get_issuer_name(backend->server_cert),
3894                          buffer, sizeof(buffer));
3895   if(rc) {
3896     if(strict)
3897       failf(data, "SSL: couldn't get X509-issuer name!");
3898     result = CURLE_PEER_FAILED_VERIFICATION;
3899   }
3900   else {
3901     infof(data, " issuer: %s", buffer);
3902 
3903     /* We could do all sorts of certificate verification stuff here before
3904        deallocating the certificate. */
3905 
3906     /* e.g. match issuer name with provided issuer certificate */
3907     if(SSL_CONN_CONFIG(issuercert) || SSL_CONN_CONFIG(issuercert_blob)) {
3908       if(SSL_CONN_CONFIG(issuercert_blob))
3909         fp = BIO_new_mem_buf(SSL_CONN_CONFIG(issuercert_blob)->data,
3910                              (int)SSL_CONN_CONFIG(issuercert_blob)->len);
3911       else {
3912         fp = BIO_new(BIO_s_file());
3913         if(!fp) {
3914           failf(data,
3915                 "BIO_new return NULL, " OSSL_PACKAGE
3916                 " error %s",
3917                 ossl_strerror(ERR_get_error(), error_buffer,
3918                               sizeof(error_buffer)) );
3919           X509_free(backend->server_cert);
3920           backend->server_cert = NULL;
3921           return CURLE_OUT_OF_MEMORY;
3922         }
3923 
3924         if(BIO_read_filename(fp, SSL_CONN_CONFIG(issuercert)) <= 0) {
3925           if(strict)
3926             failf(data, "SSL: Unable to open issuer cert (%s)",
3927                   SSL_CONN_CONFIG(issuercert));
3928           BIO_free(fp);
3929           X509_free(backend->server_cert);
3930           backend->server_cert = NULL;
3931           return CURLE_SSL_ISSUER_ERROR;
3932         }
3933       }
3934 
3935       issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
3936       if(!issuer) {
3937         if(strict)
3938           failf(data, "SSL: Unable to read issuer cert (%s)",
3939                 SSL_CONN_CONFIG(issuercert));
3940         BIO_free(fp);
3941         X509_free(issuer);
3942         X509_free(backend->server_cert);
3943         backend->server_cert = NULL;
3944         return CURLE_SSL_ISSUER_ERROR;
3945       }
3946 
3947       if(X509_check_issued(issuer, backend->server_cert) != X509_V_OK) {
3948         if(strict)
3949           failf(data, "SSL: Certificate issuer check failed (%s)",
3950                 SSL_CONN_CONFIG(issuercert));
3951         BIO_free(fp);
3952         X509_free(issuer);
3953         X509_free(backend->server_cert);
3954         backend->server_cert = NULL;
3955         return CURLE_SSL_ISSUER_ERROR;
3956       }
3957 
3958       infof(data, " SSL certificate issuer check ok (%s)",
3959             SSL_CONN_CONFIG(issuercert));
3960       BIO_free(fp);
3961       X509_free(issuer);
3962     }
3963 
3964     lerr = SSL_get_verify_result(backend->handle);
3965     SSL_SET_OPTION_LVALUE(certverifyresult) = lerr;
3966     if(lerr != X509_V_OK) {
3967       if(SSL_CONN_CONFIG(verifypeer)) {
3968         /* We probably never reach this, because SSL_connect() will fail
3969            and we return earlier if verifypeer is set? */
3970         if(strict)
3971           failf(data, "SSL certificate verify result: %s (%ld)",
3972                 X509_verify_cert_error_string(lerr), lerr);
3973         result = CURLE_PEER_FAILED_VERIFICATION;
3974       }
3975       else
3976         infof(data, " SSL certificate verify result: %s (%ld),"
3977               " continuing anyway.",
3978               X509_verify_cert_error_string(lerr), lerr);
3979     }
3980     else
3981       infof(data, " SSL certificate verify ok.");
3982   }
3983 
3984 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
3985     !defined(OPENSSL_NO_OCSP)
3986   if(SSL_CONN_CONFIG(verifystatus)) {
3987     result = verifystatus(data, connssl);
3988     if(result) {
3989       X509_free(backend->server_cert);
3990       backend->server_cert = NULL;
3991       return result;
3992     }
3993   }
3994 #endif
3995 
3996   if(!strict)
3997     /* when not strict, we don't bother about the verify cert problems */
3998     result = CURLE_OK;
3999 
4000   ptr = SSL_PINNED_PUB_KEY();
4001   if(!result && ptr) {
4002     result = pkp_pin_peer_pubkey(data, backend->server_cert, ptr);
4003     if(result)
4004       failf(data, "SSL: public key does not match pinned public key!");
4005   }
4006 
4007   X509_free(backend->server_cert);
4008   backend->server_cert = NULL;
4009   connssl->connecting_state = ssl_connect_done;
4010 
4011   return result;
4012 }
4013 
ossl_connect_step3(struct Curl_easy * data,struct connectdata * conn,int sockindex)4014 static CURLcode ossl_connect_step3(struct Curl_easy *data,
4015                                    struct connectdata *conn, int sockindex)
4016 {
4017   CURLcode result = CURLE_OK;
4018   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
4019 
4020   DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
4021 
4022   /*
4023    * We check certificates to authenticate the server; otherwise we risk
4024    * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
4025    * verify the peer ignore faults and failures from the server cert
4026    * operations.
4027    */
4028 
4029   result = servercert(data, conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
4030                                             SSL_CONN_CONFIG(verifyhost)));
4031 
4032   if(!result)
4033     connssl->connecting_state = ssl_connect_done;
4034 
4035   return result;
4036 }
4037 
4038 static Curl_recv ossl_recv;
4039 static Curl_send ossl_send;
4040 
ossl_connect_common(struct Curl_easy * data,struct connectdata * conn,int sockindex,bool nonblocking,bool * done)4041 static CURLcode ossl_connect_common(struct Curl_easy *data,
4042                                     struct connectdata *conn,
4043                                     int sockindex,
4044                                     bool nonblocking,
4045                                     bool *done)
4046 {
4047   CURLcode result;
4048   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
4049   curl_socket_t sockfd = conn->sock[sockindex];
4050   int what;
4051 
4052   /* check if the connection has already been established */
4053   if(ssl_connection_complete == connssl->state) {
4054     *done = TRUE;
4055     return CURLE_OK;
4056   }
4057 
4058   if(ssl_connect_1 == connssl->connecting_state) {
4059     /* Find out how much more time we're allowed */
4060     const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
4061 
4062     if(timeout_ms < 0) {
4063       /* no need to continue if time already is up */
4064       failf(data, "SSL connection timeout");
4065       return CURLE_OPERATION_TIMEDOUT;
4066     }
4067 
4068     result = ossl_connect_step1(data, conn, sockindex);
4069     if(result)
4070       return result;
4071   }
4072 
4073   while(ssl_connect_2 == connssl->connecting_state ||
4074         ssl_connect_2_reading == connssl->connecting_state ||
4075         ssl_connect_2_writing == connssl->connecting_state) {
4076 
4077     /* check allowed time left */
4078     const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
4079 
4080     if(timeout_ms < 0) {
4081       /* no need to continue if time already is up */
4082       failf(data, "SSL connection timeout");
4083       return CURLE_OPERATION_TIMEDOUT;
4084     }
4085 
4086     /* if ssl is expecting something, check if it's available. */
4087     if(connssl->connecting_state == ssl_connect_2_reading ||
4088        connssl->connecting_state == ssl_connect_2_writing) {
4089 
4090       curl_socket_t writefd = ssl_connect_2_writing ==
4091         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
4092       curl_socket_t readfd = ssl_connect_2_reading ==
4093         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
4094 
4095       what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
4096                                nonblocking?0:timeout_ms);
4097       if(what < 0) {
4098         /* fatal error */
4099         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
4100         return CURLE_SSL_CONNECT_ERROR;
4101       }
4102       if(0 == what) {
4103         if(nonblocking) {
4104           *done = FALSE;
4105           return CURLE_OK;
4106         }
4107         /* timeout */
4108         failf(data, "SSL connection timeout");
4109         return CURLE_OPERATION_TIMEDOUT;
4110       }
4111       /* socket is readable or writable */
4112     }
4113 
4114     /* Run transaction, and return to the caller if it failed or if this
4115      * connection is done nonblocking and this loop would execute again. This
4116      * permits the owner of a multi handle to abort a connection attempt
4117      * before step2 has completed while ensuring that a client using select()
4118      * or epoll() will always have a valid fdset to wait on.
4119      */
4120     result = ossl_connect_step2(data, conn, sockindex);
4121     if(result || (nonblocking &&
4122                   (ssl_connect_2 == connssl->connecting_state ||
4123                    ssl_connect_2_reading == connssl->connecting_state ||
4124                    ssl_connect_2_writing == connssl->connecting_state)))
4125       return result;
4126 
4127   } /* repeat step2 until all transactions are done. */
4128 
4129   if(ssl_connect_3 == connssl->connecting_state) {
4130     result = ossl_connect_step3(data, conn, sockindex);
4131     if(result)
4132       return result;
4133   }
4134 
4135   if(ssl_connect_done == connssl->connecting_state) {
4136     connssl->state = ssl_connection_complete;
4137     conn->recv[sockindex] = ossl_recv;
4138     conn->send[sockindex] = ossl_send;
4139     *done = TRUE;
4140   }
4141   else
4142     *done = FALSE;
4143 
4144   /* Reset our connect state machine */
4145   connssl->connecting_state = ssl_connect_1;
4146 
4147   return CURLE_OK;
4148 }
4149 
ossl_connect_nonblocking(struct Curl_easy * data,struct connectdata * conn,int sockindex,bool * done)4150 static CURLcode ossl_connect_nonblocking(struct Curl_easy *data,
4151                                          struct connectdata *conn,
4152                                          int sockindex,
4153                                          bool *done)
4154 {
4155   return ossl_connect_common(data, conn, sockindex, TRUE, done);
4156 }
4157 
ossl_connect(struct Curl_easy * data,struct connectdata * conn,int sockindex)4158 static CURLcode ossl_connect(struct Curl_easy *data, struct connectdata *conn,
4159                              int sockindex)
4160 {
4161   CURLcode result;
4162   bool done = FALSE;
4163 
4164   result = ossl_connect_common(data, conn, sockindex, FALSE, &done);
4165   if(result)
4166     return result;
4167 
4168   DEBUGASSERT(done);
4169 
4170   return CURLE_OK;
4171 }
4172 
ossl_data_pending(const struct connectdata * conn,int connindex)4173 static bool ossl_data_pending(const struct connectdata *conn,
4174                               int connindex)
4175 {
4176   const struct ssl_connect_data *connssl = &conn->ssl[connindex];
4177   if(connssl->backend->handle && SSL_pending(connssl->backend->handle))
4178     return TRUE;
4179 #ifndef CURL_DISABLE_PROXY
4180   {
4181     const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
4182     if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle))
4183       return TRUE;
4184   }
4185 #endif
4186   return FALSE;
4187 }
4188 
4189 static size_t ossl_version(char *buffer, size_t size);
4190 
ossl_send(struct Curl_easy * data,int sockindex,const void * mem,size_t len,CURLcode * curlcode)4191 static ssize_t ossl_send(struct Curl_easy *data,
4192                          int sockindex,
4193                          const void *mem,
4194                          size_t len,
4195                          CURLcode *curlcode)
4196 {
4197   /* SSL_write() is said to return 'int' while write() and send() returns
4198      'size_t' */
4199   int err;
4200   char error_buffer[256];
4201   unsigned long sslerror;
4202   int memlen;
4203   int rc;
4204   struct connectdata *conn = data->conn;
4205   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
4206   struct ssl_backend_data *backend = connssl->backend;
4207 
4208   ERR_clear_error();
4209 
4210   memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
4211   set_logger(conn, data);
4212   rc = SSL_write(backend->handle, mem, memlen);
4213 
4214   if(rc <= 0) {
4215     err = SSL_get_error(backend->handle, rc);
4216 
4217     switch(err) {
4218     case SSL_ERROR_WANT_READ:
4219     case SSL_ERROR_WANT_WRITE:
4220       /* The operation did not complete; the same TLS/SSL I/O function
4221          should be called again later. This is basically an EWOULDBLOCK
4222          equivalent. */
4223       *curlcode = CURLE_AGAIN;
4224       return -1;
4225     case SSL_ERROR_SYSCALL:
4226       {
4227         int sockerr = SOCKERRNO;
4228         sslerror = ERR_get_error();
4229         if(sslerror)
4230           ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
4231         else if(sockerr)
4232           Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
4233         else {
4234           strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
4235           error_buffer[sizeof(error_buffer) - 1] = '\0';
4236         }
4237         failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
4238               error_buffer, sockerr);
4239         *curlcode = CURLE_SEND_ERROR;
4240         return -1;
4241       }
4242     case SSL_ERROR_SSL:
4243       /*  A failure in the SSL library occurred, usually a protocol error.
4244           The OpenSSL error queue contains more information on the error. */
4245       sslerror = ERR_get_error();
4246       if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
4247          ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
4248          conn->ssl[sockindex].state == ssl_connection_complete
4249 #ifndef CURL_DISABLE_PROXY
4250          && conn->proxy_ssl[sockindex].state == ssl_connection_complete
4251 #endif
4252         ) {
4253         char ver[120];
4254         (void)ossl_version(ver, sizeof(ver));
4255         failf(data, "Error: %s does not support double SSL tunneling.", ver);
4256       }
4257       else
4258         failf(data, "SSL_write() error: %s",
4259               ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
4260       *curlcode = CURLE_SEND_ERROR;
4261       return -1;
4262     }
4263     /* a true error */
4264     failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
4265           SSL_ERROR_to_str(err), SOCKERRNO);
4266     *curlcode = CURLE_SEND_ERROR;
4267     return -1;
4268   }
4269   *curlcode = CURLE_OK;
4270   return (ssize_t)rc; /* number of bytes */
4271 }
4272 
ossl_recv(struct Curl_easy * data,int num,char * buf,size_t buffersize,CURLcode * curlcode)4273 static ssize_t ossl_recv(struct Curl_easy *data,   /* transfer */
4274                          int num,                  /* socketindex */
4275                          char *buf,                /* store read data here */
4276                          size_t buffersize,        /* max amount to read */
4277                          CURLcode *curlcode)
4278 {
4279   char error_buffer[256];
4280   unsigned long sslerror;
4281   ssize_t nread;
4282   int buffsize;
4283   struct connectdata *conn = data->conn;
4284   struct ssl_connect_data *connssl = &conn->ssl[num];
4285   struct ssl_backend_data *backend = connssl->backend;
4286 
4287   ERR_clear_error();
4288 
4289   buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
4290   set_logger(conn, data);
4291   nread = (ssize_t)SSL_read(backend->handle, buf, buffsize);
4292   if(nread <= 0) {
4293     /* failed SSL_read */
4294     int err = SSL_get_error(backend->handle, (int)nread);
4295 
4296     switch(err) {
4297     case SSL_ERROR_NONE: /* this is not an error */
4298       break;
4299     case SSL_ERROR_ZERO_RETURN: /* no more data */
4300       /* close_notify alert */
4301       if(num == FIRSTSOCKET)
4302         /* mark the connection for close if it is indeed the control
4303            connection */
4304         connclose(conn, "TLS close_notify");
4305       break;
4306     case SSL_ERROR_WANT_READ:
4307     case SSL_ERROR_WANT_WRITE:
4308       /* there's data pending, re-invoke SSL_read() */
4309       *curlcode = CURLE_AGAIN;
4310       return -1;
4311     default:
4312       /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
4313          value/errno" */
4314       /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
4315       sslerror = ERR_get_error();
4316       if((nread < 0) || sslerror) {
4317         /* If the return code was negative or there actually is an error in the
4318            queue */
4319         int sockerr = SOCKERRNO;
4320         if(sslerror)
4321           ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
4322         else if(sockerr && err == SSL_ERROR_SYSCALL)
4323           Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
4324         else {
4325           strncpy(error_buffer, SSL_ERROR_to_str(err), sizeof(error_buffer));
4326           error_buffer[sizeof(error_buffer) - 1] = '\0';
4327         }
4328         failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
4329               error_buffer, sockerr);
4330         *curlcode = CURLE_RECV_ERROR;
4331         return -1;
4332       }
4333       /* For debug builds be a little stricter and error on any
4334          SSL_ERROR_SYSCALL. For example a server may have closed the connection
4335          abruptly without a close_notify alert. For compatibility with older
4336          peers we don't do this by default. #4624
4337 
4338          We can use this to gauge how many users may be affected, and
4339          if it goes ok eventually transition to allow in dev and release with
4340          the newest OpenSSL: #if (OPENSSL_VERSION_NUMBER >= 0x10101000L) */
4341 #ifdef DEBUGBUILD
4342       if(err == SSL_ERROR_SYSCALL) {
4343         int sockerr = SOCKERRNO;
4344         if(sockerr)
4345           Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
4346         else {
4347           msnprintf(error_buffer, sizeof(error_buffer),
4348                     "Connection closed abruptly");
4349         }
4350         failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d"
4351               " (Fatal because this is a curl debug build)",
4352               error_buffer, sockerr);
4353         *curlcode = CURLE_RECV_ERROR;
4354         return -1;
4355       }
4356 #endif
4357     }
4358   }
4359   return nread;
4360 }
4361 
ossl_version(char * buffer,size_t size)4362 static size_t ossl_version(char *buffer, size_t size)
4363 {
4364 #ifdef LIBRESSL_VERSION_NUMBER
4365 #if LIBRESSL_VERSION_NUMBER < 0x2070100fL
4366   return msnprintf(buffer, size, "%s/%lx.%lx.%lx",
4367                    OSSL_PACKAGE,
4368                    (LIBRESSL_VERSION_NUMBER>>28)&0xf,
4369                    (LIBRESSL_VERSION_NUMBER>>20)&0xff,
4370                    (LIBRESSL_VERSION_NUMBER>>12)&0xff);
4371 #else /* OpenSSL_version() first appeared in LibreSSL 2.7.1 */
4372   char *p;
4373   int count;
4374   const char *ver = OpenSSL_version(OPENSSL_VERSION);
4375   const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
4376   if(Curl_strncasecompare(ver, expected, sizeof(expected) - 1)) {
4377     ver += sizeof(expected) - 1;
4378   }
4379   count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
4380   for(p = buffer; *p; ++p) {
4381     if(ISSPACE(*p))
4382       *p = '_';
4383   }
4384   return count;
4385 #endif
4386 #elif defined(OPENSSL_IS_BORINGSSL)
4387   return msnprintf(buffer, size, OSSL_PACKAGE);
4388 #elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING)
4389   return msnprintf(buffer, size, "%s/%s",
4390                    OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
4391 #else
4392   /* not LibreSSL, BoringSSL and not using OpenSSL_version */
4393 
4394   char sub[3];
4395   unsigned long ssleay_value;
4396   sub[2]='\0';
4397   sub[1]='\0';
4398   ssleay_value = OpenSSL_version_num();
4399   if(ssleay_value < 0x906000) {
4400     ssleay_value = SSLEAY_VERSION_NUMBER;
4401     sub[0]='\0';
4402   }
4403   else {
4404     if(ssleay_value&0xff0) {
4405       int minor_ver = (ssleay_value >> 4) & 0xff;
4406       if(minor_ver > 26) {
4407         /* handle extended version introduced for 0.9.8za */
4408         sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
4409         sub[0] = 'z';
4410       }
4411       else {
4412         sub[0] = (char) (minor_ver + 'a' - 1);
4413       }
4414     }
4415     else
4416       sub[0]='\0';
4417   }
4418 
4419   return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
4420 #ifdef OPENSSL_FIPS
4421                    "-fips"
4422 #endif
4423                    ,
4424                    OSSL_PACKAGE,
4425                    (ssleay_value>>28)&0xf,
4426                    (ssleay_value>>20)&0xff,
4427                    (ssleay_value>>12)&0xff,
4428                    sub);
4429 #endif /* OPENSSL_IS_BORINGSSL */
4430 }
4431 
4432 /* can be called with data == NULL */
ossl_random(struct Curl_easy * data,unsigned char * entropy,size_t length)4433 static CURLcode ossl_random(struct Curl_easy *data,
4434                             unsigned char *entropy, size_t length)
4435 {
4436   int rc;
4437   if(data) {
4438     if(ossl_seed(data)) /* Initiate the seed if not already done */
4439       return CURLE_FAILED_INIT; /* couldn't seed for some reason */
4440   }
4441   else {
4442     if(!rand_enough())
4443       return CURLE_FAILED_INIT;
4444   }
4445   /* RAND_bytes() returns 1 on success, 0 otherwise.  */
4446   rc = RAND_bytes(entropy, curlx_uztosi(length));
4447   return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
4448 }
4449 
4450 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
ossl_sha256sum(const unsigned char * tmp,size_t tmplen,unsigned char * sha256sum,size_t unused)4451 static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
4452                                size_t tmplen,
4453                                unsigned char *sha256sum /* output */,
4454                                size_t unused)
4455 {
4456   EVP_MD_CTX *mdctx;
4457   unsigned int len = 0;
4458   (void) unused;
4459 
4460   mdctx = EVP_MD_CTX_create();
4461   if(!mdctx)
4462     return CURLE_OUT_OF_MEMORY;
4463   EVP_DigestInit(mdctx, EVP_sha256());
4464   EVP_DigestUpdate(mdctx, tmp, tmplen);
4465   EVP_DigestFinal_ex(mdctx, sha256sum, &len);
4466   EVP_MD_CTX_destroy(mdctx);
4467   return CURLE_OK;
4468 }
4469 #endif
4470 
ossl_cert_status_request(void)4471 static bool ossl_cert_status_request(void)
4472 {
4473 #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
4474     !defined(OPENSSL_NO_OCSP)
4475   return TRUE;
4476 #else
4477   return FALSE;
4478 #endif
4479 }
4480 
ossl_get_internals(struct ssl_connect_data * connssl,CURLINFO info)4481 static void *ossl_get_internals(struct ssl_connect_data *connssl,
4482                                 CURLINFO info)
4483 {
4484   /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
4485   struct ssl_backend_data *backend = connssl->backend;
4486   return info == CURLINFO_TLS_SESSION ?
4487          (void *)backend->ctx : (void *)backend->handle;
4488 }
4489 
ossl_associate_connection(struct Curl_easy * data,struct connectdata * conn,int sockindex)4490 static void ossl_associate_connection(struct Curl_easy *data,
4491                                       struct connectdata *conn,
4492                                       int sockindex)
4493 {
4494   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
4495   struct ssl_backend_data *backend = connssl->backend;
4496 
4497   /* If we don't have SSL context, do nothing. */
4498   if(!backend->handle)
4499     return;
4500 
4501   if(SSL_SET_OPTION(primary.sessionid)) {
4502     int data_idx = ossl_get_ssl_data_index();
4503     int connectdata_idx = ossl_get_ssl_conn_index();
4504     int sockindex_idx = ossl_get_ssl_sockindex_index();
4505     int proxy_idx = ossl_get_proxy_index();
4506 
4507     if(data_idx >= 0 && connectdata_idx >= 0 && sockindex_idx >= 0 &&
4508        proxy_idx >= 0) {
4509       /* Store the data needed for the "new session" callback.
4510        * The sockindex is stored as a pointer to an array element. */
4511       SSL_set_ex_data(backend->handle, data_idx, data);
4512       SSL_set_ex_data(backend->handle, connectdata_idx, conn);
4513       SSL_set_ex_data(backend->handle, sockindex_idx, conn->sock + sockindex);
4514 #ifndef CURL_DISABLE_PROXY
4515       SSL_set_ex_data(backend->handle, proxy_idx, SSL_IS_PROXY() ? (void *) 1:
4516                       NULL);
4517 #else
4518       SSL_set_ex_data(backend->handle, proxy_idx, NULL);
4519 #endif
4520     }
4521   }
4522 }
4523 
4524 /*
4525  * Starting with TLS 1.3, the ossl_new_session_cb callback gets called after
4526  * the handshake. If the transfer that sets up the callback gets killed before
4527  * this callback arrives, we must make sure to properly clear the data to
4528  * avoid UAF problems. A future optimization could be to instead store another
4529  * transfer that might still be using the same connection.
4530  */
4531 
ossl_disassociate_connection(struct Curl_easy * data,int sockindex)4532 static void ossl_disassociate_connection(struct Curl_easy *data,
4533                                          int sockindex)
4534 {
4535   struct connectdata *conn = data->conn;
4536   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
4537   struct ssl_backend_data *backend = connssl->backend;
4538 
4539   /* If we don't have SSL context, do nothing. */
4540   if(!backend->handle)
4541     return;
4542 
4543   if(SSL_SET_OPTION(primary.sessionid)) {
4544     int data_idx = ossl_get_ssl_data_index();
4545     int connectdata_idx = ossl_get_ssl_conn_index();
4546     int sockindex_idx = ossl_get_ssl_sockindex_index();
4547     int proxy_idx = ossl_get_proxy_index();
4548 
4549     if(data_idx >= 0 && connectdata_idx >= 0 && sockindex_idx >= 0 &&
4550        proxy_idx >= 0) {
4551       /* Disable references to data in "new session" callback to avoid
4552        * accessing a stale pointer. */
4553       SSL_set_ex_data(backend->handle, data_idx, NULL);
4554       SSL_set_ex_data(backend->handle, connectdata_idx, NULL);
4555       SSL_set_ex_data(backend->handle, sockindex_idx, NULL);
4556       SSL_set_ex_data(backend->handle, proxy_idx, NULL);
4557     }
4558   }
4559 }
4560 
4561 const struct Curl_ssl Curl_ssl_openssl = {
4562   { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
4563 
4564   SSLSUPP_CA_PATH |
4565   SSLSUPP_CAINFO_BLOB |
4566   SSLSUPP_CERTINFO |
4567   SSLSUPP_PINNEDPUBKEY |
4568   SSLSUPP_SSL_CTX |
4569 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
4570   SSLSUPP_TLS13_CIPHERSUITES |
4571 #endif
4572   SSLSUPP_HTTPS_PROXY,
4573 
4574   sizeof(struct ssl_backend_data),
4575 
4576   ossl_init,                /* init */
4577   ossl_cleanup,             /* cleanup */
4578   ossl_version,             /* version */
4579   ossl_check_cxn,           /* check_cxn */
4580   ossl_shutdown,            /* shutdown */
4581   ossl_data_pending,        /* data_pending */
4582   ossl_random,              /* random */
4583   ossl_cert_status_request, /* cert_status_request */
4584   ossl_connect,             /* connect */
4585   ossl_connect_nonblocking, /* connect_nonblocking */
4586   Curl_ssl_getsock,         /* getsock */
4587   ossl_get_internals,       /* get_internals */
4588   ossl_close,               /* close_one */
4589   ossl_close_all,           /* close_all */
4590   ossl_session_free,        /* session_free */
4591   ossl_set_engine,          /* set_engine */
4592   ossl_set_engine_default,  /* set_engine_default */
4593   ossl_engines_list,        /* engines_list */
4594   Curl_none_false_start,    /* false_start */
4595 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
4596   ossl_sha256sum,           /* sha256sum */
4597 #else
4598   NULL,                     /* sha256sum */
4599 #endif
4600   ossl_associate_connection, /* associate_connection */
4601   ossl_disassociate_connection /* disassociate_connection */
4602 };
4603 
4604 #endif /* USE_OPENSSL */
4605