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