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