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