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