627ff384e1406f40e7216850459aa99e03b0759f
[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 <openssl/core.h>
11 #include <openssl/core_dispatch.h>
12 #include <openssl/core_names.h>
13 #include <openssl/provider.h>
14 #include <openssl/params.h>
15 #include <openssl/opensslv.h>
16 #include "crypto/cryptlib.h"
17 #include "crypto/evp.h" /* evp_method_store_flush */
18 #include "crypto/rand.h"
19 #include "internal/nelem.h"
20 #include "internal/thread_once.h"
21 #include "internal/provider.h"
22 #include "internal/refcount.h"
23 #include "provider_local.h"
24 #ifndef FIPS_MODULE
25 # include <openssl/self_test.h>
26 #endif
27
28 static OSSL_PROVIDER *provider_new(const char *name,
29                                    OSSL_provider_init_fn *init_function);
30
31 /*-
32  * Provider Object structure
33  * =========================
34  */
35
36 typedef struct {
37     char *name;
38     char *value;
39 } INFOPAIR;
40 DEFINE_STACK_OF(INFOPAIR)
41
42 struct provider_store_st;        /* Forward declaration */
43
44 struct ossl_provider_st {
45     /* Flag bits */
46     unsigned int flag_initialized:1;
47     unsigned int flag_activated:1;
48     unsigned int flag_fallback:1; /* Can be used as fallback */
49     unsigned int flag_activated_as_fallback:1;
50
51     /* OpenSSL library side data */
52     CRYPTO_REF_COUNT refcnt;
53     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
54     CRYPTO_REF_COUNT activatecnt;
55     CRYPTO_RWLOCK *activatecnt_lock; /* For the activate counter */
56     char *name;
57     char *path;
58     DSO *module;
59     OSSL_provider_init_fn *init_function;
60     STACK_OF(INFOPAIR) *parameters;
61     OSSL_LIB_CTX *libctx; /* The library context this instance is in */
62     struct provider_store_st *store; /* The store this instance belongs to */
63 #ifndef FIPS_MODULE
64     /*
65      * In the FIPS module inner provider, this isn't needed, since the
66      * error upcalls are always direct calls to the outer provider.
67      */
68     int error_lib;     /* ERR library number, one for each provider */
69 # ifndef OPENSSL_NO_ERR
70     ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */
71 # endif
72 #endif
73
74     /* Provider side functions */
75     OSSL_FUNC_provider_teardown_fn *teardown;
76     OSSL_FUNC_provider_gettable_params_fn *gettable_params;
77     OSSL_FUNC_provider_get_params_fn *get_params;
78     OSSL_FUNC_provider_get_capabilities_fn *get_capabilities;
79     OSSL_FUNC_provider_self_test_fn *self_test;
80     OSSL_FUNC_provider_query_operation_fn *query_operation;
81
82     /*
83      * Cache of bit to indicate of query_operation() has been called on
84      * a specific operation or not.
85      */
86     unsigned char *operation_bits;
87     size_t operation_bits_sz;
88     CRYPTO_RWLOCK *opbits_lock;
89
90     /* Provider side data */
91     void *provctx;
92 };
93 DEFINE_STACK_OF(OSSL_PROVIDER)
94
95 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
96                              const OSSL_PROVIDER * const *b)
97 {
98     return strcmp((*a)->name, (*b)->name);
99 }
100
101 /*-
102  * Provider Object store
103  * =====================
104  *
105  * The Provider Object store is a library context object, and therefore needs
106  * an index.
107  */
108
109 struct provider_store_st {
110     STACK_OF(OSSL_PROVIDER) *providers;
111     CRYPTO_RWLOCK *lock;
112     char *default_path;
113     unsigned int use_fallbacks:1;
114 };
115
116 /*
117  * provider_deactivate_free() is a wrapper around ossl_provider_deactivate()
118  * and ossl_provider_free(), called as needed.
119  * Since this is only called when the provider store is being emptied, we
120  * don't need to care about any lock.
121  */
122 static void provider_deactivate_free(OSSL_PROVIDER *prov)
123 {
124     if (prov->flag_activated)
125         ossl_provider_deactivate(prov);
126     ossl_provider_free(prov);
127 }
128
129 static void provider_store_free(void *vstore)
130 {
131     struct provider_store_st *store = vstore;
132
133     if (store == NULL)
134         return;
135     OPENSSL_free(store->default_path);
136     sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free);
137     CRYPTO_THREAD_lock_free(store->lock);
138     OPENSSL_free(store);
139 }
140
141 static void *provider_store_new(OSSL_LIB_CTX *ctx)
142 {
143     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
144     const struct predefined_providers_st *p = NULL;
145
146     if (store == NULL
147         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
148         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
149         provider_store_free(store);
150         return NULL;
151     }
152     store->use_fallbacks = 1;
153
154     for (p = predefined_providers; p->name != NULL; p++) {
155         OSSL_PROVIDER *prov = NULL;
156
157         /*
158          * We use the internal constructor directly here,
159          * otherwise we get a call loop
160          */
161         prov = provider_new(p->name, p->init);
162
163         if (prov == NULL
164             || sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
165             ossl_provider_free(prov);
166             provider_store_free(store);
167             ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
168             return NULL;
169         }
170         prov->libctx = ctx;
171         prov->store = store;
172 #ifndef FIPS_MODULE
173         prov->error_lib = ERR_get_next_error_library();
174 #endif
175         if(p->is_fallback)
176             ossl_provider_set_fallback(prov);
177     }
178
179     return store;
180 }
181
182 static const OSSL_LIB_CTX_METHOD provider_store_method = {
183     provider_store_new,
184     provider_store_free,
185 };
186
187 static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx)
188 {
189     struct provider_store_st *store = NULL;
190
191     store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX,
192                                   &provider_store_method);
193     if (store == NULL)
194         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
195     return store;
196 }
197
198 int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx)
199 {
200     struct provider_store_st *store;
201
202     if ((store = get_provider_store(libctx)) != NULL) {
203         store->use_fallbacks = 0;
204         return 1;
205     }
206     return 0;
207 }
208
209 OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
210                                   int noconfig)
211 {
212     struct provider_store_st *store = NULL;
213     OSSL_PROVIDER *prov = NULL;
214
215     if ((store = get_provider_store(libctx)) != NULL) {
216         OSSL_PROVIDER tmpl = { 0, };
217         int i;
218
219 #ifndef FIPS_MODULE
220         /*
221          * Make sure any providers are loaded from config before we try to find
222          * them.
223          */
224         if (!noconfig)
225             OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
226 #endif
227
228         tmpl.name = (char *)name;
229         CRYPTO_THREAD_write_lock(store->lock);
230         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) == -1
231             || (prov = sk_OSSL_PROVIDER_value(store->providers, i)) == NULL
232             || !ossl_provider_up_ref(prov))
233             prov = NULL;
234         CRYPTO_THREAD_unlock(store->lock);
235     }
236
237     return prov;
238 }
239
240 /*-
241  * Provider Object methods
242  * =======================
243  */
244
245 static OSSL_PROVIDER *provider_new(const char *name,
246                                    OSSL_provider_init_fn *init_function)
247 {
248     OSSL_PROVIDER *prov = NULL;
249
250     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
251 #ifndef HAVE_ATOMICS
252         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
253         || (prov->activatecnt_lock = CRYPTO_THREAD_lock_new()) == NULL
254 #endif
255         || !ossl_provider_up_ref(prov) /* +1 One reference to be returned */
256         || (prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL
257         || (prov->name = OPENSSL_strdup(name)) == NULL) {
258         ossl_provider_free(prov);
259         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
260         return NULL;
261     }
262
263     prov->init_function = init_function;
264     return prov;
265 }
266
267 int ossl_provider_up_ref(OSSL_PROVIDER *prov)
268 {
269     int ref = 0;
270
271     if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0)
272         return 0;
273     return ref;
274 }
275
276 OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
277                                  OSSL_provider_init_fn *init_function,
278                                  int noconfig)
279 {
280     struct provider_store_st *store = NULL;
281     OSSL_PROVIDER *prov = NULL;
282
283     if ((store = get_provider_store(libctx)) == NULL)
284         return NULL;
285
286     if ((prov = ossl_provider_find(libctx, name,
287                                    noconfig)) != NULL) { /* refcount +1 */
288         ossl_provider_free(prov); /* refcount -1 */
289         ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_ALREADY_EXISTS,
290                        "name=%s", name);
291         return NULL;
292     }
293
294     /* provider_new() generates an error, so no need here */
295     if ((prov = provider_new(name, init_function)) == NULL)
296         return NULL;
297
298     CRYPTO_THREAD_write_lock(store->lock);
299     if (!ossl_provider_up_ref(prov)) { /* +1 One reference for the store */
300         ossl_provider_free(prov); /* -1 Reference that was to be returned */
301         prov = NULL;
302     } else if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
303         ossl_provider_free(prov); /* -1 Store reference */
304         ossl_provider_free(prov); /* -1 Reference that was to be returned */
305         prov = NULL;
306     } else {
307         prov->libctx = libctx;
308         prov->store = store;
309 #ifndef FIPS_MODULE
310         prov->error_lib = ERR_get_next_error_library();
311 #endif
312     }
313     CRYPTO_THREAD_unlock(store->lock);
314
315     if (prov == NULL)
316         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
317
318     /*
319      * At this point, the provider is only partially "loaded".  To be
320      * fully "loaded", ossl_provider_activate() must also be called.
321      */
322
323     return prov;
324 }
325
326 static void free_infopair(INFOPAIR *pair)
327 {
328     OPENSSL_free(pair->name);
329     OPENSSL_free(pair->value);
330     OPENSSL_free(pair);
331 }
332
333 void ossl_provider_free(OSSL_PROVIDER *prov)
334 {
335     if (prov != NULL) {
336         int ref = 0;
337
338         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
339
340         /*
341          * When the refcount drops to zero, we clean up the provider.
342          * Note that this also does teardown, which may seem late,
343          * considering that init happens on first activation.  However,
344          * there may be other structures hanging on to the provider after
345          * the last deactivation and may therefore need full access to the
346          * provider's services.  Therefore, we deinit late.
347          */
348         if (ref == 0) {
349             if (prov->flag_initialized) {
350 #ifndef FIPS_MODULE
351                 ossl_init_thread_deregister(prov);
352 #endif
353                 if (prov->teardown != NULL)
354                     prov->teardown(prov->provctx);
355 #ifndef OPENSSL_NO_ERR
356 # ifndef FIPS_MODULE
357                 if (prov->error_strings != NULL) {
358                     ERR_unload_strings(prov->error_lib, prov->error_strings);
359                     OPENSSL_free(prov->error_strings);
360                     prov->error_strings = NULL;
361                 }
362 # endif
363 #endif
364                 OPENSSL_free(prov->operation_bits);
365                 prov->operation_bits = NULL;
366                 prov->operation_bits_sz = 0;
367                 prov->flag_initialized = 0;
368             }
369
370 #ifndef FIPS_MODULE
371             DSO_free(prov->module);
372 #endif
373             OPENSSL_free(prov->name);
374             OPENSSL_free(prov->path);
375             sk_INFOPAIR_pop_free(prov->parameters, free_infopair);
376             CRYPTO_THREAD_lock_free(prov->opbits_lock);
377 #ifndef HAVE_ATOMICS
378             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
379             CRYPTO_THREAD_lock_free(prov->activatecnt_lock);
380 #endif
381             OPENSSL_free(prov);
382         }
383     }
384 }
385
386 /* Setters */
387 int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
388 {
389     OPENSSL_free(prov->path);
390     if (module_path == NULL)
391         return 1;
392     if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
393         return 1;
394     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
395     return 0;
396 }
397
398 int ossl_provider_add_parameter(OSSL_PROVIDER *prov,
399                                 const char *name, const char *value)
400 {
401     INFOPAIR *pair = NULL;
402
403     if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL
404         && (prov->parameters != NULL
405             || (prov->parameters = sk_INFOPAIR_new_null()) != NULL)
406         && (pair->name = OPENSSL_strdup(name)) != NULL
407         && (pair->value = OPENSSL_strdup(value)) != NULL
408         && sk_INFOPAIR_push(prov->parameters, pair) > 0)
409         return 1;
410
411     if (pair != NULL) {
412         OPENSSL_free(pair->name);
413         OPENSSL_free(pair->value);
414         OPENSSL_free(pair);
415     }
416     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
417     return 0;
418 }
419
420 /*
421  * Provider activation.
422  *
423  * What "activation" means depends on the provider form; for built in
424  * providers (in the library or the application alike), the provider
425  * can already be considered to be loaded, all that's needed is to
426  * initialize it.  However, for dynamically loadable provider modules,
427  * we must first load that module.
428  *
429  * Built in modules are distinguished from dynamically loaded modules
430  * with an already assigned init function.
431  */
432 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
433
434 int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx,
435                                           const char *path)
436 {
437     struct provider_store_st *store;
438     char *p = NULL;
439
440     if (path != NULL) {
441         p = OPENSSL_strdup(path);
442         if (p == NULL) {
443             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
444             return 0;
445         }
446     }
447     if ((store = get_provider_store(libctx)) != NULL
448             && CRYPTO_THREAD_write_lock(store->lock)) {
449         OPENSSL_free(store->default_path);
450         store->default_path = p;
451         CRYPTO_THREAD_unlock(store->lock);
452         return 1;
453     }
454     OPENSSL_free(p);
455     return 0;
456 }
457
458 /*
459  * Internal version that doesn't affect the store flags, and thereby avoid
460  * locking.  Direct callers must remember to set the store flags when
461  * appropriate.
462  */
463 static int provider_init(OSSL_PROVIDER *prov)
464 {
465     const OSSL_DISPATCH *provider_dispatch = NULL;
466     void *tmp_provctx = NULL;    /* safety measure */
467 #ifndef OPENSSL_NO_ERR
468 # ifndef FIPS_MODULE
469     OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL;
470 # endif
471 #endif
472
473     if (prov->flag_initialized)
474         return 1;
475
476     /*
477      * If the init function isn't set, it indicates that this provider is
478      * a loadable module.
479      */
480     if (prov->init_function == NULL) {
481 #ifdef FIPS_MODULE
482         return 0;
483 #else
484         if (prov->module == NULL) {
485             char *allocated_path = NULL;
486             const char *module_path = NULL;
487             char *merged_path = NULL;
488             const char *load_dir = NULL;
489             struct provider_store_st *store;
490
491             if ((prov->module = DSO_new()) == NULL) {
492                 /* DSO_new() generates an error already */
493                 return 0;
494             }
495
496             if ((store = get_provider_store(prov->libctx)) == NULL
497                     || !CRYPTO_THREAD_read_lock(store->lock))
498                 return 0;
499             load_dir = store->default_path;
500
501             if (load_dir == NULL) {
502                 load_dir = ossl_safe_getenv("OPENSSL_MODULES");
503                 if (load_dir == NULL)
504                     load_dir = MODULESDIR;
505             }
506
507             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
508                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
509
510             module_path = prov->path;
511             if (module_path == NULL)
512                 module_path = allocated_path =
513                     DSO_convert_filename(prov->module, prov->name);
514             if (module_path != NULL)
515                 merged_path = DSO_merge(prov->module, module_path, load_dir);
516             CRYPTO_THREAD_unlock(store->lock);
517
518             if (merged_path == NULL
519                 || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
520                 DSO_free(prov->module);
521                 prov->module = NULL;
522             }
523
524             OPENSSL_free(merged_path);
525             OPENSSL_free(allocated_path);
526         }
527
528         if (prov->module != NULL)
529             prov->init_function = (OSSL_provider_init_fn *)
530                 DSO_bind_func(prov->module, "OSSL_provider_init");
531 #endif
532     }
533
534     /* Call the initialise function for the provider. */
535     if (prov->init_function == NULL
536         || !prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch,
537                                 &provider_dispatch, &tmp_provctx)) {
538         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL,
539                        "name=%s", prov->name);
540 #ifndef FIPS_MODULE
541         DSO_free(prov->module);
542         prov->module = NULL;
543 #endif
544         return 0;
545     }
546     prov->provctx = tmp_provctx;
547
548     for (; provider_dispatch->function_id != 0; provider_dispatch++) {
549         switch (provider_dispatch->function_id) {
550         case OSSL_FUNC_PROVIDER_TEARDOWN:
551             prov->teardown =
552                 OSSL_FUNC_provider_teardown(provider_dispatch);
553             break;
554         case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS:
555             prov->gettable_params =
556                 OSSL_FUNC_provider_gettable_params(provider_dispatch);
557             break;
558         case OSSL_FUNC_PROVIDER_GET_PARAMS:
559             prov->get_params =
560                 OSSL_FUNC_provider_get_params(provider_dispatch);
561             break;
562         case OSSL_FUNC_PROVIDER_SELF_TEST:
563             prov->self_test =
564                 OSSL_FUNC_provider_self_test(provider_dispatch);
565             break;
566         case OSSL_FUNC_PROVIDER_GET_CAPABILITIES:
567             prov->get_capabilities =
568                 OSSL_FUNC_provider_get_capabilities(provider_dispatch);
569             break;
570         case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
571             prov->query_operation =
572                 OSSL_FUNC_provider_query_operation(provider_dispatch);
573             break;
574 #ifndef OPENSSL_NO_ERR
575 # ifndef FIPS_MODULE
576         case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS:
577             p_get_reason_strings =
578                 OSSL_FUNC_provider_get_reason_strings(provider_dispatch);
579             break;
580 # endif
581 #endif
582         }
583     }
584
585 #ifndef OPENSSL_NO_ERR
586 # ifndef FIPS_MODULE
587     if (p_get_reason_strings != NULL) {
588         const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx);
589         size_t cnt, cnt2;
590
591         /*
592          * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM,
593          * although they are essentially the same type.
594          * Furthermore, ERR_load_strings() patches the array's error number
595          * with the error library number, so we need to make a copy of that
596          * array either way.
597          */
598         cnt = 0;
599         while (reasonstrings[cnt].id != 0) {
600             if (ERR_GET_LIB(reasonstrings[cnt].id) != 0)
601                 return 0;
602             cnt++;
603         }
604         cnt++;                   /* One for the terminating item */
605
606         /* Allocate one extra item for the "library" name */
607         prov->error_strings =
608             OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1));
609         if (prov->error_strings == NULL)
610             return 0;
611
612         /*
613          * Set the "library" name.
614          */
615         prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0);
616         prov->error_strings[0].string = prov->name;
617         /*
618          * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions
619          * 1..cnt.
620          */
621         for (cnt2 = 1; cnt2 <= cnt; cnt2++) {
622             prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id;
623             prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr;
624         }
625
626         ERR_load_strings(prov->error_lib, prov->error_strings);
627     }
628 # endif
629 #endif
630
631     /* With this flag set, this provider has become fully "loaded". */
632     prov->flag_initialized = 1;
633     return 1;
634 }
635
636 static int provider_deactivate(OSSL_PROVIDER *prov)
637 {
638     int ref = 0;
639
640     if (!ossl_assert(prov != NULL))
641         return 0;
642
643     if (CRYPTO_DOWN_REF(&prov->activatecnt, &ref, prov->activatecnt_lock) <= 0)
644         return 0;
645
646     if (ref < 1)
647         prov->flag_activated = 0;
648
649     /* We don't deinit here, that's done in ossl_provider_free() */
650     return 1;
651 }
652
653 static int provider_activate(OSSL_PROVIDER *prov)
654 {
655     int ref = 0;
656
657     if (CRYPTO_UP_REF(&prov->activatecnt, &ref, prov->activatecnt_lock) <= 0)
658         return 0;
659
660     if (provider_init(prov)) {
661         prov->flag_activated = 1;
662
663         return 1;
664     }
665
666     provider_deactivate(prov);
667     return 0;
668 }
669
670 int ossl_provider_activate(OSSL_PROVIDER *prov)
671 {
672     if (prov == NULL)
673         return 0;
674     if (provider_activate(prov)) {
675         CRYPTO_THREAD_write_lock(prov->store->lock);
676         prov->store->use_fallbacks = 0;
677         CRYPTO_THREAD_unlock(prov->store->lock);
678         return 1;
679     }
680     return 0;
681 }
682
683 int ossl_provider_deactivate(OSSL_PROVIDER *prov)
684 {
685     if (prov == NULL)
686         return 0;
687     return provider_deactivate(prov);
688 }
689
690 void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
691 {
692     return prov->provctx;
693 }
694
695
696 static int provider_forall_loaded(struct provider_store_st *store,
697                                   int *found_activated,
698                                   int (*cb)(OSSL_PROVIDER *provider,
699                                             void *cbdata),
700                                   void *cbdata)
701 {
702     int i;
703     int ret = 1;
704     int num_provs;
705
706     num_provs = sk_OSSL_PROVIDER_num(store->providers);
707
708     if (found_activated != NULL)
709         *found_activated = 0;
710     for (i = 0; i < num_provs; i++) {
711         OSSL_PROVIDER *prov =
712             sk_OSSL_PROVIDER_value(store->providers, i);
713
714         if (prov->flag_activated) {
715             if (found_activated != NULL)
716                 *found_activated = 1;
717             if (!(ret = cb(prov, cbdata)))
718                 break;
719         }
720     }
721
722     return ret;
723 }
724
725 /*
726  * This function only does something once when store->use_fallbacks == 1,
727  * and then sets store->use_fallbacks = 0, so the second call and so on is
728  * effectively a no-op.
729  */
730 static void provider_activate_fallbacks(struct provider_store_st *store)
731 {
732     int use_fallbacks;
733     int num_provs;
734     int activated_fallback_count = 0;
735     int i;
736
737     CRYPTO_THREAD_read_lock(store->lock);
738     use_fallbacks = store->use_fallbacks;
739     CRYPTO_THREAD_unlock(store->lock);
740     if (!use_fallbacks)
741         return;
742
743     CRYPTO_THREAD_write_lock(store->lock);
744     /* Check again, just in case another thread changed it */
745     use_fallbacks = store->use_fallbacks;
746     if (!use_fallbacks) {
747         CRYPTO_THREAD_unlock(store->lock);
748         return;
749     }
750
751     num_provs = sk_OSSL_PROVIDER_num(store->providers);
752     for (i = 0; i < num_provs; i++) {
753         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(store->providers, i);
754
755         if (ossl_provider_up_ref(prov)) {
756             if (prov->flag_fallback) {
757                 if (provider_activate(prov)) {
758                     prov->flag_activated_as_fallback = 1;
759                     activated_fallback_count++;
760                 }
761             }
762             ossl_provider_free(prov);
763         }
764     }
765
766     /*
767      * We assume that all fallbacks have been added to the store before
768      * any fallback is activated.
769      * TODO: We may have to reconsider this, IF we find ourselves adding
770      * fallbacks after any previous fallback has been activated.
771      */
772     if (activated_fallback_count > 0)
773         store->use_fallbacks = 0;
774
775     CRYPTO_THREAD_unlock(store->lock);
776 }
777
778 int ossl_provider_forall_loaded(OSSL_LIB_CTX *ctx,
779                                 int (*cb)(OSSL_PROVIDER *provider,
780                                           void *cbdata),
781                                 void *cbdata)
782 {
783     int ret = 1;
784     struct provider_store_st *store = get_provider_store(ctx);
785
786 #ifndef FIPS_MODULE
787     /*
788      * Make sure any providers are loaded from config before we try to use
789      * them.
790      */
791     OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
792 #endif
793
794     if (store != NULL) {
795         provider_activate_fallbacks(store);
796
797         CRYPTO_THREAD_read_lock(store->lock);
798         /*
799          * Now, we sweep through all providers
800          */
801         ret = provider_forall_loaded(store, NULL, cb, cbdata);
802
803         CRYPTO_THREAD_unlock(store->lock);
804     }
805
806     return ret;
807 }
808
809 int ossl_provider_available(OSSL_PROVIDER *prov)
810 {
811     if (prov != NULL) {
812         provider_activate_fallbacks(prov->store);
813
814         return prov->flag_activated;
815     }
816     return 0;
817 }
818
819 /* Setters of Provider Object data */
820 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
821 {
822     if (prov == NULL)
823         return 0;
824
825     prov->flag_fallback = 1;
826     return 1;
827 }
828
829 /* Getters of Provider Object data */
830 const char *ossl_provider_name(const OSSL_PROVIDER *prov)
831 {
832     return prov->name;
833 }
834
835 const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
836 {
837     return prov->module;
838 }
839
840 const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
841 {
842 #ifdef FIPS_MODULE
843     return NULL;
844 #else
845     return DSO_get_filename(prov->module);
846 #endif
847 }
848
849 const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
850 {
851 #ifdef FIPS_MODULE
852     return NULL;
853 #else
854     /* FIXME: Ensure it's a full path */
855     return DSO_get_filename(prov->module);
856 #endif
857 }
858
859 void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov)
860 {
861     if (prov != NULL)
862         return prov->provctx;
863
864     return NULL;
865 }
866
867 OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov)
868 {
869     /* TODO(3.0) just: return prov->libctx; */
870     return prov != NULL ? prov->libctx : NULL;
871 }
872
873 /* Wrappers around calls to the provider */
874 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
875 {
876     if (prov->teardown != NULL)
877         prov->teardown(prov->provctx);
878 }
879
880 const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov)
881 {
882     return prov->gettable_params == NULL
883         ? NULL : prov->gettable_params(prov->provctx);
884 }
885
886 int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
887 {
888     return prov->get_params == NULL
889         ? 0 : prov->get_params(prov->provctx, params);
890 }
891
892 int ossl_provider_self_test(const OSSL_PROVIDER *prov)
893 {
894     int ret;
895
896     if (prov->self_test == NULL)
897         return 1;
898     ret = prov->self_test(prov->provctx);
899     if (ret == 0)
900         evp_method_store_flush(ossl_provider_libctx(prov));
901     return ret;
902 }
903
904 int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
905                                    const char *capability,
906                                    OSSL_CALLBACK *cb,
907                                    void *arg)
908 {
909     return prov->get_capabilities == NULL
910         ? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg);
911 }
912
913 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
914                                                     int operation_id,
915                                                     int *no_cache)
916 {
917     const OSSL_ALGORITHM *res;
918
919     if (prov->query_operation == NULL)
920         return NULL;
921     res = prov->query_operation(prov->provctx, operation_id, no_cache);
922 #if defined(OPENSSL_NO_CACHED_FETCH)
923     /* Forcing the non-caching of queries */
924     if (no_cache != NULL)
925         *no_cache = 1;
926 #endif
927     return res;
928 }
929
930 int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum)
931 {
932     size_t byte = bitnum / 8;
933     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
934
935     CRYPTO_THREAD_write_lock(provider->opbits_lock);
936     if (provider->operation_bits_sz <= byte) {
937         unsigned char *tmp = OPENSSL_realloc(provider->operation_bits,
938                                              byte + 1);
939
940         if (tmp == NULL) {
941             CRYPTO_THREAD_unlock(provider->opbits_lock);
942             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
943             return 0;
944         }
945         provider->operation_bits = tmp;
946         memset(provider->operation_bits + provider->operation_bits_sz,
947                '\0', byte + 1 - provider->operation_bits_sz);
948         provider->operation_bits_sz = byte + 1;
949     }
950     provider->operation_bits[byte] |= bit;
951     CRYPTO_THREAD_unlock(provider->opbits_lock);
952     return 1;
953 }
954
955 int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
956                                      int *result)
957 {
958     size_t byte = bitnum / 8;
959     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
960
961     if (!ossl_assert(result != NULL)) {
962         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
963         return 0;
964     }
965
966     *result = 0;
967     CRYPTO_THREAD_read_lock(provider->opbits_lock);
968     if (provider->operation_bits_sz > byte)
969         *result = ((provider->operation_bits[byte] & bit) != 0);
970     CRYPTO_THREAD_unlock(provider->opbits_lock);
971     return 1;
972 }
973
974 /*-
975  * Core functions for the provider
976  * ===============================
977  *
978  * This is the set of functions that the core makes available to the provider
979  */
980
981 /*
982  * This returns a list of Provider Object parameters with their types, for
983  * discovery.  We do not expect that many providers will use this, but one
984  * never knows.
985  */
986 static const OSSL_PARAM param_types[] = {
987     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
988     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR,
989                     NULL, 0),
990 #ifndef FIPS_MODULE
991     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR,
992                     NULL, 0),
993 #endif
994     OSSL_PARAM_END
995 };
996
997 /*
998  * Forward declare all the functions that are provided aa dispatch.
999  * This ensures that the compiler will complain if they aren't defined
1000  * with the correct signature.
1001  */
1002 static OSSL_FUNC_core_gettable_params_fn core_gettable_params;
1003 static OSSL_FUNC_core_get_params_fn core_get_params;
1004 static OSSL_FUNC_core_thread_start_fn core_thread_start;
1005 static OSSL_FUNC_core_get_libctx_fn core_get_libctx;
1006 #ifndef FIPS_MODULE
1007 static OSSL_FUNC_core_new_error_fn core_new_error;
1008 static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug;
1009 static OSSL_FUNC_core_vset_error_fn core_vset_error;
1010 static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark;
1011 static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark;
1012 static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark;
1013 #endif
1014
1015 static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle)
1016 {
1017     return param_types;
1018 }
1019
1020 static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[])
1021 {
1022     int i;
1023     OSSL_PARAM *p;
1024     /*
1025      * We created this object originally and we know it is actually an
1026      * OSSL_PROVIDER *, so the cast is safe
1027      */
1028     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1029
1030     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL)
1031         OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
1032     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL)
1033         OSSL_PARAM_set_utf8_ptr(p, prov->name);
1034
1035 #ifndef FIPS_MODULE
1036     if ((p = OSSL_PARAM_locate(params,
1037                                OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL)
1038         OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov));
1039 #endif
1040
1041     if (prov->parameters == NULL)
1042         return 1;
1043
1044     for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
1045         INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
1046
1047         if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL)
1048             OSSL_PARAM_set_utf8_ptr(p, pair->value);
1049     }
1050     return 1;
1051 }
1052
1053 static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle)
1054 {
1055     /*
1056      * We created this object originally and we know it is actually an
1057      * OSSL_PROVIDER *, so the cast is safe
1058      */
1059     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1060
1061     return (OPENSSL_CORE_CTX *)ossl_provider_libctx(prov);
1062 }
1063
1064 static int core_thread_start(const OSSL_CORE_HANDLE *handle,
1065                              OSSL_thread_stop_handler_fn handfn)
1066 {
1067     /*
1068      * We created this object originally and we know it is actually an
1069      * OSSL_PROVIDER *, so the cast is safe
1070      */
1071     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1072
1073     return ossl_init_thread_start(prov, prov->provctx, handfn);
1074 }
1075
1076 /*
1077  * The FIPS module inner provider doesn't implement these.  They aren't
1078  * needed there, since the FIPS module upcalls are always the outer provider
1079  * ones.
1080  */
1081 #ifndef FIPS_MODULE
1082 /*
1083  * TODO(3.0) These error functions should use |handle| to select the proper
1084  * library context to report in the correct error stack, at least if error
1085  * stacks become tied to the library context.
1086  * We cannot currently do that since there's no support for it in the
1087  * ERR subsystem.
1088  */
1089 static void core_new_error(const OSSL_CORE_HANDLE *handle)
1090 {
1091     ERR_new();
1092 }
1093
1094 static void core_set_error_debug(const OSSL_CORE_HANDLE *handle,
1095                                  const char *file, int line, const char *func)
1096 {
1097     ERR_set_debug(file, line, func);
1098 }
1099
1100 static void core_vset_error(const OSSL_CORE_HANDLE *handle,
1101                             uint32_t reason, const char *fmt, va_list args)
1102 {
1103     /*
1104      * We created this object originally and we know it is actually an
1105      * OSSL_PROVIDER *, so the cast is safe
1106      */
1107     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1108
1109     /*
1110      * If the uppermost 8 bits are non-zero, it's an OpenSSL library
1111      * error and will be treated as such.  Otherwise, it's a new style
1112      * provider error and will be treated as such.
1113      */
1114     if (ERR_GET_LIB(reason) != 0) {
1115         ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args);
1116     } else {
1117         ERR_vset_error(prov->error_lib, (int)reason, fmt, args);
1118     }
1119 }
1120
1121 static int core_set_error_mark(const OSSL_CORE_HANDLE *handle)
1122 {
1123     return ERR_set_mark();
1124 }
1125
1126 static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle)
1127 {
1128     return ERR_clear_last_mark();
1129 }
1130
1131 static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle)
1132 {
1133     return ERR_pop_to_mark();
1134 }
1135 #endif /* FIPS_MODULE */
1136
1137 /*
1138  * Functions provided by the core.
1139  */
1140 static const OSSL_DISPATCH core_dispatch_[] = {
1141     { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params },
1142     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
1143     { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx },
1144     { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start },
1145 #ifndef FIPS_MODULE
1146     { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error },
1147     { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug },
1148     { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error },
1149     { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark },
1150     { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK,
1151       (void (*)(void))core_clear_last_error_mark },
1152     { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark },
1153     { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))BIO_new_file },
1154     { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))BIO_new_mem_buf },
1155     { OSSL_FUNC_BIO_READ_EX, (void (*)(void))BIO_read_ex },
1156     { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))BIO_write_ex },
1157     { OSSL_FUNC_BIO_GETS, (void (*)(void))BIO_gets },
1158     { OSSL_FUNC_BIO_PUTS, (void (*)(void))BIO_puts },
1159     { OSSL_FUNC_BIO_CTRL, (void (*)(void))BIO_ctrl },
1160     { OSSL_FUNC_BIO_FREE, (void (*)(void))BIO_free },
1161     { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))BIO_vprintf },
1162     { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf },
1163     { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))OSSL_SELF_TEST_get_callback },
1164     { OSSL_FUNC_GET_ENTROPY, (void (*)(void))ossl_rand_get_entropy },
1165     { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))ossl_rand_cleanup_entropy },
1166     { OSSL_FUNC_GET_NONCE, (void (*)(void))ossl_rand_get_nonce },
1167     { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))ossl_rand_cleanup_nonce },
1168 #endif
1169     { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc },
1170     { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc },
1171     { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free },
1172     { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free },
1173     { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc },
1174     { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc },
1175     { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc },
1176     { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc },
1177     { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free },
1178     { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE,
1179         (void (*)(void))CRYPTO_secure_clear_free },
1180     { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED,
1181         (void (*)(void))CRYPTO_secure_allocated },
1182     { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse },
1183
1184     { 0, NULL }
1185 };
1186 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;