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