xref: /freebsd/crypto/openssl/crypto/provider_core.c (revision 88b8b7f0c4e9948667a2279e78e975a784049cba)
1 /*
2  * Copyright 2019-2025 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <assert.h>
11 #include <openssl/core.h>
12 #include <openssl/core_dispatch.h>
13 #include <openssl/core_names.h>
14 #include <openssl/provider.h>
15 #include <openssl/params.h>
16 #include <openssl/opensslv.h>
17 #include "crypto/cryptlib.h"
18 #ifndef FIPS_MODULE
19 #include "crypto/decoder.h" /* ossl_decoder_store_cache_flush */
20 #include "crypto/encoder.h" /* ossl_encoder_store_cache_flush */
21 #include "crypto/store.h" /* ossl_store_loader_store_cache_flush */
22 #endif
23 #include "crypto/evp.h" /* evp_method_store_cache_flush */
24 #include "crypto/rand.h"
25 #include "internal/nelem.h"
26 #include "internal/thread_once.h"
27 #include "internal/provider.h"
28 #include "internal/refcount.h"
29 #include "internal/bio.h"
30 #include "internal/core.h"
31 #include "provider_local.h"
32 #include "crypto/context.h"
33 #ifndef FIPS_MODULE
34 # include <openssl/self_test.h>
35 # include <openssl/indicator.h>
36 #endif
37 
38 /*
39  * This file defines and uses a number of different structures:
40  *
41  * OSSL_PROVIDER (provider_st): Used to represent all information related to a
42  * single instance of a provider.
43  *
44  * provider_store_st: Holds information about the collection of providers that
45  * are available within the current library context (OSSL_LIB_CTX). It also
46  * holds configuration information about providers that could be loaded at some
47  * future point.
48  *
49  * OSSL_PROVIDER_CHILD_CB: An instance of this structure holds the callbacks
50  * that have been registered for a child library context and the associated
51  * provider that registered those callbacks.
52  *
53  * Where a child library context exists then it has its own instance of the
54  * provider store. Each provider that exists in the parent provider store, has
55  * an associated child provider in the child library context's provider store.
56  * As providers get activated or deactivated this needs to be mirrored in the
57  * associated child providers.
58  *
59  * LOCKING
60  * =======
61  *
62  * There are a number of different locks used in this file and it is important
63  * to understand how they should be used in order to avoid deadlocks.
64  *
65  * Fields within a structure can often be "write once" on creation, and then
66  * "read many". Creation of a structure is done by a single thread, and
67  * therefore no lock is required for the "write once/read many" fields. It is
68  * safe for multiple threads to read these fields without a lock, because they
69  * will never be changed.
70  *
71  * However some fields may be changed after a structure has been created and
72  * shared between multiple threads. Where this is the case a lock is required.
73  *
74  * The locks available are:
75  *
76  * The provider flag_lock: Used to control updates to the various provider
77  * "flags" (flag_initialized and flag_activated).
78  *
79  * The provider activatecnt_lock: Used to control updates to the provider
80  * activatecnt value.
81  *
82  * The provider optbits_lock: Used to control access to the provider's
83  * operation_bits and operation_bits_sz fields.
84  *
85  * The store default_path_lock: Used to control access to the provider store's
86  * default search path value (default_path)
87  *
88  * The store lock: Used to control the stack of provider's held within the
89  * provider store, as well as the stack of registered child provider callbacks.
90  *
91  * As a general rule-of-thumb it is best to:
92  *  - keep the scope of the code that is protected by a lock to the absolute
93  *    minimum possible;
94  *  - try to keep the scope of the lock to within a single function (i.e. avoid
95  *    making calls to other functions while holding a lock);
96  *  - try to only ever hold one lock at a time.
97  *
98  * Unfortunately, it is not always possible to stick to the above guidelines.
99  * Where they are not adhered to there is always a danger of inadvertently
100  * introducing the possibility of deadlock. The following rules MUST be adhered
101  * to in order to avoid that:
102  *  - Holding multiple locks at the same time is only allowed for the
103  *    provider store lock, the provider activatecnt_lock and the provider flag_lock.
104  *  - When holding multiple locks they must be acquired in the following order of
105  *    precedence:
106  *        1) provider store lock
107  *        2) provider flag_lock
108  *        3) provider activatecnt_lock
109  *  - When releasing locks they must be released in the reverse order to which
110  *    they were acquired
111  *  - No locks may be held when making an upcall. NOTE: Some common functions
112  *    can make upcalls as part of their normal operation. If you need to call
113  *    some other function while holding a lock make sure you know whether it
114  *    will make any upcalls or not. For example ossl_provider_up_ref() can call
115  *    ossl_provider_up_ref_parent() which can call the c_prov_up_ref() upcall.
116  *  - It is permissible to hold the store and flag locks when calling child
117  *    provider callbacks. No other locks may be held during such callbacks.
118  */
119 
120 static OSSL_PROVIDER *provider_new(const char *name,
121                                    OSSL_provider_init_fn *init_function,
122                                    STACK_OF(INFOPAIR) *parameters);
123 
124 /*-
125  * Provider Object structure
126  * =========================
127  */
128 
129 #ifndef FIPS_MODULE
130 typedef struct {
131     OSSL_PROVIDER *prov;
132     int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
133     int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
134     int (*global_props_cb)(const char *props, void *cbdata);
135     void *cbdata;
136 } OSSL_PROVIDER_CHILD_CB;
137 DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB)
138 #endif
139 
140 struct provider_store_st;        /* Forward declaration */
141 
142 struct ossl_provider_st {
143     /* Flag bits */
144     unsigned int flag_initialized:1;
145     unsigned int flag_activated:1;
146 
147     /* Getting and setting the flags require synchronization */
148     CRYPTO_RWLOCK *flag_lock;
149 
150     /* OpenSSL library side data */
151     CRYPTO_REF_COUNT refcnt;
152     CRYPTO_RWLOCK *activatecnt_lock; /* For the activatecnt counter */
153     int activatecnt;
154     char *name;
155     char *path;
156     DSO *module;
157     OSSL_provider_init_fn *init_function;
158     STACK_OF(INFOPAIR) *parameters;
159     OSSL_LIB_CTX *libctx; /* The library context this instance is in */
160     struct provider_store_st *store; /* The store this instance belongs to */
161 #ifndef FIPS_MODULE
162     /*
163      * In the FIPS module inner provider, this isn't needed, since the
164      * error upcalls are always direct calls to the outer provider.
165      */
166     int error_lib;     /* ERR library number, one for each provider */
167 # ifndef OPENSSL_NO_ERR
168     ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */
169 # endif
170 #endif
171 
172     /* Provider side functions */
173     OSSL_FUNC_provider_teardown_fn *teardown;
174     OSSL_FUNC_provider_gettable_params_fn *gettable_params;
175     OSSL_FUNC_provider_get_params_fn *get_params;
176     OSSL_FUNC_provider_get_capabilities_fn *get_capabilities;
177     OSSL_FUNC_provider_self_test_fn *self_test;
178     OSSL_FUNC_provider_random_bytes_fn *random_bytes;
179     OSSL_FUNC_provider_query_operation_fn *query_operation;
180     OSSL_FUNC_provider_unquery_operation_fn *unquery_operation;
181 
182     /*
183      * Cache of bit to indicate of query_operation() has been called on
184      * a specific operation or not.
185      */
186     unsigned char *operation_bits;
187     size_t operation_bits_sz;
188     CRYPTO_RWLOCK *opbits_lock;
189 
190 #ifndef FIPS_MODULE
191     /* Whether this provider is the child of some other provider */
192     const OSSL_CORE_HANDLE *handle;
193     unsigned int ischild:1;
194 #endif
195 
196     /* Provider side data */
197     void *provctx;
198     const OSSL_DISPATCH *dispatch;
199 };
DEFINE_STACK_OF(OSSL_PROVIDER)200 DEFINE_STACK_OF(OSSL_PROVIDER)
201 
202 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
203                              const OSSL_PROVIDER * const *b)
204 {
205     return strcmp((*a)->name, (*b)->name);
206 }
207 
208 /*-
209  * Provider Object store
210  * =====================
211  *
212  * The Provider Object store is a library context object, and therefore needs
213  * an index.
214  */
215 
216 struct provider_store_st {
217     OSSL_LIB_CTX *libctx;
218     STACK_OF(OSSL_PROVIDER) *providers;
219     STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs;
220     CRYPTO_RWLOCK *default_path_lock;
221     CRYPTO_RWLOCK *lock;
222     char *default_path;
223     OSSL_PROVIDER_INFO *provinfo;
224     size_t numprovinfo;
225     size_t provinfosz;
226     unsigned int use_fallbacks:1;
227     unsigned int freeing:1;
228 };
229 
230 /*
231  * provider_deactivate_free() is a wrapper around ossl_provider_deactivate()
232  * and ossl_provider_free(), called as needed.
233  * Since this is only called when the provider store is being emptied, we
234  * don't need to care about any lock.
235  */
provider_deactivate_free(OSSL_PROVIDER * prov)236 static void provider_deactivate_free(OSSL_PROVIDER *prov)
237 {
238     if (prov->flag_activated)
239         ossl_provider_deactivate(prov, 1);
240     ossl_provider_free(prov);
241 }
242 
243 #ifndef FIPS_MODULE
ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB * cb)244 static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb)
245 {
246     OPENSSL_free(cb);
247 }
248 #endif
249 
infopair_free(INFOPAIR * pair)250 static void infopair_free(INFOPAIR *pair)
251 {
252     OPENSSL_free(pair->name);
253     OPENSSL_free(pair->value);
254     OPENSSL_free(pair);
255 }
256 
infopair_copy(const INFOPAIR * src)257 static INFOPAIR *infopair_copy(const INFOPAIR *src)
258 {
259     INFOPAIR *dest = OPENSSL_zalloc(sizeof(*dest));
260 
261     if (dest == NULL)
262         return NULL;
263     if (src->name != NULL) {
264         dest->name = OPENSSL_strdup(src->name);
265         if (dest->name == NULL)
266             goto err;
267     }
268     if (src->value != NULL) {
269         dest->value = OPENSSL_strdup(src->value);
270         if (dest->value == NULL)
271             goto err;
272     }
273     return dest;
274  err:
275     OPENSSL_free(dest->name);
276     OPENSSL_free(dest);
277     return NULL;
278 }
279 
ossl_provider_info_clear(OSSL_PROVIDER_INFO * info)280 void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info)
281 {
282     OPENSSL_free(info->name);
283     OPENSSL_free(info->path);
284     sk_INFOPAIR_pop_free(info->parameters, infopair_free);
285 }
286 
ossl_provider_store_free(void * vstore)287 void ossl_provider_store_free(void *vstore)
288 {
289     struct provider_store_st *store = vstore;
290     size_t i;
291 
292     if (store == NULL)
293         return;
294     store->freeing = 1;
295     OPENSSL_free(store->default_path);
296     sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free);
297 #ifndef FIPS_MODULE
298     sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs,
299                                        ossl_provider_child_cb_free);
300 #endif
301     CRYPTO_THREAD_lock_free(store->default_path_lock);
302     CRYPTO_THREAD_lock_free(store->lock);
303     for (i = 0; i < store->numprovinfo; i++)
304         ossl_provider_info_clear(&store->provinfo[i]);
305     OPENSSL_free(store->provinfo);
306     OPENSSL_free(store);
307 }
308 
ossl_provider_store_new(OSSL_LIB_CTX * ctx)309 void *ossl_provider_store_new(OSSL_LIB_CTX *ctx)
310 {
311     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
312 
313     if (store == NULL
314         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
315         || (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL
316 #ifndef FIPS_MODULE
317         || (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL
318 #endif
319         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
320         ossl_provider_store_free(store);
321         return NULL;
322     }
323     store->libctx = ctx;
324     store->use_fallbacks = 1;
325 
326     return store;
327 }
328 
get_provider_store(OSSL_LIB_CTX * libctx)329 static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx)
330 {
331     struct provider_store_st *store = NULL;
332 
333     store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX);
334     if (store == NULL)
335         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
336     return store;
337 }
338 
ossl_provider_disable_fallback_loading(OSSL_LIB_CTX * libctx)339 int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx)
340 {
341     struct provider_store_st *store;
342 
343     if ((store = get_provider_store(libctx)) != NULL) {
344         if (!CRYPTO_THREAD_write_lock(store->lock))
345             return 0;
346         store->use_fallbacks = 0;
347         CRYPTO_THREAD_unlock(store->lock);
348         return 1;
349     }
350     return 0;
351 }
352 
353 #define BUILTINS_BLOCK_SIZE     10
354 
ossl_provider_info_add_to_store(OSSL_LIB_CTX * libctx,OSSL_PROVIDER_INFO * entry)355 int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx,
356                                     OSSL_PROVIDER_INFO *entry)
357 {
358     struct provider_store_st *store = get_provider_store(libctx);
359     int ret = 0;
360 
361     if (entry->name == NULL) {
362         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
363         return 0;
364     }
365 
366     if (store == NULL) {
367         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
368         return 0;
369     }
370 
371     if (!CRYPTO_THREAD_write_lock(store->lock))
372         return 0;
373     if (store->provinfosz == 0) {
374         store->provinfo = OPENSSL_zalloc(sizeof(*store->provinfo)
375                                          * BUILTINS_BLOCK_SIZE);
376         if (store->provinfo == NULL)
377             goto err;
378         store->provinfosz = BUILTINS_BLOCK_SIZE;
379     } else if (store->numprovinfo == store->provinfosz) {
380         OSSL_PROVIDER_INFO *tmpbuiltins;
381         size_t newsz = store->provinfosz + BUILTINS_BLOCK_SIZE;
382 
383         tmpbuiltins = OPENSSL_realloc(store->provinfo,
384                                       sizeof(*store->provinfo) * newsz);
385         if (tmpbuiltins == NULL)
386             goto err;
387         store->provinfo = tmpbuiltins;
388         store->provinfosz = newsz;
389     }
390     store->provinfo[store->numprovinfo] = *entry;
391     store->numprovinfo++;
392 
393     ret = 1;
394  err:
395     CRYPTO_THREAD_unlock(store->lock);
396     return ret;
397 }
398 
ossl_provider_find(OSSL_LIB_CTX * libctx,const char * name,ossl_unused int noconfig)399 OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
400                                   ossl_unused int noconfig)
401 {
402     struct provider_store_st *store = NULL;
403     OSSL_PROVIDER *prov = NULL;
404 
405     if ((store = get_provider_store(libctx)) != NULL) {
406         OSSL_PROVIDER tmpl = { 0, };
407         int i;
408 
409 #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
410         /*
411          * Make sure any providers are loaded from config before we try to find
412          * them.
413          */
414         if (!noconfig) {
415             if (ossl_lib_ctx_is_default(libctx))
416                 OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
417         }
418 #endif
419 
420         tmpl.name = (char *)name;
421         if (!CRYPTO_THREAD_write_lock(store->lock))
422             return NULL;
423         sk_OSSL_PROVIDER_sort(store->providers);
424         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) != -1)
425             prov = sk_OSSL_PROVIDER_value(store->providers, i);
426         CRYPTO_THREAD_unlock(store->lock);
427         if (prov != NULL && !ossl_provider_up_ref(prov))
428             prov = NULL;
429     }
430 
431     return prov;
432 }
433 
434 /*-
435  * Provider Object methods
436  * =======================
437  */
438 
provider_new(const char * name,OSSL_provider_init_fn * init_function,STACK_OF (INFOPAIR)* parameters)439 static OSSL_PROVIDER *provider_new(const char *name,
440                                    OSSL_provider_init_fn *init_function,
441                                    STACK_OF(INFOPAIR) *parameters)
442 {
443     OSSL_PROVIDER *prov = NULL;
444 
445     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL)
446         return NULL;
447     if (!CRYPTO_NEW_REF(&prov->refcnt, 1)) {
448         OPENSSL_free(prov);
449         return NULL;
450     }
451     if ((prov->activatecnt_lock = CRYPTO_THREAD_lock_new()) == NULL) {
452         ossl_provider_free(prov);
453         ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
454         return NULL;
455     }
456 
457     if ((prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL
458         || (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL
459         || (prov->parameters = sk_INFOPAIR_deep_copy(parameters,
460                                                      infopair_copy,
461                                                      infopair_free)) == NULL) {
462         ossl_provider_free(prov);
463         ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
464         return NULL;
465     }
466     if ((prov->name = OPENSSL_strdup(name)) == NULL) {
467         ossl_provider_free(prov);
468         return NULL;
469     }
470 
471     prov->init_function = init_function;
472 
473     return prov;
474 }
475 
ossl_provider_up_ref(OSSL_PROVIDER * prov)476 int ossl_provider_up_ref(OSSL_PROVIDER *prov)
477 {
478     int ref = 0;
479 
480     if (CRYPTO_UP_REF(&prov->refcnt, &ref) <= 0)
481         return 0;
482 
483 #ifndef FIPS_MODULE
484     if (prov->ischild) {
485         if (!ossl_provider_up_ref_parent(prov, 0)) {
486             ossl_provider_free(prov);
487             return 0;
488         }
489     }
490 #endif
491 
492     return ref;
493 }
494 
495 #ifndef FIPS_MODULE
provider_up_ref_intern(OSSL_PROVIDER * prov,int activate)496 static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate)
497 {
498     if (activate)
499         return ossl_provider_activate(prov, 1, 0);
500 
501     return ossl_provider_up_ref(prov);
502 }
503 
provider_free_intern(OSSL_PROVIDER * prov,int deactivate)504 static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate)
505 {
506     if (deactivate)
507         return ossl_provider_deactivate(prov, 1);
508 
509     ossl_provider_free(prov);
510     return 1;
511 }
512 #endif
513 
514 /*
515  * We assume that the requested provider does not already exist in the store.
516  * The caller should check. If it does exist then adding it to the store later
517  * will fail.
518  */
ossl_provider_new(OSSL_LIB_CTX * libctx,const char * name,OSSL_provider_init_fn * init_function,OSSL_PARAM * params,int noconfig)519 OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
520                                  OSSL_provider_init_fn *init_function,
521                                  OSSL_PARAM *params, int noconfig)
522 {
523     struct provider_store_st *store = NULL;
524     OSSL_PROVIDER_INFO template;
525     OSSL_PROVIDER *prov = NULL;
526 
527     if ((store = get_provider_store(libctx)) == NULL)
528         return NULL;
529 
530     memset(&template, 0, sizeof(template));
531     if (init_function == NULL) {
532         const OSSL_PROVIDER_INFO *p;
533         size_t i;
534         int chosen = 0;
535 
536         /* Check if this is a predefined builtin provider */
537         for (p = ossl_predefined_providers; p->name != NULL; p++) {
538             if (strcmp(p->name, name) != 0)
539                 continue;
540             /* These compile-time templates always have NULL parameters */
541             template = *p;
542             chosen = 1;
543             break;
544         }
545         if (!CRYPTO_THREAD_read_lock(store->lock))
546             return NULL;
547         for (i = 0, p = store->provinfo; i < store->numprovinfo; p++, i++) {
548             if (strcmp(p->name, name) != 0)
549                 continue;
550             /* For built-in providers, copy just implicit parameters. */
551             if (!chosen)
552                 template = *p;
553             /*
554              * Explicit parameters override config-file defaults.  If an empty
555              * parameter set is desired, a non-NULL empty set must be provided.
556              */
557             if (params != NULL || p->parameters == NULL) {
558                 template.parameters = NULL;
559                 break;
560             }
561             /* Always copy to avoid sharing/mutation. */
562             template.parameters = sk_INFOPAIR_deep_copy(p->parameters,
563                                                         infopair_copy,
564                                                         infopair_free);
565             if (template.parameters == NULL) {
566                 CRYPTO_THREAD_unlock(store->lock);
567                 return NULL;
568             }
569             break;
570         }
571         CRYPTO_THREAD_unlock(store->lock);
572     } else {
573         template.init = init_function;
574     }
575 
576     if (params != NULL) {
577         int i;
578 
579         /* Don't leak if already non-NULL */
580         if (template.parameters == NULL)
581             template.parameters = sk_INFOPAIR_new_null();
582         if (template.parameters == NULL)
583             return NULL;
584 
585         for (i = 0; params[i].key != NULL; i++) {
586             if (params[i].data_type != OSSL_PARAM_UTF8_STRING)
587                 continue;
588             if (ossl_provider_info_add_parameter(&template, params[i].key,
589                                                  (char *)params[i].data) <= 0) {
590                 sk_INFOPAIR_pop_free(template.parameters, infopair_free);
591                 return NULL;
592             }
593         }
594     }
595 
596     /* provider_new() generates an error, so no need here */
597     prov = provider_new(name, template.init, template.parameters);
598 
599     /* If we copied the parameters, free them */
600     if (template.parameters != NULL)
601         sk_INFOPAIR_pop_free(template.parameters, infopair_free);
602 
603     if (prov == NULL)
604         return NULL;
605 
606     if (!ossl_provider_set_module_path(prov, template.path)) {
607         ossl_provider_free(prov);
608         return NULL;
609     }
610 
611     prov->libctx = libctx;
612 #ifndef FIPS_MODULE
613     prov->error_lib = ERR_get_next_error_library();
614 #endif
615 
616     /*
617      * At this point, the provider is only partially "loaded".  To be
618      * fully "loaded", ossl_provider_activate() must also be called and it must
619      * then be added to the provider store.
620      */
621 
622     return prov;
623 }
624 
625 /* Assumes that the store lock is held */
create_provider_children(OSSL_PROVIDER * prov)626 static int create_provider_children(OSSL_PROVIDER *prov)
627 {
628     int ret = 1;
629 #ifndef FIPS_MODULE
630     struct provider_store_st *store = prov->store;
631     OSSL_PROVIDER_CHILD_CB *child_cb;
632     int i, max;
633 
634     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
635     for (i = 0; i < max; i++) {
636         /*
637          * This is newly activated (activatecnt == 1), so we need to
638          * create child providers as necessary.
639          */
640         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
641         ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
642     }
643 #endif
644 
645     return ret;
646 }
647 
ossl_provider_add_to_store(OSSL_PROVIDER * prov,OSSL_PROVIDER ** actualprov,int retain_fallbacks)648 int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov,
649                                int retain_fallbacks)
650 {
651     struct provider_store_st *store;
652     int idx;
653     OSSL_PROVIDER tmpl = { 0, };
654     OSSL_PROVIDER *actualtmp = NULL;
655 
656     if (actualprov != NULL)
657         *actualprov = NULL;
658 
659     if ((store = get_provider_store(prov->libctx)) == NULL)
660         return 0;
661 
662     if (!CRYPTO_THREAD_write_lock(store->lock))
663         return 0;
664 
665     tmpl.name = (char *)prov->name;
666     idx = sk_OSSL_PROVIDER_find(store->providers, &tmpl);
667     if (idx == -1)
668         actualtmp = prov;
669     else
670         actualtmp = sk_OSSL_PROVIDER_value(store->providers, idx);
671 
672     if (idx == -1) {
673         if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0)
674             goto err;
675         prov->store = store;
676         if (!create_provider_children(prov)) {
677             sk_OSSL_PROVIDER_delete_ptr(store->providers, prov);
678             goto err;
679         }
680         if (!retain_fallbacks)
681             store->use_fallbacks = 0;
682     }
683 
684     CRYPTO_THREAD_unlock(store->lock);
685 
686     if (actualprov != NULL) {
687         if (!ossl_provider_up_ref(actualtmp)) {
688             ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
689             actualtmp = NULL;
690             return 0;
691         }
692         *actualprov = actualtmp;
693     }
694 
695     if (idx >= 0) {
696         /*
697          * The provider is already in the store. Probably two threads
698          * independently initialised their own provider objects with the same
699          * name and raced to put them in the store. This thread lost. We
700          * deactivate the one we just created and use the one that already
701          * exists instead.
702          * If we get here then we know we did not create provider children
703          * above, so we inform ossl_provider_deactivate not to attempt to remove
704          * any.
705          */
706         ossl_provider_deactivate(prov, 0);
707         ossl_provider_free(prov);
708     }
709 #ifndef FIPS_MODULE
710     else {
711         /*
712          * This can be done outside the lock. We tolerate other threads getting
713          * the wrong result briefly when creating OSSL_DECODER_CTXs.
714          */
715         ossl_decoder_cache_flush(prov->libctx);
716     }
717 #endif
718 
719     return 1;
720 
721  err:
722     CRYPTO_THREAD_unlock(store->lock);
723     return 0;
724 }
725 
ossl_provider_free(OSSL_PROVIDER * prov)726 void ossl_provider_free(OSSL_PROVIDER *prov)
727 {
728     if (prov != NULL) {
729         int ref = 0;
730 
731         CRYPTO_DOWN_REF(&prov->refcnt, &ref);
732 
733         /*
734          * When the refcount drops to zero, we clean up the provider.
735          * Note that this also does teardown, which may seem late,
736          * considering that init happens on first activation.  However,
737          * there may be other structures hanging on to the provider after
738          * the last deactivation and may therefore need full access to the
739          * provider's services.  Therefore, we deinit late.
740          */
741         if (ref == 0) {
742             if (prov->flag_initialized) {
743                 ossl_provider_teardown(prov);
744 #ifndef OPENSSL_NO_ERR
745 # ifndef FIPS_MODULE
746                 if (prov->error_strings != NULL) {
747                     ERR_unload_strings(prov->error_lib, prov->error_strings);
748                     OPENSSL_free(prov->error_strings);
749                     prov->error_strings = NULL;
750                 }
751 # endif
752 #endif
753                 OPENSSL_free(prov->operation_bits);
754                 prov->operation_bits = NULL;
755                 prov->operation_bits_sz = 0;
756                 prov->flag_initialized = 0;
757             }
758 
759 #ifndef FIPS_MODULE
760             /*
761              * We deregister thread handling whether or not the provider was
762              * initialized. If init was attempted but was not successful then
763              * the provider may still have registered a thread handler.
764              */
765             ossl_init_thread_deregister(prov);
766             DSO_free(prov->module);
767 #endif
768             OPENSSL_free(prov->name);
769             OPENSSL_free(prov->path);
770             sk_INFOPAIR_pop_free(prov->parameters, infopair_free);
771             CRYPTO_THREAD_lock_free(prov->opbits_lock);
772             CRYPTO_THREAD_lock_free(prov->flag_lock);
773             CRYPTO_THREAD_lock_free(prov->activatecnt_lock);
774             CRYPTO_FREE_REF(&prov->refcnt);
775             OPENSSL_free(prov);
776         }
777 #ifndef FIPS_MODULE
778         else if (prov->ischild) {
779             ossl_provider_free_parent(prov, 0);
780         }
781 #endif
782     }
783 }
784 
785 /* Setters */
ossl_provider_set_module_path(OSSL_PROVIDER * prov,const char * module_path)786 int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
787 {
788     OPENSSL_free(prov->path);
789     prov->path = NULL;
790     if (module_path == NULL)
791         return 1;
792     if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
793         return 1;
794     return 0;
795 }
796 
infopair_add(STACK_OF (INFOPAIR)** infopairsk,const char * name,const char * value)797 static int infopair_add(STACK_OF(INFOPAIR) **infopairsk, const char *name,
798                         const char *value)
799 {
800     INFOPAIR *pair = NULL;
801 
802     if ((pair = OPENSSL_zalloc(sizeof(*pair))) == NULL
803         || (pair->name = OPENSSL_strdup(name)) == NULL
804         || (pair->value = OPENSSL_strdup(value)) == NULL)
805         goto err;
806 
807     if ((*infopairsk == NULL
808          && (*infopairsk = sk_INFOPAIR_new_null()) == NULL)
809         || sk_INFOPAIR_push(*infopairsk, pair) <= 0) {
810         ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
811         goto err;
812     }
813 
814     return 1;
815 
816  err:
817     if (pair != NULL) {
818         OPENSSL_free(pair->name);
819         OPENSSL_free(pair->value);
820         OPENSSL_free(pair);
821     }
822     return 0;
823 }
824 
OSSL_PROVIDER_add_conf_parameter(OSSL_PROVIDER * prov,const char * name,const char * value)825 int OSSL_PROVIDER_add_conf_parameter(OSSL_PROVIDER *prov,
826                                      const char *name, const char *value)
827 {
828     return infopair_add(&prov->parameters, name, value);
829 }
830 
OSSL_PROVIDER_get_conf_parameters(const OSSL_PROVIDER * prov,OSSL_PARAM params[])831 int OSSL_PROVIDER_get_conf_parameters(const OSSL_PROVIDER *prov,
832                                       OSSL_PARAM params[])
833 {
834     int i;
835 
836     if (prov->parameters == NULL)
837         return 1;
838 
839     for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
840         INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
841         OSSL_PARAM *p = OSSL_PARAM_locate(params, pair->name);
842 
843         if (p != NULL
844             && !OSSL_PARAM_set_utf8_ptr(p, pair->value))
845             return 0;
846     }
847     return 1;
848 }
849 
OSSL_PROVIDER_conf_get_bool(const OSSL_PROVIDER * prov,const char * name,int defval)850 int OSSL_PROVIDER_conf_get_bool(const OSSL_PROVIDER *prov,
851                                 const char *name, int defval)
852 {
853     char *val = NULL;
854     OSSL_PARAM param[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
855 
856     param[0].key = (char *)name;
857     param[0].data_type = OSSL_PARAM_UTF8_PTR;
858     param[0].data = (void *) &val;
859     param[0].data_size = sizeof(val);
860     param[0].return_size = OSSL_PARAM_UNMODIFIED;
861 
862     /* Errors are ignored, returning the default value */
863     if (OSSL_PROVIDER_get_conf_parameters(prov, param)
864         && OSSL_PARAM_modified(param)
865         && val != NULL) {
866         if ((strcmp(val, "1") == 0)
867             || (OPENSSL_strcasecmp(val, "yes") == 0)
868             || (OPENSSL_strcasecmp(val, "true") == 0)
869             || (OPENSSL_strcasecmp(val, "on") == 0))
870             return 1;
871         else if ((strcmp(val, "0") == 0)
872                    || (OPENSSL_strcasecmp(val, "no") == 0)
873                    || (OPENSSL_strcasecmp(val, "false") == 0)
874                    || (OPENSSL_strcasecmp(val, "off") == 0))
875             return 0;
876     }
877     return defval;
878 }
879 
ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO * provinfo,const char * name,const char * value)880 int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo,
881                                      const char *name,
882                                      const char *value)
883 {
884     return infopair_add(&provinfo->parameters, name, value);
885 }
886 
887 /*
888  * Provider activation.
889  *
890  * What "activation" means depends on the provider form; for built in
891  * providers (in the library or the application alike), the provider
892  * can already be considered to be loaded, all that's needed is to
893  * initialize it.  However, for dynamically loadable provider modules,
894  * we must first load that module.
895  *
896  * Built in modules are distinguished from dynamically loaded modules
897  * with an already assigned init function.
898  */
899 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
900 
OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX * libctx,const char * path)901 int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx,
902                                           const char *path)
903 {
904     struct provider_store_st *store;
905     char *p = NULL;
906 
907     if (path != NULL) {
908         p = OPENSSL_strdup(path);
909         if (p == NULL)
910             return 0;
911     }
912     if ((store = get_provider_store(libctx)) != NULL
913             && CRYPTO_THREAD_write_lock(store->default_path_lock)) {
914         OPENSSL_free(store->default_path);
915         store->default_path = p;
916         CRYPTO_THREAD_unlock(store->default_path_lock);
917         return 1;
918     }
919     OPENSSL_free(p);
920     return 0;
921 }
922 
OSSL_PROVIDER_get0_default_search_path(OSSL_LIB_CTX * libctx)923 const char *OSSL_PROVIDER_get0_default_search_path(OSSL_LIB_CTX *libctx)
924 {
925     struct provider_store_st *store;
926     char *path = NULL;
927 
928     if ((store = get_provider_store(libctx)) != NULL
929             && CRYPTO_THREAD_read_lock(store->default_path_lock)) {
930         path = store->default_path;
931         CRYPTO_THREAD_unlock(store->default_path_lock);
932     }
933     return path;
934 }
935 
936 /*
937  * Internal version that doesn't affect the store flags, and thereby avoid
938  * locking.  Direct callers must remember to set the store flags when
939  * appropriate.
940  */
provider_init(OSSL_PROVIDER * prov)941 static int provider_init(OSSL_PROVIDER *prov)
942 {
943     const OSSL_DISPATCH *provider_dispatch = NULL;
944     void *tmp_provctx = NULL;    /* safety measure */
945 #ifndef OPENSSL_NO_ERR
946 # ifndef FIPS_MODULE
947     OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL;
948 # endif
949 #endif
950     int ok = 0;
951 
952     if (!ossl_assert(!prov->flag_initialized)) {
953         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
954         goto end;
955     }
956 
957     /*
958      * If the init function isn't set, it indicates that this provider is
959      * a loadable module.
960      */
961     if (prov->init_function == NULL) {
962 #ifdef FIPS_MODULE
963         goto end;
964 #else
965         if (prov->module == NULL) {
966             char *allocated_path = NULL;
967             const char *module_path = NULL;
968             char *merged_path = NULL;
969             const char *load_dir = NULL;
970             char *allocated_load_dir = NULL;
971             struct provider_store_st *store;
972 
973             if ((prov->module = DSO_new()) == NULL) {
974                 /* DSO_new() generates an error already */
975                 goto end;
976             }
977 
978             if ((store = get_provider_store(prov->libctx)) == NULL
979                     || !CRYPTO_THREAD_read_lock(store->default_path_lock))
980                 goto end;
981 
982             if (store->default_path != NULL) {
983                 allocated_load_dir = OPENSSL_strdup(store->default_path);
984                 CRYPTO_THREAD_unlock(store->default_path_lock);
985                 if (allocated_load_dir == NULL)
986                     goto end;
987                 load_dir = allocated_load_dir;
988             } else {
989                 CRYPTO_THREAD_unlock(store->default_path_lock);
990             }
991 
992             if (load_dir == NULL) {
993                 load_dir = ossl_safe_getenv("OPENSSL_MODULES");
994                 if (load_dir == NULL)
995                     load_dir = ossl_get_modulesdir();
996             }
997 
998             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
999                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
1000 
1001             module_path = prov->path;
1002             if (module_path == NULL)
1003                 module_path = allocated_path =
1004                     DSO_convert_filename(prov->module, prov->name);
1005             if (module_path != NULL)
1006                 merged_path = DSO_merge(prov->module, module_path, load_dir);
1007 
1008             if (merged_path == NULL
1009                 || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
1010                 DSO_free(prov->module);
1011                 prov->module = NULL;
1012             }
1013 
1014             OPENSSL_free(merged_path);
1015             OPENSSL_free(allocated_path);
1016             OPENSSL_free(allocated_load_dir);
1017         }
1018 
1019         if (prov->module == NULL) {
1020             /* DSO has already recorded errors, this is just a tracepoint */
1021             ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_DSO_LIB,
1022                            "name=%s", prov->name);
1023             goto end;
1024         }
1025 
1026         prov->init_function = (OSSL_provider_init_fn *)
1027             DSO_bind_func(prov->module, "OSSL_provider_init");
1028 #endif
1029     }
1030 
1031     /* Check for and call the initialise function for the provider. */
1032     if (prov->init_function == NULL) {
1033         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED,
1034                        "name=%s, provider has no provider init function",
1035                        prov->name);
1036         goto end;
1037     }
1038 #ifndef FIPS_MODULE
1039     OSSL_TRACE_BEGIN(PROVIDER) {
1040         BIO_printf(trc_out,
1041                    "(provider %s) initalizing\n", prov->name);
1042     } OSSL_TRACE_END(PROVIDER);
1043 #endif
1044 
1045     if (!prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch,
1046                              &provider_dispatch, &tmp_provctx)) {
1047         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL,
1048                        "name=%s", prov->name);
1049         goto end;
1050     }
1051     prov->provctx = tmp_provctx;
1052     prov->dispatch = provider_dispatch;
1053 
1054     if (provider_dispatch != NULL) {
1055         for (; provider_dispatch->function_id != 0; provider_dispatch++) {
1056             switch (provider_dispatch->function_id) {
1057             case OSSL_FUNC_PROVIDER_TEARDOWN:
1058                 prov->teardown =
1059                     OSSL_FUNC_provider_teardown(provider_dispatch);
1060                 break;
1061             case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS:
1062                 prov->gettable_params =
1063                     OSSL_FUNC_provider_gettable_params(provider_dispatch);
1064                 break;
1065             case OSSL_FUNC_PROVIDER_GET_PARAMS:
1066                 prov->get_params =
1067                     OSSL_FUNC_provider_get_params(provider_dispatch);
1068                 break;
1069             case OSSL_FUNC_PROVIDER_SELF_TEST:
1070                 prov->self_test =
1071                     OSSL_FUNC_provider_self_test(provider_dispatch);
1072                 break;
1073             case OSSL_FUNC_PROVIDER_RANDOM_BYTES:
1074                 prov->random_bytes =
1075                     OSSL_FUNC_provider_random_bytes(provider_dispatch);
1076                 break;
1077             case OSSL_FUNC_PROVIDER_GET_CAPABILITIES:
1078                 prov->get_capabilities =
1079                     OSSL_FUNC_provider_get_capabilities(provider_dispatch);
1080                 break;
1081             case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
1082                 prov->query_operation =
1083                     OSSL_FUNC_provider_query_operation(provider_dispatch);
1084                 break;
1085             case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION:
1086                 prov->unquery_operation =
1087                     OSSL_FUNC_provider_unquery_operation(provider_dispatch);
1088                 break;
1089 #ifndef OPENSSL_NO_ERR
1090 # ifndef FIPS_MODULE
1091             case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS:
1092                 p_get_reason_strings =
1093                     OSSL_FUNC_provider_get_reason_strings(provider_dispatch);
1094                 break;
1095 # endif
1096 #endif
1097             }
1098         }
1099     }
1100 
1101 #ifndef OPENSSL_NO_ERR
1102 # ifndef FIPS_MODULE
1103     if (p_get_reason_strings != NULL) {
1104         const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx);
1105         size_t cnt, cnt2;
1106 
1107         /*
1108          * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM,
1109          * although they are essentially the same type.
1110          * Furthermore, ERR_load_strings() patches the array's error number
1111          * with the error library number, so we need to make a copy of that
1112          * array either way.
1113          */
1114         cnt = 0;
1115         while (reasonstrings[cnt].id != 0) {
1116             if (ERR_GET_LIB(reasonstrings[cnt].id) != 0)
1117                 goto end;
1118             cnt++;
1119         }
1120         cnt++;                   /* One for the terminating item */
1121 
1122         /* Allocate one extra item for the "library" name */
1123         prov->error_strings =
1124             OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1));
1125         if (prov->error_strings == NULL)
1126             goto end;
1127 
1128         /*
1129          * Set the "library" name.
1130          */
1131         prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0);
1132         prov->error_strings[0].string = prov->name;
1133         /*
1134          * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions
1135          * 1..cnt.
1136          */
1137         for (cnt2 = 1; cnt2 <= cnt; cnt2++) {
1138             prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id;
1139             prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr;
1140         }
1141 
1142         ERR_load_strings(prov->error_lib, prov->error_strings);
1143     }
1144 # endif
1145 #endif
1146 
1147     /* With this flag set, this provider has become fully "loaded". */
1148     prov->flag_initialized = 1;
1149     ok = 1;
1150 
1151  end:
1152     return ok;
1153 }
1154 
1155 /*
1156  * Deactivate a provider. If upcalls is 0 then we suppress any upcalls to a
1157  * parent provider. If removechildren is 0 then we suppress any calls to remove
1158  * child providers.
1159  * Return -1 on failure and the activation count on success
1160  */
provider_deactivate(OSSL_PROVIDER * prov,int upcalls,int removechildren)1161 static int provider_deactivate(OSSL_PROVIDER *prov, int upcalls,
1162                                int removechildren)
1163 {
1164     int count;
1165     struct provider_store_st *store;
1166 #ifndef FIPS_MODULE
1167     int freeparent = 0;
1168 #endif
1169     int lock = 1;
1170 
1171     if (!ossl_assert(prov != NULL))
1172         return -1;
1173 
1174 #ifndef FIPS_MODULE
1175     if (prov->random_bytes != NULL
1176             && !ossl_rand_check_random_provider_on_unload(prov->libctx, prov))
1177         return -1;
1178 #endif
1179 
1180     /*
1181      * No need to lock if we've got no store because we've not been shared with
1182      * other threads.
1183      */
1184     store = get_provider_store(prov->libctx);
1185     if (store == NULL)
1186         lock = 0;
1187 
1188     if (lock && !CRYPTO_THREAD_read_lock(store->lock))
1189         return -1;
1190     if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
1191         CRYPTO_THREAD_unlock(store->lock);
1192         return -1;
1193     }
1194 
1195     if (!CRYPTO_atomic_add(&prov->activatecnt, -1, &count, prov->activatecnt_lock)) {
1196         if (lock) {
1197             CRYPTO_THREAD_unlock(prov->flag_lock);
1198             CRYPTO_THREAD_unlock(store->lock);
1199         }
1200         return -1;
1201     }
1202 
1203 #ifndef FIPS_MODULE
1204     if (count >= 1 && prov->ischild && upcalls) {
1205         /*
1206          * We have had a direct activation in this child libctx so we need to
1207          * now down the ref count in the parent provider. We do the actual down
1208          * ref outside of the flag_lock, since it could involve getting other
1209          * locks.
1210          */
1211         freeparent = 1;
1212     }
1213 #endif
1214 
1215     if (count < 1)
1216         prov->flag_activated = 0;
1217 #ifndef FIPS_MODULE
1218     else
1219         removechildren = 0;
1220 #endif
1221 
1222 #ifndef FIPS_MODULE
1223     if (removechildren && store != NULL) {
1224         int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
1225         OSSL_PROVIDER_CHILD_CB *child_cb;
1226 
1227         for (i = 0; i < max; i++) {
1228             child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
1229             child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
1230         }
1231     }
1232 #endif
1233     if (lock) {
1234         CRYPTO_THREAD_unlock(prov->flag_lock);
1235         CRYPTO_THREAD_unlock(store->lock);
1236         /*
1237          * This can be done outside the lock. We tolerate other threads getting
1238          * the wrong result briefly when creating OSSL_DECODER_CTXs.
1239          */
1240 #ifndef FIPS_MODULE
1241         if (count < 1)
1242             ossl_decoder_cache_flush(prov->libctx);
1243 #endif
1244     }
1245 #ifndef FIPS_MODULE
1246     if (freeparent)
1247         ossl_provider_free_parent(prov, 1);
1248 #endif
1249 
1250     /* We don't deinit here, that's done in ossl_provider_free() */
1251     return count;
1252 }
1253 
1254 /*
1255  * Activate a provider.
1256  * Return -1 on failure and the activation count on success
1257  */
provider_activate(OSSL_PROVIDER * prov,int lock,int upcalls)1258 static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls)
1259 {
1260     int count = -1;
1261     struct provider_store_st *store;
1262     int ret = 1;
1263 
1264     store = prov->store;
1265     /*
1266     * If the provider hasn't been added to the store, then we don't need
1267     * any locks because we've not shared it with other threads.
1268     */
1269     if (store == NULL) {
1270         lock = 0;
1271         if (!provider_init(prov))
1272             return -1;
1273     }
1274 
1275 #ifndef FIPS_MODULE
1276     if (prov->random_bytes != NULL
1277             && !ossl_rand_check_random_provider_on_load(prov->libctx, prov))
1278         return -1;
1279 
1280     if (prov->ischild && upcalls && !ossl_provider_up_ref_parent(prov, 1))
1281         return -1;
1282 #endif
1283 
1284     if (lock && !CRYPTO_THREAD_read_lock(store->lock)) {
1285 #ifndef FIPS_MODULE
1286         if (prov->ischild && upcalls)
1287             ossl_provider_free_parent(prov, 1);
1288 #endif
1289         return -1;
1290     }
1291 
1292     if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
1293         CRYPTO_THREAD_unlock(store->lock);
1294 #ifndef FIPS_MODULE
1295         if (prov->ischild && upcalls)
1296             ossl_provider_free_parent(prov, 1);
1297 #endif
1298         return -1;
1299     }
1300     if (CRYPTO_atomic_add(&prov->activatecnt, 1, &count, prov->activatecnt_lock)) {
1301         prov->flag_activated = 1;
1302 
1303         if (count == 1 && store != NULL) {
1304             ret = create_provider_children(prov);
1305         }
1306     }
1307     if (lock) {
1308         CRYPTO_THREAD_unlock(prov->flag_lock);
1309         CRYPTO_THREAD_unlock(store->lock);
1310         /*
1311          * This can be done outside the lock. We tolerate other threads getting
1312          * the wrong result briefly when creating OSSL_DECODER_CTXs.
1313          */
1314 #ifndef FIPS_MODULE
1315         if (count == 1)
1316             ossl_decoder_cache_flush(prov->libctx);
1317 #endif
1318     }
1319 
1320     if (!ret)
1321         return -1;
1322 
1323     return count;
1324 }
1325 
provider_flush_store_cache(const OSSL_PROVIDER * prov)1326 static int provider_flush_store_cache(const OSSL_PROVIDER *prov)
1327 {
1328     struct provider_store_st *store;
1329     int freeing;
1330 
1331     if ((store = get_provider_store(prov->libctx)) == NULL)
1332         return 0;
1333 
1334     if (!CRYPTO_THREAD_read_lock(store->lock))
1335         return 0;
1336     freeing = store->freeing;
1337     CRYPTO_THREAD_unlock(store->lock);
1338 
1339     if (!freeing) {
1340         int acc
1341             = evp_method_store_cache_flush(prov->libctx)
1342 #ifndef FIPS_MODULE
1343             + ossl_encoder_store_cache_flush(prov->libctx)
1344             + ossl_decoder_store_cache_flush(prov->libctx)
1345             + ossl_store_loader_store_cache_flush(prov->libctx)
1346 #endif
1347             ;
1348 
1349 #ifndef FIPS_MODULE
1350         return acc == 4;
1351 #else
1352         return acc == 1;
1353 #endif
1354     }
1355     return 1;
1356 }
1357 
provider_remove_store_methods(OSSL_PROVIDER * prov)1358 static int provider_remove_store_methods(OSSL_PROVIDER *prov)
1359 {
1360     struct provider_store_st *store;
1361     int freeing;
1362 
1363     if ((store = get_provider_store(prov->libctx)) == NULL)
1364         return 0;
1365 
1366     if (!CRYPTO_THREAD_read_lock(store->lock))
1367         return 0;
1368     freeing = store->freeing;
1369     CRYPTO_THREAD_unlock(store->lock);
1370 
1371     if (!freeing) {
1372         int acc;
1373 
1374         if (!CRYPTO_THREAD_write_lock(prov->opbits_lock))
1375             return 0;
1376         OPENSSL_free(prov->operation_bits);
1377         prov->operation_bits = NULL;
1378         prov->operation_bits_sz = 0;
1379         CRYPTO_THREAD_unlock(prov->opbits_lock);
1380 
1381         acc = evp_method_store_remove_all_provided(prov)
1382 #ifndef FIPS_MODULE
1383             + ossl_encoder_store_remove_all_provided(prov)
1384             + ossl_decoder_store_remove_all_provided(prov)
1385             + ossl_store_loader_store_remove_all_provided(prov)
1386 #endif
1387             ;
1388 
1389 #ifndef FIPS_MODULE
1390         return acc == 4;
1391 #else
1392         return acc == 1;
1393 #endif
1394     }
1395     return 1;
1396 }
1397 
ossl_provider_activate(OSSL_PROVIDER * prov,int upcalls,int aschild)1398 int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild)
1399 {
1400     int count;
1401 
1402     if (prov == NULL)
1403         return 0;
1404 #ifndef FIPS_MODULE
1405     /*
1406      * If aschild is true, then we only actually do the activation if the
1407      * provider is a child. If its not, this is still success.
1408      */
1409     if (aschild && !prov->ischild)
1410         return 1;
1411 #endif
1412     if ((count = provider_activate(prov, 1, upcalls)) > 0)
1413         return count == 1 ? provider_flush_store_cache(prov) : 1;
1414 
1415     return 0;
1416 }
1417 
ossl_provider_deactivate(OSSL_PROVIDER * prov,int removechildren)1418 int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren)
1419 {
1420     int count;
1421 
1422     if (prov == NULL
1423             || (count = provider_deactivate(prov, 1, removechildren)) < 0)
1424         return 0;
1425     return count == 0 ? provider_remove_store_methods(prov) : 1;
1426 }
1427 
ossl_provider_ctx(const OSSL_PROVIDER * prov)1428 void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
1429 {
1430     return prov != NULL ? prov->provctx : NULL;
1431 }
1432 
1433 /*
1434  * This function only does something once when store->use_fallbacks == 1,
1435  * and then sets store->use_fallbacks = 0, so the second call and so on is
1436  * effectively a no-op.
1437  */
provider_activate_fallbacks(struct provider_store_st * store)1438 static int provider_activate_fallbacks(struct provider_store_st *store)
1439 {
1440     int use_fallbacks;
1441     int activated_fallback_count = 0;
1442     int ret = 0;
1443     const OSSL_PROVIDER_INFO *p;
1444 
1445     if (!CRYPTO_THREAD_read_lock(store->lock))
1446         return 0;
1447     use_fallbacks = store->use_fallbacks;
1448     CRYPTO_THREAD_unlock(store->lock);
1449     if (!use_fallbacks)
1450         return 1;
1451 
1452     if (!CRYPTO_THREAD_write_lock(store->lock))
1453         return 0;
1454     /* Check again, just in case another thread changed it */
1455     use_fallbacks = store->use_fallbacks;
1456     if (!use_fallbacks) {
1457         CRYPTO_THREAD_unlock(store->lock);
1458         return 1;
1459     }
1460 
1461     for (p = ossl_predefined_providers; p->name != NULL; p++) {
1462         OSSL_PROVIDER *prov = NULL;
1463         OSSL_PROVIDER_INFO *info = store->provinfo;
1464         STACK_OF(INFOPAIR) *params = NULL;
1465         size_t i;
1466 
1467         if (!p->is_fallback)
1468             continue;
1469 
1470         for (i = 0; i < store->numprovinfo; info++, i++) {
1471             if (strcmp(info->name, p->name) != 0)
1472                 continue;
1473             params = info->parameters;
1474             break;
1475         }
1476 
1477         /*
1478          * We use the internal constructor directly here,
1479          * otherwise we get a call loop
1480          */
1481         prov = provider_new(p->name, p->init, params);
1482         if (prov == NULL)
1483             goto err;
1484         prov->libctx = store->libctx;
1485 #ifndef FIPS_MODULE
1486         prov->error_lib = ERR_get_next_error_library();
1487 #endif
1488 
1489         /*
1490          * We are calling provider_activate while holding the store lock. This
1491          * means the init function will be called while holding a lock. Normally
1492          * we try to avoid calling a user callback while holding a lock.
1493          * However, fallbacks are never third party providers so we accept this.
1494          */
1495         if (provider_activate(prov, 0, 0) < 0) {
1496             ossl_provider_free(prov);
1497             goto err;
1498         }
1499         prov->store = store;
1500         if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
1501             ossl_provider_free(prov);
1502             goto err;
1503         }
1504         activated_fallback_count++;
1505     }
1506 
1507     if (activated_fallback_count > 0) {
1508         store->use_fallbacks = 0;
1509         ret = 1;
1510     }
1511  err:
1512     CRYPTO_THREAD_unlock(store->lock);
1513     return ret;
1514 }
1515 
ossl_provider_activate_fallbacks(OSSL_LIB_CTX * ctx)1516 int ossl_provider_activate_fallbacks(OSSL_LIB_CTX *ctx)
1517 {
1518     struct provider_store_st *store = get_provider_store(ctx);
1519 
1520     if (store == NULL)
1521         return 0;
1522 
1523     return provider_activate_fallbacks(store);
1524 }
1525 
ossl_provider_doall_activated(OSSL_LIB_CTX * ctx,int (* cb)(OSSL_PROVIDER * provider,void * cbdata),void * cbdata)1526 int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx,
1527                                   int (*cb)(OSSL_PROVIDER *provider,
1528                                             void *cbdata),
1529                                   void *cbdata)
1530 {
1531     int ret = 0, curr, max, ref = 0;
1532     struct provider_store_st *store = get_provider_store(ctx);
1533     STACK_OF(OSSL_PROVIDER) *provs = NULL;
1534 
1535 #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
1536     /*
1537      * Make sure any providers are loaded from config before we try to use
1538      * them.
1539      */
1540     if (ossl_lib_ctx_is_default(ctx))
1541         OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
1542 #endif
1543 
1544     if (store == NULL)
1545         return 1;
1546     if (!provider_activate_fallbacks(store))
1547         return 0;
1548 
1549     /*
1550      * Under lock, grab a copy of the provider list and up_ref each
1551      * provider so that they don't disappear underneath us.
1552      */
1553     if (!CRYPTO_THREAD_read_lock(store->lock))
1554         return 0;
1555     provs = sk_OSSL_PROVIDER_dup(store->providers);
1556     if (provs == NULL) {
1557         CRYPTO_THREAD_unlock(store->lock);
1558         return 0;
1559     }
1560     max = sk_OSSL_PROVIDER_num(provs);
1561     /*
1562      * We work backwards through the stack so that we can safely delete items
1563      * as we go.
1564      */
1565     for (curr = max - 1; curr >= 0; curr--) {
1566         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1567 
1568         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1569             goto err_unlock;
1570         if (prov->flag_activated) {
1571             /*
1572              * We call CRYPTO_UP_REF directly rather than ossl_provider_up_ref
1573              * to avoid upping the ref count on the parent provider, which we
1574              * must not do while holding locks.
1575              */
1576             if (CRYPTO_UP_REF(&prov->refcnt, &ref) <= 0) {
1577                 CRYPTO_THREAD_unlock(prov->flag_lock);
1578                 goto err_unlock;
1579             }
1580             /*
1581              * It's already activated, but we up the activated count to ensure
1582              * it remains activated until after we've called the user callback.
1583              * In theory this could mean the parent provider goes inactive,
1584              * whilst still activated in the child for a short period. That's ok.
1585              */
1586             if (!CRYPTO_atomic_add(&prov->activatecnt, 1, &ref,
1587                                    prov->activatecnt_lock)) {
1588                 CRYPTO_DOWN_REF(&prov->refcnt, &ref);
1589                 CRYPTO_THREAD_unlock(prov->flag_lock);
1590                 goto err_unlock;
1591             }
1592         } else {
1593             sk_OSSL_PROVIDER_delete(provs, curr);
1594             max--;
1595         }
1596         CRYPTO_THREAD_unlock(prov->flag_lock);
1597     }
1598     CRYPTO_THREAD_unlock(store->lock);
1599 
1600     /*
1601      * Now, we sweep through all providers not under lock
1602      */
1603     for (curr = 0; curr < max; curr++) {
1604         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1605 
1606         if (!cb(prov, cbdata)) {
1607             curr = -1;
1608             goto finish;
1609         }
1610     }
1611     curr = -1;
1612 
1613     ret = 1;
1614     goto finish;
1615 
1616  err_unlock:
1617     CRYPTO_THREAD_unlock(store->lock);
1618  finish:
1619     /*
1620      * The pop_free call doesn't do what we want on an error condition. We
1621      * either start from the first item in the stack, or part way through if
1622      * we only processed some of the items.
1623      */
1624     for (curr++; curr < max; curr++) {
1625         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1626 
1627         if (!CRYPTO_atomic_add(&prov->activatecnt, -1, &ref,
1628                                prov->activatecnt_lock)) {
1629             ret = 0;
1630             continue;
1631         }
1632         if (ref < 1) {
1633             /*
1634              * Looks like we need to deactivate properly. We could just have
1635              * done this originally, but it involves taking a write lock so
1636              * we avoid it. We up the count again and do a full deactivation
1637              */
1638             if (CRYPTO_atomic_add(&prov->activatecnt, 1, &ref,
1639                                   prov->activatecnt_lock))
1640                 provider_deactivate(prov, 0, 1);
1641             else
1642                 ret = 0;
1643         }
1644         /*
1645          * As above where we did the up-ref, we don't call ossl_provider_free
1646          * to avoid making upcalls. There should always be at least one ref
1647          * to the provider in the store, so this should never drop to 0.
1648          */
1649         if (!CRYPTO_DOWN_REF(&prov->refcnt, &ref)) {
1650             ret = 0;
1651             continue;
1652         }
1653         /*
1654          * Not much we can do if this assert ever fails. So we don't use
1655          * ossl_assert here.
1656          */
1657         assert(ref > 0);
1658     }
1659     sk_OSSL_PROVIDER_free(provs);
1660     return ret;
1661 }
1662 
OSSL_PROVIDER_available(OSSL_LIB_CTX * libctx,const char * name)1663 int OSSL_PROVIDER_available(OSSL_LIB_CTX *libctx, const char *name)
1664 {
1665     OSSL_PROVIDER *prov = NULL;
1666     int available = 0;
1667     struct provider_store_st *store = get_provider_store(libctx);
1668 
1669     if (store == NULL || !provider_activate_fallbacks(store))
1670         return 0;
1671 
1672     prov = ossl_provider_find(libctx, name, 0);
1673     if (prov != NULL) {
1674         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1675             return 0;
1676         available = prov->flag_activated;
1677         CRYPTO_THREAD_unlock(prov->flag_lock);
1678         ossl_provider_free(prov);
1679     }
1680     return available;
1681 }
1682 
1683 /* Getters of Provider Object data */
ossl_provider_name(const OSSL_PROVIDER * prov)1684 const char *ossl_provider_name(const OSSL_PROVIDER *prov)
1685 {
1686     return prov->name;
1687 }
1688 
ossl_provider_dso(const OSSL_PROVIDER * prov)1689 const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
1690 {
1691     return prov->module;
1692 }
1693 
ossl_provider_module_name(const OSSL_PROVIDER * prov)1694 const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
1695 {
1696 #ifdef FIPS_MODULE
1697     return NULL;
1698 #else
1699     return DSO_get_filename(prov->module);
1700 #endif
1701 }
1702 
ossl_provider_module_path(const OSSL_PROVIDER * prov)1703 const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
1704 {
1705 #ifdef FIPS_MODULE
1706     return NULL;
1707 #else
1708     /* FIXME: Ensure it's a full path */
1709     return DSO_get_filename(prov->module);
1710 #endif
1711 }
1712 
ossl_provider_get0_dispatch(const OSSL_PROVIDER * prov)1713 const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov)
1714 {
1715     if (prov != NULL)
1716         return prov->dispatch;
1717 
1718     return NULL;
1719 }
1720 
ossl_provider_libctx(const OSSL_PROVIDER * prov)1721 OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov)
1722 {
1723     return prov != NULL ? prov->libctx : NULL;
1724 }
1725 
1726 /**
1727  * @brief Tears down the given provider.
1728  *
1729  * This function calls the `teardown` callback of the given provider to release
1730  * any resources associated with it. The teardown is skipped if the callback is
1731  * not defined or, in non-FIPS builds, if the provider is a child.
1732  *
1733  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1734  *
1735  * If tracing is enabled, a message is printed indicating that the teardown is
1736  * being called.
1737  */
ossl_provider_teardown(const OSSL_PROVIDER * prov)1738 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
1739 {
1740     if (prov->teardown != NULL
1741 #ifndef FIPS_MODULE
1742             && !prov->ischild
1743 #endif
1744         ) {
1745 #ifndef FIPS_MODULE
1746         OSSL_TRACE_BEGIN(PROVIDER) {
1747             BIO_printf(trc_out, "(provider %s) calling teardown\n",
1748                        ossl_provider_name(prov));
1749         } OSSL_TRACE_END(PROVIDER);
1750 #endif
1751         prov->teardown(prov->provctx);
1752     }
1753 }
1754 
1755 /**
1756  * @brief Retrieves the parameters that can be obtained from a provider.
1757  *
1758  * This function calls the `gettable_params` callback of the given provider to
1759  * get a list of parameters that can be retrieved.
1760  *
1761  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1762  *
1763  * @return Pointer to an array of OSSL_PARAM structures that represent the
1764  *         gettable parameters, or NULL if the callback is not defined.
1765  *
1766  * If tracing is enabled, the gettable parameters are printed for debugging.
1767  */
ossl_provider_gettable_params(const OSSL_PROVIDER * prov)1768 const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov)
1769 {
1770     const OSSL_PARAM *ret = NULL;
1771 
1772     if (prov->gettable_params != NULL)
1773         ret = prov->gettable_params(prov->provctx);
1774 
1775 #ifndef FIPS_MODULE
1776     OSSL_TRACE_BEGIN(PROVIDER) {
1777         char *buf = NULL;
1778 
1779         BIO_printf(trc_out, "(provider %s) gettable params\n",
1780                    ossl_provider_name(prov));
1781         BIO_printf(trc_out, "Parameters:\n");
1782         if (prov->gettable_params != NULL) {
1783             if (!OSSL_PARAM_print_to_bio(ret, trc_out, 0))
1784                 BIO_printf(trc_out, "Failed to parse param values\n");
1785             OPENSSL_free(buf);
1786         } else {
1787             BIO_printf(trc_out, "Provider doesn't implement gettable_params\n");
1788         }
1789     } OSSL_TRACE_END(PROVIDER);
1790 #endif
1791 
1792     return ret;
1793 }
1794 
1795 /**
1796  * @brief Retrieves parameters from a provider.
1797  *
1798  * This function calls the `get_params` callback of the given provider to
1799  * retrieve its parameters. If the callback is defined, it is invoked with the
1800  * provider context and the parameters array.
1801  *
1802  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1803  * @param params Array of OSSL_PARAM structures to store the retrieved parameters.
1804  *
1805  * @return 1 on success, 0 if the `get_params` callback is not defined or fails.
1806  *
1807  * If tracing is enabled, the retrieved parameters are printed for debugging.
1808  */
ossl_provider_get_params(const OSSL_PROVIDER * prov,OSSL_PARAM params[])1809 int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
1810 {
1811     int ret;
1812 
1813     if (prov->get_params == NULL)
1814         return 0;
1815 
1816     ret = prov->get_params(prov->provctx, params);
1817 #ifndef FIPS_MODULE
1818     OSSL_TRACE_BEGIN(PROVIDER) {
1819 
1820         BIO_printf(trc_out,
1821                    "(provider %s) calling get_params\n", prov->name);
1822         if (ret == 1) {
1823             BIO_printf(trc_out, "Parameters:\n");
1824             if (!OSSL_PARAM_print_to_bio(params, trc_out, 1))
1825                 BIO_printf(trc_out, "Failed to parse param values\n");
1826         } else {
1827             BIO_printf(trc_out, "get_params call failed\n");
1828         }
1829     } OSSL_TRACE_END(PROVIDER);
1830 #endif
1831     return ret;
1832 }
1833 
1834 /**
1835  * @brief Performs a self-test on the given provider.
1836  *
1837  * This function calls the `self_test` callback of the given provider to
1838  * perform a self-test. If the callback is not defined, it assumes the test
1839  * passed.
1840  *
1841  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1842  *
1843  * @return 1 if the self-test passes or the callback is not defined, 0 on failure.
1844  *
1845  * If tracing is enabled, the result of the self-test is printed for debugging.
1846  * If the test fails, the provider's store methods are removed.
1847  */
ossl_provider_self_test(const OSSL_PROVIDER * prov)1848 int ossl_provider_self_test(const OSSL_PROVIDER *prov)
1849 {
1850     int ret = 1;
1851 
1852     if (prov->self_test != NULL)
1853         ret = prov->self_test(prov->provctx);
1854 
1855 #ifndef FIPS_MODULE
1856     OSSL_TRACE_BEGIN(PROVIDER) {
1857         if (prov->self_test != NULL)
1858             BIO_printf(trc_out,
1859                        "(provider %s) Calling self_test, ret = %d\n",
1860                        prov->name, ret);
1861         else
1862             BIO_printf(trc_out,
1863                        "(provider %s) doesn't implement self_test\n",
1864                        prov->name);
1865     } OSSL_TRACE_END(PROVIDER);
1866 #endif
1867     if (ret == 0)
1868         (void)provider_remove_store_methods((OSSL_PROVIDER *)prov);
1869     return ret;
1870 }
1871 
1872 /**
1873  * @brief Retrieves capabilities from the given provider.
1874  *
1875  * This function calls the `get_capabilities` callback of the specified provider
1876  * to retrieve capabilities information. The callback is invoked with the
1877  * provider context, capability name, a callback function, and an argument.
1878  *
1879  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1880  * @param capability String representing the capability to be retrieved.
1881  * @param cb Callback function to process the capability data.
1882  * @param arg Argument to be passed to the callback function.
1883  *
1884  * @return 1 if the capabilities are successfully retrieved or if the callback
1885  *         is not defined, otherwise the value returned by `get_capabilities`.
1886  *
1887  * If tracing is enabled, a message is printed indicating the requested
1888  * capabilities.
1889  */
ossl_provider_random_bytes(const OSSL_PROVIDER * prov,int which,void * buf,size_t n,unsigned int strength)1890 int ossl_provider_random_bytes(const OSSL_PROVIDER *prov, int which,
1891                                void *buf, size_t n, unsigned int strength)
1892 {
1893     return prov->random_bytes == NULL ? 0
1894                                       : prov->random_bytes(prov->provctx, which,
1895                                                            buf, n, strength);
1896 }
1897 
ossl_provider_get_capabilities(const OSSL_PROVIDER * prov,const char * capability,OSSL_CALLBACK * cb,void * arg)1898 int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
1899                                    const char *capability,
1900                                    OSSL_CALLBACK *cb,
1901                                    void *arg)
1902 {
1903     if (prov->get_capabilities != NULL) {
1904 #ifndef FIPS_MODULE
1905         OSSL_TRACE_BEGIN(PROVIDER) {
1906             BIO_printf(trc_out,
1907                        "(provider %s) Calling get_capabilities "
1908                        "with capabilities %s\n", prov->name,
1909                        capability == NULL ? "none" : capability);
1910         } OSSL_TRACE_END(PROVIDER);
1911 #endif
1912         return prov->get_capabilities(prov->provctx, capability, cb, arg);
1913     }
1914     return 1;
1915 }
1916 
1917 /**
1918  * @brief Queries the provider for available algorithms for a given operation.
1919  *
1920  * This function calls the `query_operation` callback of the specified provider
1921  * to obtain a list of algorithms that can perform the given operation. It may
1922  * also set a flag indicating whether the result should be cached.
1923  *
1924  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1925  * @param operation_id Identifier of the operation to query.
1926  * @param no_cache Pointer to an integer flag to indicate whether caching is allowed.
1927  *
1928  * @return Pointer to an array of OSSL_ALGORITHM structures representing the
1929  *         available algorithms, or NULL if the callback is not defined or
1930  *         there are no available algorithms.
1931  *
1932  * If tracing is enabled, the available algorithms and their properties are
1933  * printed for debugging.
1934  */
ossl_provider_query_operation(const OSSL_PROVIDER * prov,int operation_id,int * no_cache)1935 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
1936                                                     int operation_id,
1937                                                     int *no_cache)
1938 {
1939     const OSSL_ALGORITHM *res;
1940 
1941     if (prov->query_operation == NULL) {
1942 #ifndef FIPS_MODULE
1943         OSSL_TRACE_BEGIN(PROVIDER) {
1944             BIO_printf(trc_out, "provider %s lacks query operation!\n",
1945                        prov->name);
1946         } OSSL_TRACE_END(PROVIDER);
1947 #endif
1948         return NULL;
1949     }
1950 
1951     res = prov->query_operation(prov->provctx, operation_id, no_cache);
1952 #ifndef FIPS_MODULE
1953     OSSL_TRACE_BEGIN(PROVIDER) {
1954         const OSSL_ALGORITHM *idx;
1955         if (res != NULL) {
1956             BIO_printf(trc_out,
1957                        "(provider %s) Calling query, available algs are:\n", prov->name);
1958 
1959             for (idx = res; idx->algorithm_names != NULL; idx++) {
1960                 BIO_printf(trc_out,
1961                            "(provider %s) names %s, prop_def %s, desc %s\n",
1962                            prov->name,
1963                            idx->algorithm_names == NULL ? "none" :
1964                            idx->algorithm_names,
1965                            idx->property_definition == NULL ? "none" :
1966                            idx->property_definition,
1967                            idx->algorithm_description == NULL ? "none" :
1968                            idx->algorithm_description);
1969             }
1970         } else {
1971             BIO_printf(trc_out, "(provider %s) query_operation failed\n", prov->name);
1972         }
1973     } OSSL_TRACE_END(PROVIDER);
1974 #endif
1975 
1976 #if defined(OPENSSL_NO_CACHED_FETCH)
1977     /* Forcing the non-caching of queries */
1978     if (no_cache != NULL)
1979         *no_cache = 1;
1980 #endif
1981     return res;
1982 }
1983 
1984 /**
1985  * @brief Releases resources associated with a queried operation.
1986  *
1987  * This function calls the `unquery_operation` callback of the specified
1988  * provider to release any resources related to a previously queried operation.
1989  *
1990  * @param prov Pointer to the OSSL_PROVIDER structure representing the provider.
1991  * @param operation_id Identifier of the operation to unquery.
1992  * @param algs Pointer to the OSSL_ALGORITHM structures representing the
1993  *             algorithms associated with the operation.
1994  *
1995  * If tracing is enabled, a message is printed indicating that the operation
1996  * is being unqueried.
1997  */
ossl_provider_unquery_operation(const OSSL_PROVIDER * prov,int operation_id,const OSSL_ALGORITHM * algs)1998 void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
1999                                      int operation_id,
2000                                      const OSSL_ALGORITHM *algs)
2001 {
2002     if (prov->unquery_operation != NULL) {
2003 #ifndef FIPS_MODULE
2004         OSSL_TRACE_BEGIN(PROVIDER) {
2005             BIO_printf(trc_out,
2006                        "(provider %s) Calling unquery"
2007                        " with operation %d\n",
2008                        prov->name,
2009                        operation_id);
2010         } OSSL_TRACE_END(PROVIDER);
2011 #endif
2012         prov->unquery_operation(prov->provctx, operation_id, algs);
2013     }
2014 }
2015 
ossl_provider_set_operation_bit(OSSL_PROVIDER * provider,size_t bitnum)2016 int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum)
2017 {
2018     size_t byte = bitnum / 8;
2019     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
2020 
2021     if (!CRYPTO_THREAD_write_lock(provider->opbits_lock))
2022         return 0;
2023     if (provider->operation_bits_sz <= byte) {
2024         unsigned char *tmp = OPENSSL_realloc(provider->operation_bits,
2025                                              byte + 1);
2026 
2027         if (tmp == NULL) {
2028             CRYPTO_THREAD_unlock(provider->opbits_lock);
2029             return 0;
2030         }
2031         provider->operation_bits = tmp;
2032         memset(provider->operation_bits + provider->operation_bits_sz,
2033                '\0', byte + 1 - provider->operation_bits_sz);
2034         provider->operation_bits_sz = byte + 1;
2035     }
2036     provider->operation_bits[byte] |= bit;
2037     CRYPTO_THREAD_unlock(provider->opbits_lock);
2038     return 1;
2039 }
2040 
ossl_provider_test_operation_bit(OSSL_PROVIDER * provider,size_t bitnum,int * result)2041 int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
2042                                      int *result)
2043 {
2044     size_t byte = bitnum / 8;
2045     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
2046 
2047     if (!ossl_assert(result != NULL)) {
2048         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
2049         return 0;
2050     }
2051 
2052     *result = 0;
2053     if (!CRYPTO_THREAD_read_lock(provider->opbits_lock))
2054         return 0;
2055     if (provider->operation_bits_sz > byte)
2056         *result = ((provider->operation_bits[byte] & bit) != 0);
2057     CRYPTO_THREAD_unlock(provider->opbits_lock);
2058     return 1;
2059 }
2060 
2061 #ifndef FIPS_MODULE
ossl_provider_get_parent(OSSL_PROVIDER * prov)2062 const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov)
2063 {
2064     return prov->handle;
2065 }
2066 
ossl_provider_is_child(const OSSL_PROVIDER * prov)2067 int ossl_provider_is_child(const OSSL_PROVIDER *prov)
2068 {
2069     return prov->ischild;
2070 }
2071 
ossl_provider_set_child(OSSL_PROVIDER * prov,const OSSL_CORE_HANDLE * handle)2072 int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle)
2073 {
2074     prov->handle = handle;
2075     prov->ischild = 1;
2076 
2077     return 1;
2078 }
2079 
ossl_provider_default_props_update(OSSL_LIB_CTX * libctx,const char * props)2080 int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props)
2081 {
2082 #ifndef FIPS_MODULE
2083     struct provider_store_st *store = NULL;
2084     int i, max;
2085     OSSL_PROVIDER_CHILD_CB *child_cb;
2086 
2087     if ((store = get_provider_store(libctx)) == NULL)
2088         return 0;
2089 
2090     if (!CRYPTO_THREAD_read_lock(store->lock))
2091         return 0;
2092 
2093     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
2094     for (i = 0; i < max; i++) {
2095         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
2096         child_cb->global_props_cb(props, child_cb->cbdata);
2097     }
2098 
2099     CRYPTO_THREAD_unlock(store->lock);
2100 #endif
2101     return 1;
2102 }
2103 
ossl_provider_register_child_cb(const OSSL_CORE_HANDLE * handle,int (* create_cb)(const OSSL_CORE_HANDLE * provider,void * cbdata),int (* remove_cb)(const OSSL_CORE_HANDLE * provider,void * cbdata),int (* global_props_cb)(const char * props,void * cbdata),void * cbdata)2104 static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle,
2105                                            int (*create_cb)(
2106                                                const OSSL_CORE_HANDLE *provider,
2107                                                void *cbdata),
2108                                            int (*remove_cb)(
2109                                                const OSSL_CORE_HANDLE *provider,
2110                                                void *cbdata),
2111                                            int (*global_props_cb)(
2112                                                const char *props,
2113                                                void *cbdata),
2114                                            void *cbdata)
2115 {
2116     /*
2117      * This is really an OSSL_PROVIDER that we created and cast to
2118      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
2119      */
2120     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
2121     OSSL_PROVIDER *prov;
2122     OSSL_LIB_CTX *libctx = thisprov->libctx;
2123     struct provider_store_st *store = NULL;
2124     int ret = 0, i, max;
2125     OSSL_PROVIDER_CHILD_CB *child_cb;
2126     char *propsstr = NULL;
2127 
2128     if ((store = get_provider_store(libctx)) == NULL)
2129         return 0;
2130 
2131     child_cb = OPENSSL_malloc(sizeof(*child_cb));
2132     if (child_cb == NULL)
2133         return 0;
2134     child_cb->prov = thisprov;
2135     child_cb->create_cb = create_cb;
2136     child_cb->remove_cb = remove_cb;
2137     child_cb->global_props_cb = global_props_cb;
2138     child_cb->cbdata = cbdata;
2139 
2140     if (!CRYPTO_THREAD_write_lock(store->lock)) {
2141         OPENSSL_free(child_cb);
2142         return 0;
2143     }
2144     propsstr = evp_get_global_properties_str(libctx, 0);
2145 
2146     if (propsstr != NULL) {
2147         global_props_cb(propsstr, cbdata);
2148         OPENSSL_free(propsstr);
2149     }
2150     max = sk_OSSL_PROVIDER_num(store->providers);
2151     for (i = 0; i < max; i++) {
2152         int activated;
2153 
2154         prov = sk_OSSL_PROVIDER_value(store->providers, i);
2155 
2156         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
2157             break;
2158         activated = prov->flag_activated;
2159         CRYPTO_THREAD_unlock(prov->flag_lock);
2160         /*
2161          * We hold the store lock while calling the user callback. This means
2162          * that the user callback must be short and simple and not do anything
2163          * likely to cause a deadlock. We don't hold the flag_lock during this
2164          * call. In theory this means that another thread could deactivate it
2165          * while we are calling create. This is ok because the other thread
2166          * will also call remove_cb, but won't be able to do so until we release
2167          * the store lock.
2168          */
2169         if (activated && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata))
2170             break;
2171     }
2172     if (i == max) {
2173         /* Success */
2174         ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb);
2175     }
2176     if (i != max || ret <= 0) {
2177         /* Failed during creation. Remove everything we just added */
2178         for (; i >= 0; i--) {
2179             prov = sk_OSSL_PROVIDER_value(store->providers, i);
2180             remove_cb((OSSL_CORE_HANDLE *)prov, cbdata);
2181         }
2182         OPENSSL_free(child_cb);
2183         ret = 0;
2184     }
2185     CRYPTO_THREAD_unlock(store->lock);
2186 
2187     return ret;
2188 }
2189 
ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE * handle)2190 static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle)
2191 {
2192     /*
2193      * This is really an OSSL_PROVIDER that we created and cast to
2194      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
2195      */
2196     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
2197     OSSL_LIB_CTX *libctx = thisprov->libctx;
2198     struct provider_store_st *store = NULL;
2199     int i, max;
2200     OSSL_PROVIDER_CHILD_CB *child_cb;
2201 
2202     if ((store = get_provider_store(libctx)) == NULL)
2203         return;
2204 
2205     if (!CRYPTO_THREAD_write_lock(store->lock))
2206         return;
2207     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
2208     for (i = 0; i < max; i++) {
2209         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
2210         if (child_cb->prov == thisprov) {
2211             /* Found an entry */
2212             sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i);
2213             OPENSSL_free(child_cb);
2214             break;
2215         }
2216     }
2217     CRYPTO_THREAD_unlock(store->lock);
2218 }
2219 #endif
2220 
2221 /*-
2222  * Core functions for the provider
2223  * ===============================
2224  *
2225  * This is the set of functions that the core makes available to the provider
2226  */
2227 
2228 /*
2229  * This returns a list of Provider Object parameters with their types, for
2230  * discovery.  We do not expect that many providers will use this, but one
2231  * never knows.
2232  */
2233 static const OSSL_PARAM param_types[] = {
2234     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
2235     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR,
2236                     NULL, 0),
2237 #ifndef FIPS_MODULE
2238     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR,
2239                     NULL, 0),
2240 #endif
2241     OSSL_PARAM_END
2242 };
2243 
2244 /*
2245  * Forward declare all the functions that are provided aa dispatch.
2246  * This ensures that the compiler will complain if they aren't defined
2247  * with the correct signature.
2248  */
2249 static OSSL_FUNC_core_gettable_params_fn core_gettable_params;
2250 static OSSL_FUNC_core_get_params_fn core_get_params;
2251 static OSSL_FUNC_core_get_libctx_fn core_get_libctx;
2252 static OSSL_FUNC_core_thread_start_fn core_thread_start;
2253 #ifndef FIPS_MODULE
2254 static OSSL_FUNC_core_new_error_fn core_new_error;
2255 static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug;
2256 static OSSL_FUNC_core_vset_error_fn core_vset_error;
2257 static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark;
2258 static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark;
2259 static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark;
2260 OSSL_FUNC_BIO_new_file_fn ossl_core_bio_new_file;
2261 OSSL_FUNC_BIO_new_membuf_fn ossl_core_bio_new_mem_buf;
2262 OSSL_FUNC_BIO_read_ex_fn ossl_core_bio_read_ex;
2263 OSSL_FUNC_BIO_write_ex_fn ossl_core_bio_write_ex;
2264 OSSL_FUNC_BIO_gets_fn ossl_core_bio_gets;
2265 OSSL_FUNC_BIO_puts_fn ossl_core_bio_puts;
2266 OSSL_FUNC_BIO_up_ref_fn ossl_core_bio_up_ref;
2267 OSSL_FUNC_BIO_free_fn ossl_core_bio_free;
2268 OSSL_FUNC_BIO_vprintf_fn ossl_core_bio_vprintf;
2269 OSSL_FUNC_BIO_vsnprintf_fn BIO_vsnprintf;
2270 static OSSL_FUNC_indicator_cb_fn core_indicator_get_callback;
2271 static OSSL_FUNC_self_test_cb_fn core_self_test_get_callback;
2272 static OSSL_FUNC_get_entropy_fn rand_get_entropy;
2273 static OSSL_FUNC_get_user_entropy_fn rand_get_user_entropy;
2274 static OSSL_FUNC_cleanup_entropy_fn rand_cleanup_entropy;
2275 static OSSL_FUNC_cleanup_user_entropy_fn rand_cleanup_user_entropy;
2276 static OSSL_FUNC_get_nonce_fn rand_get_nonce;
2277 static OSSL_FUNC_get_user_nonce_fn rand_get_user_nonce;
2278 static OSSL_FUNC_cleanup_nonce_fn rand_cleanup_nonce;
2279 static OSSL_FUNC_cleanup_user_nonce_fn rand_cleanup_user_nonce;
2280 #endif
2281 OSSL_FUNC_CRYPTO_malloc_fn CRYPTO_malloc;
2282 OSSL_FUNC_CRYPTO_zalloc_fn CRYPTO_zalloc;
2283 OSSL_FUNC_CRYPTO_free_fn CRYPTO_free;
2284 OSSL_FUNC_CRYPTO_clear_free_fn CRYPTO_clear_free;
2285 OSSL_FUNC_CRYPTO_realloc_fn CRYPTO_realloc;
2286 OSSL_FUNC_CRYPTO_clear_realloc_fn CRYPTO_clear_realloc;
2287 OSSL_FUNC_CRYPTO_secure_malloc_fn CRYPTO_secure_malloc;
2288 OSSL_FUNC_CRYPTO_secure_zalloc_fn CRYPTO_secure_zalloc;
2289 OSSL_FUNC_CRYPTO_secure_free_fn CRYPTO_secure_free;
2290 OSSL_FUNC_CRYPTO_secure_clear_free_fn CRYPTO_secure_clear_free;
2291 OSSL_FUNC_CRYPTO_secure_allocated_fn CRYPTO_secure_allocated;
2292 OSSL_FUNC_OPENSSL_cleanse_fn OPENSSL_cleanse;
2293 #ifndef FIPS_MODULE
2294 OSSL_FUNC_provider_register_child_cb_fn ossl_provider_register_child_cb;
2295 OSSL_FUNC_provider_deregister_child_cb_fn ossl_provider_deregister_child_cb;
2296 static OSSL_FUNC_provider_name_fn core_provider_get0_name;
2297 static OSSL_FUNC_provider_get0_provider_ctx_fn core_provider_get0_provider_ctx;
2298 static OSSL_FUNC_provider_get0_dispatch_fn core_provider_get0_dispatch;
2299 static OSSL_FUNC_provider_up_ref_fn core_provider_up_ref_intern;
2300 static OSSL_FUNC_provider_free_fn core_provider_free_intern;
2301 static OSSL_FUNC_core_obj_add_sigid_fn core_obj_add_sigid;
2302 static OSSL_FUNC_core_obj_create_fn core_obj_create;
2303 #endif
2304 
core_gettable_params(const OSSL_CORE_HANDLE * handle)2305 static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle)
2306 {
2307     return param_types;
2308 }
2309 
core_get_params(const OSSL_CORE_HANDLE * handle,OSSL_PARAM params[])2310 static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[])
2311 {
2312     OSSL_PARAM *p;
2313     /*
2314      * We created this object originally and we know it is actually an
2315      * OSSL_PROVIDER *, so the cast is safe
2316      */
2317     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
2318 
2319     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL)
2320         OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
2321     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL)
2322         OSSL_PARAM_set_utf8_ptr(p, prov->name);
2323 
2324 #ifndef FIPS_MODULE
2325     if ((p = OSSL_PARAM_locate(params,
2326                                OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL)
2327         OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov));
2328 #endif
2329 
2330     return OSSL_PROVIDER_get_conf_parameters(prov, params);
2331 }
2332 
core_get_libctx(const OSSL_CORE_HANDLE * handle)2333 static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle)
2334 {
2335     /*
2336      * We created this object originally and we know it is actually an
2337      * OSSL_PROVIDER *, so the cast is safe
2338      */
2339     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
2340 
2341     /*
2342      * Using ossl_provider_libctx would be wrong as that returns
2343      * NULL for |prov| == NULL and NULL libctx has a special meaning
2344      * that does not apply here. Here |prov| == NULL can happen only in
2345      * case of a coding error.
2346      */
2347     assert(prov != NULL);
2348     return (OPENSSL_CORE_CTX *)prov->libctx;
2349 }
2350 
core_thread_start(const OSSL_CORE_HANDLE * handle,OSSL_thread_stop_handler_fn handfn,void * arg)2351 static int core_thread_start(const OSSL_CORE_HANDLE *handle,
2352                              OSSL_thread_stop_handler_fn handfn,
2353                              void *arg)
2354 {
2355     /*
2356      * We created this object originally and we know it is actually an
2357      * OSSL_PROVIDER *, so the cast is safe
2358      */
2359     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
2360 
2361     return ossl_init_thread_start(prov, arg, handfn);
2362 }
2363 
2364 /*
2365  * The FIPS module inner provider doesn't implement these.  They aren't
2366  * needed there, since the FIPS module upcalls are always the outer provider
2367  * ones.
2368  */
2369 #ifndef FIPS_MODULE
2370 /*
2371  * These error functions should use |handle| to select the proper
2372  * library context to report in the correct error stack if error
2373  * stacks become tied to the library context.
2374  * We cannot currently do that since there's no support for it in the
2375  * ERR subsystem.
2376  */
core_new_error(const OSSL_CORE_HANDLE * handle)2377 static void core_new_error(const OSSL_CORE_HANDLE *handle)
2378 {
2379     ERR_new();
2380 }
2381 
core_set_error_debug(const OSSL_CORE_HANDLE * handle,const char * file,int line,const char * func)2382 static void core_set_error_debug(const OSSL_CORE_HANDLE *handle,
2383                                  const char *file, int line, const char *func)
2384 {
2385     ERR_set_debug(file, line, func);
2386 }
2387 
core_vset_error(const OSSL_CORE_HANDLE * handle,uint32_t reason,const char * fmt,va_list args)2388 static void core_vset_error(const OSSL_CORE_HANDLE *handle,
2389                             uint32_t reason, const char *fmt, va_list args)
2390 {
2391     /*
2392      * We created this object originally and we know it is actually an
2393      * OSSL_PROVIDER *, so the cast is safe
2394      */
2395     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
2396 
2397     /*
2398      * If the uppermost 8 bits are non-zero, it's an OpenSSL library
2399      * error and will be treated as such.  Otherwise, it's a new style
2400      * provider error and will be treated as such.
2401      */
2402     if (ERR_GET_LIB(reason) != 0) {
2403         ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args);
2404     } else {
2405         ERR_vset_error(prov->error_lib, (int)reason, fmt, args);
2406     }
2407 }
2408 
core_set_error_mark(const OSSL_CORE_HANDLE * handle)2409 static int core_set_error_mark(const OSSL_CORE_HANDLE *handle)
2410 {
2411     return ERR_set_mark();
2412 }
2413 
core_clear_last_error_mark(const OSSL_CORE_HANDLE * handle)2414 static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle)
2415 {
2416     return ERR_clear_last_mark();
2417 }
2418 
core_pop_error_to_mark(const OSSL_CORE_HANDLE * handle)2419 static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle)
2420 {
2421     return ERR_pop_to_mark();
2422 }
2423 
core_count_to_mark(const OSSL_CORE_HANDLE * handle)2424 static int core_count_to_mark(const OSSL_CORE_HANDLE *handle)
2425 {
2426     return ERR_count_to_mark();
2427 }
2428 
core_indicator_get_callback(OPENSSL_CORE_CTX * libctx,OSSL_INDICATOR_CALLBACK ** cb)2429 static void core_indicator_get_callback(OPENSSL_CORE_CTX *libctx,
2430                                         OSSL_INDICATOR_CALLBACK **cb)
2431 {
2432     OSSL_INDICATOR_get_callback((OSSL_LIB_CTX *)libctx, cb);
2433 }
2434 
core_self_test_get_callback(OPENSSL_CORE_CTX * libctx,OSSL_CALLBACK ** cb,void ** cbarg)2435 static void core_self_test_get_callback(OPENSSL_CORE_CTX *libctx,
2436                                         OSSL_CALLBACK **cb, void **cbarg)
2437 {
2438     OSSL_SELF_TEST_get_callback((OSSL_LIB_CTX *)libctx, cb, cbarg);
2439 }
2440 
2441 # ifdef OPENSSL_NO_FIPS_JITTER
rand_get_entropy(const OSSL_CORE_HANDLE * handle,unsigned char ** pout,int entropy,size_t min_len,size_t max_len)2442 static size_t rand_get_entropy(const OSSL_CORE_HANDLE *handle,
2443                                unsigned char **pout, int entropy,
2444                                size_t min_len, size_t max_len)
2445 {
2446     return ossl_rand_get_entropy((OSSL_LIB_CTX *)core_get_libctx(handle),
2447                                  pout, entropy, min_len, max_len);
2448 }
2449 # else
2450 /*
2451  * OpenSSL FIPS providers prior to 3.2 call rand_get_entropy API from
2452  * core, instead of the newer get_user_entropy. Newer API call honors
2453  * runtime configuration of random seed source and can be configured
2454  * to use os getranom() or another seed source, such as
2455  * JITTER. However, 3.0.9 only calls this API. Note that no other
2456  * providers known to use this, and it is core <-> provider only
2457  * API. Public facing EVP and getrandom bytes already correctly honor
2458  * runtime configuration for seed source. There are no other providers
2459  * packaged in Wolfi, or even known to exist that use this api. Thus
2460  * it is safe to say any caller of this API is in fact 3.0.9 FIPS
2461  * provider. Also note that the passed in handle is invalid and cannot
2462  * be safely dereferences in such cases. Due to a bug in FIPS
2463  * providers 3.0.0, 3.0.8 and 3.0.9. See
2464  * https://github.com/openssl/openssl/blob/master/doc/internal/man3/ossl_rand_get_entropy.pod#notes
2465  */
2466 size_t ossl_rand_jitter_get_seed(unsigned char **, int, size_t, size_t);
rand_get_entropy(const OSSL_CORE_HANDLE * handle,unsigned char ** pout,int entropy,size_t min_len,size_t max_len)2467 static size_t rand_get_entropy(const OSSL_CORE_HANDLE *handle,
2468                                unsigned char **pout, int entropy,
2469                                size_t min_len, size_t max_len)
2470 {
2471     return ossl_rand_jitter_get_seed(pout, entropy, min_len, max_len);
2472 }
2473 # endif
2474 
rand_get_user_entropy(const OSSL_CORE_HANDLE * handle,unsigned char ** pout,int entropy,size_t min_len,size_t max_len)2475 static size_t rand_get_user_entropy(const OSSL_CORE_HANDLE *handle,
2476                                     unsigned char **pout, int entropy,
2477                                     size_t min_len, size_t max_len)
2478 {
2479     return ossl_rand_get_user_entropy((OSSL_LIB_CTX *)core_get_libctx(handle),
2480                                       pout, entropy, min_len, max_len);
2481 }
2482 
rand_cleanup_entropy(const OSSL_CORE_HANDLE * handle,unsigned char * buf,size_t len)2483 static void rand_cleanup_entropy(const OSSL_CORE_HANDLE *handle,
2484                                  unsigned char *buf, size_t len)
2485 {
2486     ossl_rand_cleanup_entropy((OSSL_LIB_CTX *)core_get_libctx(handle),
2487                               buf, len);
2488 }
2489 
rand_cleanup_user_entropy(const OSSL_CORE_HANDLE * handle,unsigned char * buf,size_t len)2490 static void rand_cleanup_user_entropy(const OSSL_CORE_HANDLE *handle,
2491                                       unsigned char *buf, size_t len)
2492 {
2493     ossl_rand_cleanup_user_entropy((OSSL_LIB_CTX *)core_get_libctx(handle),
2494                                    buf, len);
2495 }
2496 
rand_get_nonce(const OSSL_CORE_HANDLE * handle,unsigned char ** pout,size_t min_len,size_t max_len,const void * salt,size_t salt_len)2497 static size_t rand_get_nonce(const OSSL_CORE_HANDLE *handle,
2498                              unsigned char **pout,
2499                              size_t min_len, size_t max_len,
2500                              const void *salt, size_t salt_len)
2501 {
2502     return ossl_rand_get_nonce((OSSL_LIB_CTX *)core_get_libctx(handle),
2503                                pout, min_len, max_len, salt, salt_len);
2504 }
2505 
rand_get_user_nonce(const OSSL_CORE_HANDLE * handle,unsigned char ** pout,size_t min_len,size_t max_len,const void * salt,size_t salt_len)2506 static size_t rand_get_user_nonce(const OSSL_CORE_HANDLE *handle,
2507                                   unsigned char **pout,
2508                                   size_t min_len, size_t max_len,
2509                                   const void *salt, size_t salt_len)
2510 {
2511     return ossl_rand_get_user_nonce((OSSL_LIB_CTX *)core_get_libctx(handle),
2512                                     pout, min_len, max_len, salt, salt_len);
2513 }
2514 
rand_cleanup_nonce(const OSSL_CORE_HANDLE * handle,unsigned char * buf,size_t len)2515 static void rand_cleanup_nonce(const OSSL_CORE_HANDLE *handle,
2516                                unsigned char *buf, size_t len)
2517 {
2518     ossl_rand_cleanup_nonce((OSSL_LIB_CTX *)core_get_libctx(handle),
2519                             buf, len);
2520 }
2521 
rand_cleanup_user_nonce(const OSSL_CORE_HANDLE * handle,unsigned char * buf,size_t len)2522 static void rand_cleanup_user_nonce(const OSSL_CORE_HANDLE *handle,
2523                                unsigned char *buf, size_t len)
2524 {
2525     ossl_rand_cleanup_user_nonce((OSSL_LIB_CTX *)core_get_libctx(handle),
2526                                  buf, len);
2527 }
2528 
core_provider_get0_name(const OSSL_CORE_HANDLE * prov)2529 static const char *core_provider_get0_name(const OSSL_CORE_HANDLE *prov)
2530 {
2531     return OSSL_PROVIDER_get0_name((const OSSL_PROVIDER *)prov);
2532 }
2533 
core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE * prov)2534 static void *core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE *prov)
2535 {
2536     return OSSL_PROVIDER_get0_provider_ctx((const OSSL_PROVIDER *)prov);
2537 }
2538 
2539 static const OSSL_DISPATCH *
core_provider_get0_dispatch(const OSSL_CORE_HANDLE * prov)2540 core_provider_get0_dispatch(const OSSL_CORE_HANDLE *prov)
2541 {
2542     return OSSL_PROVIDER_get0_dispatch((const OSSL_PROVIDER *)prov);
2543 }
2544 
core_provider_up_ref_intern(const OSSL_CORE_HANDLE * prov,int activate)2545 static int core_provider_up_ref_intern(const OSSL_CORE_HANDLE *prov,
2546                                        int activate)
2547 {
2548     return provider_up_ref_intern((OSSL_PROVIDER *)prov, activate);
2549 }
2550 
core_provider_free_intern(const OSSL_CORE_HANDLE * prov,int deactivate)2551 static int core_provider_free_intern(const OSSL_CORE_HANDLE *prov,
2552                                      int deactivate)
2553 {
2554     return provider_free_intern((OSSL_PROVIDER *)prov, deactivate);
2555 }
2556 
core_obj_add_sigid(const OSSL_CORE_HANDLE * prov,const char * sign_name,const char * digest_name,const char * pkey_name)2557 static int core_obj_add_sigid(const OSSL_CORE_HANDLE *prov,
2558                               const char *sign_name, const char *digest_name,
2559                               const char *pkey_name)
2560 {
2561     int sign_nid = OBJ_txt2nid(sign_name);
2562     int digest_nid = NID_undef;
2563     int pkey_nid = OBJ_txt2nid(pkey_name);
2564 
2565     if (digest_name != NULL && digest_name[0] != '\0'
2566         && (digest_nid = OBJ_txt2nid(digest_name)) == NID_undef)
2567             return 0;
2568 
2569     if (sign_nid == NID_undef)
2570         return 0;
2571 
2572     /*
2573      * Check if it already exists. This is a success if so (even if we don't
2574      * have nids for the digest/pkey)
2575      */
2576     if (OBJ_find_sigid_algs(sign_nid, NULL, NULL))
2577         return 1;
2578 
2579     if (pkey_nid == NID_undef)
2580         return 0;
2581 
2582     return OBJ_add_sigid(sign_nid, digest_nid, pkey_nid);
2583 }
2584 
core_obj_create(const OSSL_CORE_HANDLE * prov,const char * oid,const char * sn,const char * ln)2585 static int core_obj_create(const OSSL_CORE_HANDLE *prov, const char *oid,
2586                            const char *sn, const char *ln)
2587 {
2588     /* Check if it already exists and create it if not */
2589     return OBJ_txt2nid(oid) != NID_undef
2590            || OBJ_create(oid, sn, ln) != NID_undef;
2591 }
2592 #endif /* FIPS_MODULE */
2593 
2594 /*
2595  * Functions provided by the core.
2596  */
2597 static const OSSL_DISPATCH core_dispatch_[] = {
2598     { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params },
2599     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
2600     { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx },
2601     { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start },
2602 #ifndef FIPS_MODULE
2603     { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error },
2604     { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug },
2605     { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error },
2606     { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark },
2607     { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK,
2608       (void (*)(void))core_clear_last_error_mark },
2609     { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark },
2610     { OSSL_FUNC_CORE_COUNT_TO_MARK, (void (*)(void))core_count_to_mark },
2611     { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file },
2612     { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf },
2613     { OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex },
2614     { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex },
2615     { OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets },
2616     { OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts },
2617     { OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl },
2618     { OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref },
2619     { OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free },
2620     { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf },
2621     { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf },
2622     { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))core_self_test_get_callback },
2623     { OSSL_FUNC_INDICATOR_CB, (void (*)(void))core_indicator_get_callback },
2624     { OSSL_FUNC_GET_ENTROPY, (void (*)(void))rand_get_entropy },
2625     { OSSL_FUNC_GET_USER_ENTROPY, (void (*)(void))rand_get_user_entropy },
2626     { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))rand_cleanup_entropy },
2627     { OSSL_FUNC_CLEANUP_USER_ENTROPY, (void (*)(void))rand_cleanup_user_entropy },
2628     { OSSL_FUNC_GET_NONCE, (void (*)(void))rand_get_nonce },
2629     { OSSL_FUNC_GET_USER_NONCE, (void (*)(void))rand_get_user_nonce },
2630     { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))rand_cleanup_nonce },
2631     { OSSL_FUNC_CLEANUP_USER_NONCE, (void (*)(void))rand_cleanup_user_nonce },
2632 #endif
2633     { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc },
2634     { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc },
2635     { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free },
2636     { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free },
2637     { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc },
2638     { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc },
2639     { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc },
2640     { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc },
2641     { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free },
2642     { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE,
2643         (void (*)(void))CRYPTO_secure_clear_free },
2644     { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED,
2645         (void (*)(void))CRYPTO_secure_allocated },
2646     { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse },
2647 #ifndef FIPS_MODULE
2648     { OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB,
2649         (void (*)(void))ossl_provider_register_child_cb },
2650     { OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB,
2651         (void (*)(void))ossl_provider_deregister_child_cb },
2652     { OSSL_FUNC_PROVIDER_NAME,
2653         (void (*)(void))core_provider_get0_name },
2654     { OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX,
2655         (void (*)(void))core_provider_get0_provider_ctx },
2656     { OSSL_FUNC_PROVIDER_GET0_DISPATCH,
2657         (void (*)(void))core_provider_get0_dispatch },
2658     { OSSL_FUNC_PROVIDER_UP_REF,
2659         (void (*)(void))core_provider_up_ref_intern },
2660     { OSSL_FUNC_PROVIDER_FREE,
2661         (void (*)(void))core_provider_free_intern },
2662     { OSSL_FUNC_CORE_OBJ_ADD_SIGID, (void (*)(void))core_obj_add_sigid },
2663     { OSSL_FUNC_CORE_OBJ_CREATE, (void (*)(void))core_obj_create },
2664 #endif
2665     OSSL_DISPATCH_END
2666 };
2667 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;
2668