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