Constify OSSL_PROVIDER getter input parameters
[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/params.h>
13 #include <openssl/opensslv.h>
14 #include "internal/cryptlib.h"
15 #include "internal/nelem.h"
16 #include "internal/thread_once.h"
17 #include "internal/provider.h"
18 #include "internal/refcount.h"
19 #include "provider_local.h"
20
21 static OSSL_PROVIDER *provider_new(const char *name,
22                                    OSSL_provider_init_fn *init_function);
23
24 /*-
25  * Provider Object structure
26  * =========================
27  */
28
29 typedef struct {
30     char *name;
31     char *value;
32 } INFOPAIR;
33 DEFINE_STACK_OF(INFOPAIR)
34
35 struct provider_store_st;        /* Forward declaration */
36
37 struct ossl_provider_st {
38     /* Flag bits */
39     unsigned int flag_initialized:1;
40     unsigned int flag_fallback:1;
41
42     /* OpenSSL library side data */
43     CRYPTO_REF_COUNT refcnt;
44     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
45     char *name;
46     char *path;
47     DSO *module;
48     OSSL_provider_init_fn *init_function;
49     STACK_OF(INFOPAIR) *parameters;
50     struct provider_store_st *store; /* The store this instance belongs to */
51
52     /* Provider side functions */
53     OSSL_provider_teardown_fn *teardown;
54     OSSL_provider_get_param_types_fn *get_param_types;
55     OSSL_provider_get_params_fn *get_params;
56     OSSL_provider_query_operation_fn *query_operation;
57
58     /* Provider side data */
59     void *provctx;
60 };
61 DEFINE_STACK_OF(OSSL_PROVIDER)
62
63 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
64                              const OSSL_PROVIDER * const *b)
65 {
66     return strcmp((*a)->name, (*b)->name);
67 }
68
69 /*-
70  * Provider Object store
71  * =====================
72  *
73  * The Provider Object store is a library context object, and therefore needs
74  * an index.
75  */
76
77 struct provider_store_st {
78     STACK_OF(OSSL_PROVIDER) *providers;
79     CRYPTO_RWLOCK *lock;
80     unsigned int use_fallbacks:1;
81 };
82
83 static void provider_store_free(void *vstore)
84 {
85     struct provider_store_st *store = vstore;
86
87     if (store == NULL)
88         return;
89     sk_OSSL_PROVIDER_pop_free(store->providers, ossl_provider_free);
90     CRYPTO_THREAD_lock_free(store->lock);
91     OPENSSL_free(store);
92 }
93
94 static void *provider_store_new(OPENSSL_CTX *ctx)
95 {
96     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
97     const struct predefined_providers_st *p = NULL;
98
99     if (store == NULL
100         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
101         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
102         provider_store_free(store);
103         return NULL;
104     }
105     store->use_fallbacks = 1;
106
107     for (p = predefined_providers; p->name != NULL; p++) {
108         OSSL_PROVIDER *prov = NULL;
109
110         /*
111          * We use the internal constructor directly here,
112          * otherwise we get a call loop
113          */
114         prov = provider_new(p->name, p->init);
115
116         if (prov == NULL
117             || sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
118             ossl_provider_free(prov);
119             provider_store_free(store);
120             CRYPTOerr(CRYPTO_F_PROVIDER_STORE_NEW, ERR_R_INTERNAL_ERROR);
121             return NULL;
122         }
123         prov->store = store;
124         if(p->is_fallback)
125             ossl_provider_set_fallback(prov);
126     }
127
128     return store;
129 }
130
131 static const OPENSSL_CTX_METHOD provider_store_method = {
132     provider_store_new,
133     provider_store_free,
134 };
135
136 static struct provider_store_st *get_provider_store(OPENSSL_CTX *libctx)
137 {
138     struct provider_store_st *store = NULL;
139
140     store = openssl_ctx_get_data(libctx, OPENSSL_CTX_PROVIDER_STORE_INDEX,
141                                  &provider_store_method);
142     if (store == NULL)
143         CRYPTOerr(CRYPTO_F_GET_PROVIDER_STORE, ERR_R_INTERNAL_ERROR);
144     return store;
145 }
146
147 OSSL_PROVIDER *ossl_provider_find(OPENSSL_CTX *libctx, const char *name)
148 {
149     struct provider_store_st *store = NULL;
150     OSSL_PROVIDER *prov = NULL;
151
152     if ((store = get_provider_store(libctx)) != NULL) {
153         OSSL_PROVIDER tmpl = { 0, };
154         int i;
155
156         tmpl.name = (char *)name;
157         CRYPTO_THREAD_write_lock(store->lock);
158         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) == -1
159             || (prov = sk_OSSL_PROVIDER_value(store->providers, i)) == NULL
160             || !ossl_provider_upref(prov))
161             prov = NULL;
162         CRYPTO_THREAD_unlock(store->lock);
163     }
164
165     return prov;
166 }
167
168 /*-
169  * Provider Object methods
170  * =======================
171  */
172
173 static OSSL_PROVIDER *provider_new(const char *name,
174                                    OSSL_provider_init_fn *init_function)
175 {
176     OSSL_PROVIDER *prov = NULL;
177
178     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
179 #ifndef HAVE_ATOMICS
180         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
181 #endif
182         || !ossl_provider_upref(prov) /* +1 One reference to be returned */
183         || (prov->name = OPENSSL_strdup(name)) == NULL) {
184         ossl_provider_free(prov);
185         CRYPTOerr(CRYPTO_F_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
186         return NULL;
187     }
188
189     prov->init_function = init_function;
190     return prov;
191 }
192
193 int ossl_provider_upref(OSSL_PROVIDER *prov)
194 {
195     int ref = 0;
196
197     CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock);
198     return ref;
199 }
200
201 OSSL_PROVIDER *ossl_provider_new(OPENSSL_CTX *libctx, const char *name,
202                                  OSSL_provider_init_fn *init_function)
203 {
204     struct provider_store_st *store = NULL;
205     OSSL_PROVIDER *prov = NULL;
206
207     if ((store = get_provider_store(libctx)) == NULL)
208         return NULL;
209
210     if ((prov = ossl_provider_find(libctx, name)) != NULL) { /* refcount +1 */
211         ossl_provider_free(prov); /* refcount -1 */
212         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW,
213                   CRYPTO_R_PROVIDER_ALREADY_EXISTS);
214         ERR_add_error_data(2, "name=", name);
215         return NULL;
216     }
217
218     /* provider_new() generates an error, so no need here */
219     if ((prov = provider_new(name, init_function)) == NULL)
220         return NULL;
221
222     CRYPTO_THREAD_write_lock(store->lock);
223     if (!ossl_provider_upref(prov)) { /* +1 One reference for the store */
224         ossl_provider_free(prov); /* -1 Reference that was to be returned */
225         prov = NULL;
226     } else if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
227         ossl_provider_free(prov); /* -1 Store reference */
228         ossl_provider_free(prov); /* -1 Reference that was to be returned */
229         prov = NULL;
230     } else {
231         prov->store = store;
232     }
233     CRYPTO_THREAD_unlock(store->lock);
234
235     if (prov == NULL)
236         CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_NEW, ERR_R_MALLOC_FAILURE);
237
238     /*
239      * At this point, the provider is only partially "loaded".  To be
240      * fully "loaded", ossl_provider_activate() must also be called.
241      */
242
243     return prov;
244 }
245
246 static void free_infopair(INFOPAIR *pair)
247 {
248     OPENSSL_free(pair->name);
249     OPENSSL_free(pair->value);
250     OPENSSL_free(pair);
251 }
252
253 void ossl_provider_free(OSSL_PROVIDER *prov)
254 {
255     if (prov != NULL) {
256         int ref = 0;
257
258         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
259
260         /*
261          * When the refcount drops below two, the store is the only
262          * possible reference, or it has already been taken away from
263          * the store (this may happen if a provider was activated
264          * because it's a fallback, but isn't currently used)
265          * When that happens, the provider is inactivated.
266          */
267         if (ref < 2 && prov->flag_initialized) {
268             if (prov->teardown != NULL)
269                 prov->teardown(prov->provctx);
270             prov->flag_initialized = 0;
271         }
272
273         /*
274          * When the refcount drops to zero, it has been taken out of
275          * the store.  All we have to do here is clean it out.
276          */
277         if (ref == 0) {
278 #ifndef FIPS_MODE
279             DSO_free(prov->module);
280 #endif
281             OPENSSL_free(prov->name);
282             OPENSSL_free(prov->path);
283             sk_INFOPAIR_pop_free(prov->parameters, free_infopair);
284 #ifndef HAVE_ATOMICS
285             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
286 #endif
287             OPENSSL_free(prov);
288         }
289     }
290 }
291
292 /* Setters */
293 int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
294 {
295     OPENSSL_free(prov->path);
296     if (module_path == NULL)
297         return 1;
298     if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
299         return 1;
300     CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_SET_MODULE_PATH, ERR_R_MALLOC_FAILURE);
301     return 0;
302 }
303
304 int ossl_provider_add_parameter(OSSL_PROVIDER *prov,
305                                 const char *name, const char *value)
306 {
307     INFOPAIR *pair = NULL;
308
309     if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL
310         && (prov->parameters != NULL
311             || (prov->parameters = sk_INFOPAIR_new_null()) != NULL)
312         && (pair->name = OPENSSL_strdup(name)) != NULL
313         && (pair->value = OPENSSL_strdup(value)) != NULL
314         && sk_INFOPAIR_push(prov->parameters, pair) > 0)
315         return 1;
316
317     if (pair != NULL) {
318         OPENSSL_free(pair->name);
319         OPENSSL_free(pair->value);
320         OPENSSL_free(pair);
321     }
322     CRYPTOerr(CRYPTO_F_OSSL_PROVIDER_ADD_PARAMETER, ERR_R_MALLOC_FAILURE);
323     return 0;
324 }
325
326 /*
327  * Provider activation.
328  *
329  * What "activation" means depends on the provider form; for built in
330  * providers (in the library or the application alike), the provider
331  * can already be considered to be loaded, all that's needed is to
332  * initialize it.  However, for dynamically loadable provider modules,
333  * we must first load that module.
334  *
335  * Built in modules are distinguished from dynamically loaded modules
336  * with an already assigned init function.
337  */
338 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
339
340 /*
341  * Internal version that doesn't affect the store flags, and thereby avoid
342  * locking.  Direct callers must remember to set the store flags when
343  * appropriate. The libctx parameter is only necessary when FIPS_MODE is set
344  * (i.e. we are being called from inside the FIPS module) - it is ignored for
345  * other uses.
346  */
347 static int provider_activate(OSSL_PROVIDER *prov, OPENSSL_CTX *libctx)
348 {
349     const OSSL_DISPATCH *provider_dispatch = NULL;
350
351     if (prov->flag_initialized)
352         return 1;
353
354     /*
355      * If the init function isn't set, it indicates that this provider is
356      * a loadable module.
357      */
358     if (prov->init_function == NULL) {
359 #ifdef FIPS_MODE
360         return 0;
361 #else
362         if (prov->module == NULL) {
363             char *allocated_path = NULL;
364             const char *module_path = NULL;
365             char *merged_path = NULL;
366             const char *load_dir = ossl_safe_getenv("OPENSSL_MODULES");
367
368             if ((prov->module = DSO_new()) == NULL) {
369                 /* DSO_new() generates an error already */
370                 return 0;
371             }
372
373             if (load_dir == NULL)
374                 load_dir = MODULESDIR;
375
376             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
377                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
378
379             module_path = prov->path;
380             if (module_path == NULL)
381                 module_path = allocated_path =
382                     DSO_convert_filename(prov->module, prov->name);
383             if (module_path != NULL)
384                 merged_path = DSO_merge(prov->module, module_path, load_dir);
385
386             if (merged_path == NULL
387                 || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
388                 DSO_free(prov->module);
389                 prov->module = NULL;
390             }
391
392             OPENSSL_free(merged_path);
393             OPENSSL_free(allocated_path);
394         }
395
396         if (prov->module != NULL)
397             prov->init_function = (OSSL_provider_init_fn *)
398                 DSO_bind_func(prov->module, "OSSL_provider_init");
399 #endif
400     }
401
402     /*
403      * We call the initialise function for the provider.
404      *
405      * If FIPS_MODE is defined then we are inside the FIPS module and are about
406      * to recursively initialise ourselves. We need to do this so that we can
407      * get all the provider callback functions set up in order for us to be able
408      * to make EVP calls from within the FIPS module itself. Only algorithms
409      * from the FIPS module itself are available via the FIPS module EVP
410      * interface, i.e. we only ever have one provider available inside the FIPS
411      * module - the FIPS provider itself.
412      *
413      * For modules in general we cannot know what value will be used for the
414      * provctx - it is a "black box". But for the FIPS module we know that the
415      * provctx is really a library context. We default the provctx value to the
416      * same library context as was used for the EVP call that caused this call
417      * to "provider_activate".
418      */
419 #ifdef FIPS_MODE
420     prov->provctx = libctx;
421 #endif
422     if (prov->init_function == NULL
423         || !prov->init_function(prov, core_dispatch, &provider_dispatch,
424                                 &prov->provctx)) {
425         CRYPTOerr(CRYPTO_F_PROVIDER_ACTIVATE, ERR_R_INIT_FAIL);
426         ERR_add_error_data(2, "name=", prov->name);
427 #ifndef FIPS_MODE
428         DSO_free(prov->module);
429         prov->module = NULL;
430 #endif
431         return 0;
432     }
433
434     for (; provider_dispatch->function_id != 0; provider_dispatch++) {
435         switch (provider_dispatch->function_id) {
436         case OSSL_FUNC_PROVIDER_TEARDOWN:
437             prov->teardown =
438                 OSSL_get_provider_teardown(provider_dispatch);
439             break;
440         case OSSL_FUNC_PROVIDER_GET_PARAM_TYPES:
441             prov->get_param_types =
442                 OSSL_get_provider_get_param_types(provider_dispatch);
443             break;
444         case OSSL_FUNC_PROVIDER_GET_PARAMS:
445             prov->get_params =
446                 OSSL_get_provider_get_params(provider_dispatch);
447             break;
448         case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
449             prov->query_operation =
450                 OSSL_get_provider_query_operation(provider_dispatch);
451             break;
452         }
453     }
454
455     /* With this flag set, this provider has become fully "loaded". */
456     prov->flag_initialized = 1;
457
458     return 1;
459 }
460
461 int ossl_provider_activate(OSSL_PROVIDER *prov)
462 {
463     if (provider_activate(prov, NULL)) {
464         CRYPTO_THREAD_write_lock(prov->store->lock);
465         prov->store->use_fallbacks = 0;
466         CRYPTO_THREAD_unlock(prov->store->lock);
467         return 1;
468     }
469
470     return 0;
471 }
472
473 void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
474 {
475     return prov->provctx;
476 }
477
478
479 static int provider_forall_loaded(struct provider_store_st *store,
480                                   int *found_activated,
481                                   int (*cb)(OSSL_PROVIDER *provider,
482                                             void *cbdata),
483                                   void *cbdata)
484 {
485     int i;
486     int ret = 1;
487     int num_provs = sk_OSSL_PROVIDER_num(store->providers);
488
489     if (found_activated != NULL)
490         *found_activated = 0;
491     for (i = 0; i < num_provs; i++) {
492         OSSL_PROVIDER *prov =
493             sk_OSSL_PROVIDER_value(store->providers, i);
494
495         if (prov->flag_initialized) {
496             if (found_activated != NULL)
497                 *found_activated = 1;
498             if (!(ret = cb(prov, cbdata)))
499                 break;
500         }
501     }
502
503     return ret;
504 }
505
506 int ossl_provider_forall_loaded(OPENSSL_CTX *ctx,
507                                 int (*cb)(OSSL_PROVIDER *provider,
508                                           void *cbdata),
509                                 void *cbdata)
510 {
511     int ret = 1;
512     int i;
513     struct provider_store_st *store = get_provider_store(ctx);
514
515     if (store != NULL) {
516         int found_activated = 0;
517
518         CRYPTO_THREAD_read_lock(store->lock);
519         ret = provider_forall_loaded(store, &found_activated, cb, cbdata);
520
521         /*
522          * If there's nothing activated ever in this store, try to activate
523          * all fallbacks.
524          */
525         if (!found_activated && store->use_fallbacks) {
526             int num_provs = sk_OSSL_PROVIDER_num(store->providers);
527             int activated_fallback_count = 0;
528
529             for (i = 0; i < num_provs; i++) {
530                 OSSL_PROVIDER *prov =
531                     sk_OSSL_PROVIDER_value(store->providers, i);
532
533                 /*
534                  * Note that we don't care if the activation succeeds or
535                  * not.  If it doesn't succeed, then the next loop will
536                  * fail anyway.
537                  */
538                 if (prov->flag_fallback) {
539                     activated_fallback_count++;
540                     provider_activate(prov, ctx);
541                 }
542             }
543
544             if (activated_fallback_count > 0) {
545                 /*
546                  * We assume that all fallbacks have been added to the store
547                  * before any fallback is activated.
548                  * TODO: We may have to reconsider this, IF we find ourselves
549                  * adding fallbacks after any previous fallback has been
550                  * activated.
551                  */
552                 store->use_fallbacks = 0;
553
554                 /*
555                  * Now that we've activated available fallbacks, try a
556                  * second sweep
557                  */
558                 ret = provider_forall_loaded(store, NULL, cb, cbdata);
559             }
560         }
561         CRYPTO_THREAD_unlock(store->lock);
562     }
563
564     return ret;
565 }
566
567 /* Setters of Provider Object data */
568 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
569 {
570     if (prov == NULL)
571         return 0;
572
573     prov->flag_fallback = 1;
574     return 1;
575 }
576
577 /* Getters of Provider Object data */
578 const char *ossl_provider_name(const OSSL_PROVIDER *prov)
579 {
580     return prov->name;
581 }
582
583 const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
584 {
585     return prov->module;
586 }
587
588 const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
589 {
590 #ifdef FIPS_MODE
591     return NULL;
592 #else
593     return DSO_get_filename(prov->module);
594 #endif
595 }
596
597 const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
598 {
599 #ifdef FIPS_MODE
600     return NULL;
601 #else
602     /* FIXME: Ensure it's a full path */
603     return DSO_get_filename(prov->module);
604 #endif
605 }
606
607 /* Wrappers around calls to the provider */
608 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
609 {
610     if (prov->teardown != NULL)
611         prov->teardown(prov->provctx);
612 }
613
614 const OSSL_ITEM *ossl_provider_get_param_types(const OSSL_PROVIDER *prov)
615 {
616     return prov->get_param_types == NULL
617         ? NULL : prov->get_param_types(prov->provctx);
618 }
619
620 int ossl_provider_get_params(const OSSL_PROVIDER *prov,
621                              const OSSL_PARAM params[])
622 {
623     return prov->get_params == NULL
624         ? 0 : prov->get_params(prov->provctx, params);
625 }
626
627
628 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
629                                                     int operation_id,
630                                                     int *no_cache)
631 {
632     return prov->query_operation(prov->provctx, operation_id, no_cache);
633 }
634
635 /*-
636  * Core functions for the provider
637  * ===============================
638  *
639  * This is the set of functions that the core makes available to the provider
640  */
641
642 /*
643  * This returns a list of Provider Object parameters with their types, for
644  * discovery.  We do not expect that many providers will use this, but one
645  * never knows.
646  */
647 static const OSSL_ITEM param_types[] = {
648     { OSSL_PARAM_UTF8_PTR, "openssl-version" },
649     { OSSL_PARAM_UTF8_PTR, "provider-name" },
650     { 0, NULL }
651 };
652
653 static const OSSL_ITEM *core_get_param_types(const OSSL_PROVIDER *prov)
654 {
655     return param_types;
656 }
657
658 static int core_get_params(const OSSL_PROVIDER *prov, const OSSL_PARAM params[])
659 {
660     int i;
661     const OSSL_PARAM *p;
662
663     if ((p = OSSL_PARAM_locate(params, "openssl-version")) != NULL)
664         OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
665     if ((p = OSSL_PARAM_locate(params, "provider-name")) != NULL)
666         OSSL_PARAM_set_utf8_ptr(p, prov->name);
667
668     if (prov->parameters == NULL)
669         return 1;
670
671     for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
672         INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
673
674         if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL)
675             OSSL_PARAM_set_utf8_ptr(p, pair->value);
676     }
677
678     return 1;
679 }
680
681 static const OSSL_DISPATCH core_dispatch_[] = {
682     { OSSL_FUNC_CORE_GET_PARAM_TYPES, (void (*)(void))core_get_param_types },
683     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
684     { OSSL_FUNC_CORE_PUT_ERROR, (void (*)(void))ERR_put_error },
685     { OSSL_FUNC_CORE_ADD_ERROR_VDATA, (void (*)(void))ERR_add_error_vdata },
686     { 0, NULL }
687 };
688 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;