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