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