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