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