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