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