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