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