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