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