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