Replumbing: add fallback provider capability
[openssl.git] / crypto / provider_core.c
1 /*
2  * Copyright 2019 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/opensslv.h>
13 #include "internal/cryptlib.h"
14 #include "internal/thread_once.h"
15 #include "internal/provider.h"
16 #include "internal/refcount.h"
17
18 /*-
19  * Provider Object structure
20  * =========================
21  */
22
23 struct provider_store_st;        /* Forward declaration */
24
25 struct ossl_provider_st {
26     /* Flag bits */
27     unsigned int flag_initialized:1;
28     unsigned int flag_fallback:1;
29
30     /* OpenSSL library side data */
31     CRYPTO_REF_COUNT refcnt;
32     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
33     char *name;
34     DSO *module;
35     OSSL_provider_init_fn *init_function;
36     struct provider_store_st *store; /* The store this instance belongs to */
37
38     /* Provider side functions */
39     OSSL_provider_teardown_fn *teardown;
40     OSSL_provider_get_param_types_fn *get_param_types;
41     OSSL_provider_get_params_fn *get_params;
42     OSSL_provider_query_operation_fn *query_operation;
43 };
44 DEFINE_STACK_OF(OSSL_PROVIDER)
45
46 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
47                              const OSSL_PROVIDER * const *b)
48 {
49     return strcmp((*a)->name, (*b)->name);
50 }
51
52 /*-
53  * Provider Object store
54  * =====================
55  *
56  * The Provider Object store is a library context object, and therefore needs
57  * an index.
58  */
59
60 struct provider_store_st {
61     STACK_OF(OSSL_PROVIDER) *providers;
62     CRYPTO_RWLOCK *lock;
63     unsigned int use_fallbacks:1;
64 };
65 static int provider_store_index = -1;
66
67 static void provider_store_free(void *vstore)
68 {
69     struct provider_store_st *store = vstore;
70
71     if (store == NULL)
72         return;
73     sk_OSSL_PROVIDER_pop_free(store->providers, ossl_provider_free);
74     CRYPTO_THREAD_lock_free(store->lock);
75     OPENSSL_free(store);
76 }
77
78 static void *provider_store_new(void)
79 {
80     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
81
82     if (store == NULL
83         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
84         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
85         provider_store_free(store);
86         return NULL;
87     }
88     store->use_fallbacks = 1;
89     return store;
90 }
91
92 static const OPENSSL_CTX_METHOD provider_store_method = {
93     provider_store_new,
94     provider_store_free,
95 };
96
97 static CRYPTO_ONCE provider_store_init_flag = CRYPTO_ONCE_STATIC_INIT;
98 DEFINE_RUN_ONCE_STATIC(do_provider_store_init)
99 {
100     return OPENSSL_init_crypto(0, NULL)
101         && (provider_store_index =
102             openssl_ctx_new_index(&provider_store_method)) != -1;
103 }
104
105
106 static struct provider_store_st *get_provider_store(OPENSSL_CTX *libctx)
107 {
108     struct provider_store_st *store = NULL;
109
110     if (!RUN_ONCE(&provider_store_init_flag, do_provider_store_init))
111         return NULL;
112
113     store = openssl_ctx_get_data(libctx, provider_store_index);
114     if (store == NULL)
115         CRYPTOerr(CRYPTO_F_GET_PROVIDER_STORE, ERR_R_INTERNAL_ERROR);
116     return store;
117 }
118
119 /*-
120  * Provider Object methods
121  * =======================
122  */
123
124 int ossl_provider_upref(OSSL_PROVIDER *prov)
125 {
126     int ref = 0;
127
128     CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock);
129     return ref;
130 }
131
132 /* Finder, constructor and destructor */
133 OSSL_PROVIDER *ossl_provider_find(OPENSSL_CTX *libctx, const char *name)
134 {
135     struct provider_store_st *store = NULL;
136     OSSL_PROVIDER *prov = NULL;
137
138     if ((store = get_provider_store(libctx)) != NULL) {
139         OSSL_PROVIDER tmpl = { 0, };
140         int i;
141
142         tmpl.name = (char *)name;
143         CRYPTO_THREAD_write_lock(store->lock);
144         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) == -1
145             || (prov = sk_OSSL_PROVIDER_value(store->providers, i)) == NULL
146             || !ossl_provider_upref(prov))
147             prov = NULL;
148         CRYPTO_THREAD_unlock(store->lock);
149     }
150
151     return prov;
152 }
153
154 OSSL_PROVIDER *ossl_provider_new(OPENSSL_CTX *libctx, const char *name,
155                                  OSSL_provider_init_fn *init_function)
156 {
157     struct provider_store_st *store = NULL;
158     OSSL_PROVIDER *prov = NULL;
159
160     if ((store = get_provider_store(libctx)) == NULL)
161         return NULL;
162
163     if ((prov = ossl_provider_find(libctx, name)) != NULL) { /* refcount +1 */
164         ossl_provider_free(prov); /* refcount -1 */
165         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW,
166                   CRYPTO_R_PROVIDER_ALREADY_EXISTS);
167         ERR_add_error_data(2, "name=", name);
168         return NULL;
169     }
170
171     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
172 #ifndef HAVE_ATOMICS
173         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
174 #endif
175         || !ossl_provider_upref(prov) /* +1 One reference to be returned */
176         || (prov->name = OPENSSL_strdup(name)) == NULL) {
177         ossl_provider_free(prov);
178         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
179         return NULL;
180     }
181
182     prov->init_function = init_function;
183
184     CRYPTO_THREAD_write_lock(store->lock);
185     if (!ossl_provider_upref(prov)) { /* +1 One reference for the store */
186         ossl_provider_free(prov); /* -1 Reference that was to be returned */
187         prov = NULL;
188     } else if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
189         ossl_provider_free(prov); /* -1 Store reference */
190         ossl_provider_free(prov); /* -1 Reference that was to be returned */
191         prov = NULL;
192     } else {
193         prov->store = store;
194     }
195     CRYPTO_THREAD_unlock(store->lock);
196
197     if (prov == NULL)
198         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
199
200     /*
201      * At this point, the provider is only partially "loaded".  To be
202      * fully "loaded", ossl_provider_activate() must also be called.
203      */
204
205     return prov;
206 }
207
208 void ossl_provider_free(OSSL_PROVIDER *prov)
209 {
210     if (prov != NULL) {
211         int ref = 0;
212
213         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
214
215         /*
216          * When the refcount drops below two, the store is the only
217          * possible reference, or it has already been taken away from
218          * the store (this may happen if a provider was activated
219          * because it's a fallback, but isn't currently used)
220          * When that happens, the provider is inactivated.
221          */
222         if (ref < 2 && prov->flag_initialized) {
223             if (prov->teardown != NULL)
224                 prov->teardown();
225             prov->flag_initialized = 0;
226         }
227
228         /*
229          * When the refcount drops to zero, it has been taken out of
230          * the store.  All we have to do here is clean it out.
231          */
232         if (ref == 0) {
233             DSO_free(prov->module);
234             OPENSSL_free(prov->name);
235 #ifndef HAVE_ATOMICS
236             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
237 #endif
238             OPENSSL_free(prov);
239         }
240     }
241 }
242
243 /*
244  * Provider activation.
245  *
246  * What "activation" means depends on the provider form; for built in
247  * providers (in the library or the application alike), the provider
248  * can already be considered to be loaded, all that's needed is to
249  * initialize it.  However, for dynamically loadable provider modules,
250  * we must first load that module.
251  *
252  * Built in modules are distinguished from dynamically loaded modules
253  * with an already assigned init function.
254  */
255 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
256
257 /*
258  * Internal version that doesn't affect the store flags, and thereby avoid
259  * locking.  Direct callers must remember to set the store flags when
260  * appropriate
261  */
262 static int provider_activate(OSSL_PROVIDER *prov)
263 {
264     const OSSL_DISPATCH *provider_dispatch = NULL;
265
266     if (prov->flag_initialized)
267         return 1;
268
269     /*
270      * If the init function isn't set, it indicates that this provider is
271      * a loadable module.
272      */
273     if (prov->init_function == NULL) {
274         if (prov->module == NULL) {
275             char *platform_module_name = NULL;
276             char *module_path = NULL;
277             const char *load_dir = ossl_safe_getenv("OPENSSL_MODULES");
278
279             if ((prov->module = DSO_new()) == NULL) {
280                 /* DSO_new() generates an error already */
281                 return 0;
282             }
283
284             if (load_dir == NULL)
285                 load_dir = MODULESDIR;
286
287             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
288                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
289             if ((platform_module_name =
290                  DSO_convert_filename(prov->module, prov->name)) == NULL
291                 || (module_path =
292                     DSO_merge(prov->module, platform_module_name,
293                               load_dir)) == NULL
294                 || DSO_load(prov->module, module_path, NULL,
295                             DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == NULL) {
296                 DSO_free(prov->module);
297                 prov->module = NULL;
298             }
299
300             OPENSSL_free(platform_module_name);
301             OPENSSL_free(module_path);
302         }
303
304         if (prov->module != NULL)
305             prov->init_function = (OSSL_provider_init_fn *)
306                 DSO_bind_func(prov->module, "OSSL_provider_init");
307     }
308
309     if (prov->init_function == NULL
310         || !prov->init_function(prov, core_dispatch, &provider_dispatch)) {
311         CRYPTOerr(CRYPTO_F_PROVIDER_ACTIVATE, ERR_R_INIT_FAIL);
312         ERR_add_error_data(2, "name=", prov->name);
313         DSO_free(prov->module);
314         prov->module = NULL;
315         return 0;
316     }
317
318     for (; provider_dispatch->function_id != 0; provider_dispatch++) {
319         switch (provider_dispatch->function_id) {
320         case OSSL_FUNC_PROVIDER_TEARDOWN:
321             prov->teardown =
322                 OSSL_get_provider_teardown(provider_dispatch);
323             break;
324         case OSSL_FUNC_PROVIDER_GET_PARAM_TYPES:
325             prov->get_param_types =
326                 OSSL_get_provider_get_param_types(provider_dispatch);
327             break;
328         case OSSL_FUNC_PROVIDER_GET_PARAMS:
329             prov->get_params =
330                 OSSL_get_provider_get_params(provider_dispatch);
331             break;
332         case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
333             prov->query_operation =
334                 OSSL_get_provider_query_operation(provider_dispatch);
335             break;
336         }
337     }
338
339     /* With this flag set, this provider has become fully "loaded". */
340     prov->flag_initialized = 1;
341
342     return 1;
343 }
344
345 int ossl_provider_activate(OSSL_PROVIDER *prov)
346 {
347     if (provider_activate(prov)) {
348         CRYPTO_THREAD_write_lock(prov->store->lock);
349         prov->store->use_fallbacks = 0;
350         CRYPTO_THREAD_unlock(prov->store->lock);
351         return 1;
352     }
353
354     return 0;
355 }
356
357
358 static int provider_forall_loaded(struct provider_store_st *store,
359                                   int *found_activated,
360                                   int (*cb)(OSSL_PROVIDER *provider,
361                                             void *cbdata),
362                                   void *cbdata)
363 {
364     int i;
365     int ret = 1;
366     int num_provs = sk_OSSL_PROVIDER_num(store->providers);
367
368     if (found_activated != NULL)
369         *found_activated = 0;
370     for (i = 0; i < num_provs; i++) {
371         OSSL_PROVIDER *prov =
372             sk_OSSL_PROVIDER_value(store->providers, i);
373
374         if (prov->flag_initialized) {
375             if (found_activated != NULL)
376                 *found_activated = 1;
377             if (!(ret = cb(prov, cbdata)))
378                 break;
379         }
380     }
381
382     return ret;
383 }
384
385 int ossl_provider_forall_loaded(OPENSSL_CTX *ctx,
386                                 int (*cb)(OSSL_PROVIDER *provider,
387                                           void *cbdata),
388                                 void *cbdata)
389 {
390     int ret = 1;
391     int i;
392     struct provider_store_st *store = get_provider_store(ctx);
393
394     if (store != NULL) {
395         int found_activated = 0;
396
397         CRYPTO_THREAD_read_lock(store->lock);
398         ret = provider_forall_loaded(store, &found_activated, cb, cbdata);
399
400         /*
401          * If there's nothing activated ever in this store, try to activate
402          * all fallbacks.
403          */
404         if (!found_activated && store->use_fallbacks) {
405             int num_provs = sk_OSSL_PROVIDER_num(store->providers);
406             int activated_fallback_count = 0;
407
408             for (i = 0; i < num_provs; i++) {
409                 OSSL_PROVIDER *prov =
410                     sk_OSSL_PROVIDER_value(store->providers, i);
411
412                 /*
413                  * Note that we don't care if the activation succeeds or
414                  * not.  If it doesn't succeed, then the next loop will
415                  * fail anyway.
416                  */
417                 if (prov->flag_fallback) {
418                     activated_fallback_count++;
419                     provider_activate(prov);
420                 }
421             }
422
423             if (activated_fallback_count > 0) {
424                 /*
425                  * We assume that all fallbacks have been added to the store
426                  * before any fallback is activated.
427                  * TODO: We may have to reconsider this, IF we find ourselves
428                  * adding fallbacks after any previous fallback has been
429                  * activated.
430                  */
431                 store->use_fallbacks = 0;
432
433                 /*
434                  * Now that we've activated available fallbacks, try a
435                  * second sweep
436                  */
437                 ret = provider_forall_loaded(store, NULL, cb, cbdata);
438             }
439         }
440         CRYPTO_THREAD_unlock(store->lock);
441     }
442
443     return ret;
444 }
445
446 /* Setters of Provider Object data */
447 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
448 {
449     if (prov == NULL)
450         return 0;
451
452     prov->flag_fallback = 1;
453     return 1;
454 }
455
456 /* Getters of Provider Object data */
457 const char *ossl_provider_name(OSSL_PROVIDER *prov)
458 {
459     return prov->name;
460 }
461
462 const DSO *ossl_provider_dso(OSSL_PROVIDER *prov)
463 {
464     return prov->module;
465 }
466
467 const char *ossl_provider_module_name(OSSL_PROVIDER *prov)
468 {
469     return DSO_get_filename(prov->module);
470 }
471
472 const char *ossl_provider_module_path(OSSL_PROVIDER *prov)
473 {
474     /* FIXME: Ensure it's a full path */
475     return DSO_get_filename(prov->module);
476 }
477
478 /* Wrappers around calls to the provider */
479 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
480 {
481     if (prov->teardown != NULL)
482         prov->teardown();
483 }
484
485 const OSSL_ITEM *ossl_provider_get_param_types(const OSSL_PROVIDER *prov)
486 {
487     return prov->get_param_types == NULL ? NULL : prov->get_param_types(prov);
488 }
489
490 int ossl_provider_get_params(const OSSL_PROVIDER *prov,
491                              const OSSL_PARAM params[])
492 {
493     return prov->get_params == NULL ? 0 : prov->get_params(prov, params);
494 }
495
496
497 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
498                                                     int operation_id,
499                                                     int *no_cache)
500 {
501     return prov->query_operation(prov, operation_id, no_cache);
502 }
503
504 /*-
505  * Core functions for the provider
506  * ===============================
507  *
508  * This is the set of functions that the core makes available to the provider
509  */
510
511 /*
512  * This returns a list of Provider Object parameters with their types, for
513  * discovery.  We do not expect that many providers will use this, but one
514  * never knows.
515  */
516 static const OSSL_ITEM param_types[] = {
517     { OSSL_PARAM_UTF8_PTR, "openssl-version" },
518     { OSSL_PARAM_UTF8_PTR, "provider-name" },
519     { 0, NULL }
520 };
521
522 static const OSSL_ITEM *core_get_param_types(const OSSL_PROVIDER *prov)
523 {
524     return param_types;
525 }
526
527 static int core_get_params(const OSSL_PROVIDER *prov, const OSSL_PARAM params[])
528 {
529     int i;
530
531     for (i = 0; params[i].key != NULL; i++) {
532         if (strcmp(params[i].key, "openssl-version") == 0) {
533             *(void **)params[i].data = OPENSSL_VERSION_STR;
534             if (params[i].return_size)
535                 *params[i].return_size = sizeof(OPENSSL_VERSION_STR);
536         } else if (strcmp(params[i].key, "provider-name") == 0) {
537             *(void **)params[i].data = prov->name;
538             if (params[i].return_size)
539                 *params[i].return_size = strlen(prov->name) + 1;
540         }
541     }
542
543     return 1;
544 }
545
546 static const OSSL_DISPATCH core_dispatch_[] = {
547     { OSSL_FUNC_CORE_GET_PARAM_TYPES, (void (*)(void))core_get_param_types },
548     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
549     { 0, NULL }
550 };
551 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;