fips module header inclusion fine-tunning
[openssl.git] / crypto / evp / keymgmt_lib.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 <openssl/core_names.h>
11 #include "internal/cryptlib.h"
12 #include "internal/nelem.h"
13 #include "crypto/evp.h"
14 #include "internal/core.h"
15 #include "internal/provider.h"
16 #include "evp_local.h"
17
18 /*
19  * match_type() checks if two EVP_KEYMGMT are matching key types.  This
20  * function assumes that the caller has made all the necessary NULL checks.
21  */
22 static int match_type(const EVP_KEYMGMT *keymgmt1, const EVP_KEYMGMT *keymgmt2)
23 {
24     const char *name2 = EVP_KEYMGMT_get0_name(keymgmt2);
25
26     return EVP_KEYMGMT_is_a(keymgmt1, name2);
27 }
28
29 int evp_keymgmt_util_try_import(const OSSL_PARAM params[], void *arg)
30 {
31     struct evp_keymgmt_util_try_import_data_st *data = arg;
32     int delete_on_error = 0;
33
34     /* Just in time creation of keydata */
35     if (data->keydata == NULL) {
36         if ((data->keydata = evp_keymgmt_newdata(data->keymgmt)) == NULL) {
37             ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
38             return 0;
39         }
40         delete_on_error = 1;
41     }
42
43     /*
44      * It's fine if there was no data to transfer, we just end up with an
45      * empty destination key.
46      */
47     if (params[0].key == NULL)
48         return 1;
49
50     if (evp_keymgmt_import(data->keymgmt, data->keydata, data->selection,
51                            params))
52         return 1;
53     if (delete_on_error) {
54         evp_keymgmt_freedata(data->keymgmt, data->keydata);
55         data->keydata = NULL;
56     }
57     return 0;
58 }
59
60 int evp_keymgmt_util_assign_pkey(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt,
61                                  void *keydata)
62 {
63     if (pkey == NULL || keymgmt == NULL || keydata == NULL
64         || !EVP_PKEY_set_type_by_keymgmt(pkey, keymgmt)) {
65         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
66         return 0;
67     }
68     pkey->keydata = keydata;
69     evp_keymgmt_util_cache_keyinfo(pkey);
70     return 1;
71 }
72
73 EVP_PKEY *evp_keymgmt_util_make_pkey(EVP_KEYMGMT *keymgmt, void *keydata)
74 {
75     EVP_PKEY *pkey = NULL;
76
77     if (keymgmt == NULL
78         || keydata == NULL
79         || (pkey = EVP_PKEY_new()) == NULL
80         || !evp_keymgmt_util_assign_pkey(pkey, keymgmt, keydata)) {
81         EVP_PKEY_free(pkey);
82         return NULL;
83     }
84     return pkey;
85 }
86
87 int evp_keymgmt_util_export(const EVP_PKEY *pk, int selection,
88                             OSSL_CALLBACK *export_cb, void *export_cbarg)
89 {
90     if (pk == NULL || export_cb == NULL)
91         return 0;
92     return evp_keymgmt_export(pk->keymgmt, pk->keydata, selection,
93                               export_cb, export_cbarg);
94 }
95
96 void *evp_keymgmt_util_export_to_provider(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt)
97 {
98     struct evp_keymgmt_util_try_import_data_st import_data;
99     OP_CACHE_ELEM *op;
100
101     /* Export to where? */
102     if (keymgmt == NULL)
103         return NULL;
104
105     /* If we have an unassigned key, give up */
106     if (pk->keydata == NULL)
107         return NULL;
108
109     /*
110      * If |keymgmt| matches the "origin" |keymgmt|, there is no more to do.
111      * The "origin" is determined by the |keymgmt| pointers being identical
112      * or when the provider and the name ID match.  The latter case handles the
113      * situation where the fetch cache is flushed and a "new" key manager is
114      * created.
115      */
116     if (pk->keymgmt == keymgmt
117         || (pk->keymgmt->name_id == keymgmt->name_id
118             && pk->keymgmt->prov == keymgmt->prov))
119         return pk->keydata;
120
121     if (!CRYPTO_THREAD_read_lock(pk->lock))
122         return NULL;
123     /*
124      * If the provider native "origin" hasn't changed since last time, we
125      * try to find our keymgmt in the operation cache.  If it has changed
126      * and our keymgmt isn't found, we will clear the cache further down.
127      */
128     if (pk->dirty_cnt == pk->dirty_cnt_copy) {
129         /* If this key is already exported to |keymgmt|, no more to do */
130         op = evp_keymgmt_util_find_operation_cache(pk, keymgmt);
131         if (op != NULL && op->keymgmt != NULL) {
132             void *ret = op->keydata;
133
134             CRYPTO_THREAD_unlock(pk->lock);
135             return ret;
136         }
137     }
138     CRYPTO_THREAD_unlock(pk->lock);
139
140     /* If the "origin" |keymgmt| doesn't support exporting, give up */
141     if (pk->keymgmt->export == NULL)
142         return NULL;
143
144     /*
145      * Make sure that the type of the keymgmt to export to matches the type
146      * of the "origin"
147      */
148     if (!ossl_assert(match_type(pk->keymgmt, keymgmt)))
149         return NULL;
150
151     /*
152      * We look at the already cached provider keys, and import from the
153      * first that supports it (i.e. use its export function), and export
154      * the imported data to the new provider.
155      */
156
157     /* Setup for the export callback */
158     import_data.keydata = NULL;  /* evp_keymgmt_util_try_import will create it */
159     import_data.keymgmt = keymgmt;
160     import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
161
162     /*
163      * The export function calls the callback (evp_keymgmt_util_try_import),
164      * which does the import for us.  If successful, we're done.
165      */
166     if (!evp_keymgmt_util_export(pk, OSSL_KEYMGMT_SELECT_ALL,
167                                  &evp_keymgmt_util_try_import, &import_data))
168         /* If there was an error, bail out */
169         return NULL;
170
171     if (!CRYPTO_THREAD_write_lock(pk->lock)) {
172         evp_keymgmt_freedata(keymgmt, import_data.keydata);
173         return NULL;
174     }
175     /* Check to make sure some other thread didn't get there first */
176     op = evp_keymgmt_util_find_operation_cache(pk, keymgmt);
177     if (op != NULL && op->keydata != NULL) {
178         void *ret = op->keydata;
179
180         CRYPTO_THREAD_unlock(pk->lock);
181
182         /*
183          * Another thread seemms to have already exported this so we abandon
184          * all the work we just did.
185          */
186         evp_keymgmt_freedata(keymgmt, import_data.keydata);
187
188         return ret;
189     }
190
191     /*
192      * If the dirty counter changed since last time, then clear the
193      * operation cache.  In that case, we know that |i| is zero.
194      */
195     if (pk->dirty_cnt != pk->dirty_cnt_copy)
196         evp_keymgmt_util_clear_operation_cache(pk, 0);
197
198     /* Add the new export to the operation cache */
199     if (!evp_keymgmt_util_cache_keydata(pk, keymgmt, import_data.keydata)) {
200         evp_keymgmt_freedata(keymgmt, import_data.keydata);
201         return NULL;
202     }
203
204     /* Synchronize the dirty count */
205     pk->dirty_cnt_copy = pk->dirty_cnt;
206
207     CRYPTO_THREAD_unlock(pk->lock);
208
209     return import_data.keydata;
210 }
211
212 static void op_cache_free(OP_CACHE_ELEM *e)
213 {
214     evp_keymgmt_freedata(e->keymgmt, e->keydata);
215     EVP_KEYMGMT_free(e->keymgmt);
216     OPENSSL_free(e);
217 }
218
219 int evp_keymgmt_util_clear_operation_cache(EVP_PKEY *pk, int locking)
220 {
221     if (pk != NULL) {
222         if (locking && pk->lock != NULL && !CRYPTO_THREAD_write_lock(pk->lock))
223             return 0;
224         sk_OP_CACHE_ELEM_pop_free(pk->operation_cache, op_cache_free);
225         pk->operation_cache = NULL;
226         if (locking && pk->lock != NULL)
227             CRYPTO_THREAD_unlock(pk->lock);
228     }
229
230     return 1;
231 }
232
233 OP_CACHE_ELEM *evp_keymgmt_util_find_operation_cache(EVP_PKEY *pk,
234                                                      EVP_KEYMGMT *keymgmt)
235 {
236     int i, end = sk_OP_CACHE_ELEM_num(pk->operation_cache);
237     OP_CACHE_ELEM *p;
238
239     /*
240      * A comparison and sk_P_CACHE_ELEM_find() are avoided to not cause
241      * problems when we've only a read lock.
242      */
243     for (i = 0; i < end; i++) {
244         p = sk_OP_CACHE_ELEM_value(pk->operation_cache, i);
245         if (keymgmt == p->keymgmt)
246             return p;
247     }
248     return NULL;
249 }
250
251 int evp_keymgmt_util_cache_keydata(EVP_PKEY *pk,
252                                    EVP_KEYMGMT *keymgmt, void *keydata)
253 {
254     OP_CACHE_ELEM *p = NULL;
255
256     if (keydata != NULL) {
257         if (pk->operation_cache == NULL) {
258             pk->operation_cache = sk_OP_CACHE_ELEM_new_null();
259             if (pk->operation_cache == NULL)
260                 return 0;
261         }
262
263         p = OPENSSL_malloc(sizeof(*p));
264         if (p == NULL)
265             return 0;
266         p->keydata = keydata;
267         p->keymgmt = keymgmt;
268
269         if (!EVP_KEYMGMT_up_ref(keymgmt)) {
270             OPENSSL_free(p);
271             return 0;
272         }
273
274         if (!sk_OP_CACHE_ELEM_push(pk->operation_cache, p)) {
275             EVP_KEYMGMT_free(keymgmt);
276             OPENSSL_free(p);
277             return 0;
278         }
279     }
280     return 1;
281 }
282
283 void evp_keymgmt_util_cache_keyinfo(EVP_PKEY *pk)
284 {
285     /*
286      * Cache information about the provider "origin" key.
287      *
288      * This services functions like EVP_PKEY_get_size, EVP_PKEY_get_bits, etc
289      */
290     if (pk->keydata != NULL) {
291         int bits = 0;
292         int security_bits = 0;
293         int size = 0;
294         OSSL_PARAM params[4];
295
296         params[0] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_BITS, &bits);
297         params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_SECURITY_BITS,
298                                              &security_bits);
299         params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_MAX_SIZE, &size);
300         params[3] = OSSL_PARAM_construct_end();
301         if (evp_keymgmt_get_params(pk->keymgmt, pk->keydata, params)) {
302             pk->cache.size = size;
303             pk->cache.bits = bits;
304             pk->cache.security_bits = security_bits;
305         }
306     }
307 }
308
309 void *evp_keymgmt_util_fromdata(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
310                                 int selection, const OSSL_PARAM params[])
311 {
312     void *keydata = NULL;
313
314     if ((keydata = evp_keymgmt_newdata(keymgmt)) == NULL
315         || !evp_keymgmt_import(keymgmt, keydata, selection, params)
316         || !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) {
317         evp_keymgmt_freedata(keymgmt, keydata);
318         keydata = NULL;
319     }
320     return keydata;
321 }
322
323 int evp_keymgmt_util_has(EVP_PKEY *pk, int selection)
324 {
325     /* Check if key is even assigned */
326     if (pk->keymgmt == NULL)
327         return 0;
328
329     return evp_keymgmt_has(pk->keymgmt, pk->keydata, selection);
330 }
331
332 /*
333  * evp_keymgmt_util_match() doesn't just look at the provider side "origin",
334  * but also in the operation cache to see if there's any common keymgmt that
335  * supplies OP_keymgmt_match.
336  *
337  * evp_keymgmt_util_match() adheres to the return values that EVP_PKEY_eq()
338  * and EVP_PKEY_parameters_eq() return, i.e.:
339  *
340  *  1   same key
341  *  0   not same key
342  * -1   not same key type
343  * -2   unsupported operation
344  */
345 int evp_keymgmt_util_match(EVP_PKEY *pk1, EVP_PKEY *pk2, int selection)
346 {
347     EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
348     void *keydata1 = NULL, *keydata2 = NULL;
349
350     if (pk1 == NULL || pk2 == NULL) {
351         if (pk1 == NULL && pk2 == NULL)
352             return 1;
353         return 0;
354     }
355
356     keymgmt1 = pk1->keymgmt;
357     keydata1 = pk1->keydata;
358     keymgmt2 = pk2->keymgmt;
359     keydata2 = pk2->keydata;
360
361     if (keymgmt1 != keymgmt2) {
362         /*
363          * The condition for a successful cross export is that the
364          * keydata to be exported is NULL (typed, but otherwise empty
365          * EVP_PKEY), or that it was possible to export it with
366          * evp_keymgmt_util_export_to_provider().
367          *
368          * We use |ok| to determine if it's ok to cross export one way,
369          * but also to determine if we should attempt a cross export
370          * the other way.  There's no point doing it both ways.
371          */
372         int ok = 1;
373
374         /* Complex case, where the keymgmt differ */
375         if (keymgmt1 != NULL
376             && keymgmt2 != NULL
377             && !match_type(keymgmt1, keymgmt2)) {
378             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
379             return -1;           /* Not the same type */
380         }
381
382         /*
383          * The key types are determined to match, so we try cross export,
384          * but only to keymgmt's that supply a matching function.
385          */
386         if (keymgmt2 != NULL
387             && keymgmt2->match != NULL) {
388             void *tmp_keydata = NULL;
389
390             ok = 1;
391             if (keydata1 != NULL) {
392                 tmp_keydata =
393                     evp_keymgmt_util_export_to_provider(pk1, keymgmt2);
394                 ok = (tmp_keydata != NULL);
395             }
396             if (ok) {
397                 keymgmt1 = keymgmt2;
398                 keydata1 = tmp_keydata;
399             }
400         }
401         /*
402          * If we've successfully cross exported one way, there's no point
403          * doing it the other way, hence the |!ok| check.
404          */
405         if (!ok
406             && keymgmt1 != NULL
407             && keymgmt1->match != NULL) {
408             void *tmp_keydata = NULL;
409
410             ok = 1;
411             if (keydata2 != NULL) {
412                 tmp_keydata =
413                     evp_keymgmt_util_export_to_provider(pk2, keymgmt1);
414                 ok = (tmp_keydata != NULL);
415             }
416             if (ok) {
417                 keymgmt2 = keymgmt1;
418                 keydata2 = tmp_keydata;
419             }
420         }
421     }
422
423     /* If we still don't have matching keymgmt implementations, we give up */
424     if (keymgmt1 != keymgmt2)
425         return -2;
426
427     /* If both keydata are NULL, then they're the same key */
428     if (keydata1 == NULL && keydata2 == NULL)
429         return 1;
430     /* If only one of the keydata is NULL, then they're different keys */
431     if (keydata1 == NULL || keydata2 == NULL)
432         return 0;
433     /* If both keydata are non-NULL, we let the backend decide */
434     return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
435 }
436
437 int evp_keymgmt_util_copy(EVP_PKEY *to, EVP_PKEY *from, int selection)
438 {
439     /* Save copies of pointers we want to play with without affecting |to| */
440     EVP_KEYMGMT *to_keymgmt = to->keymgmt;
441     void *to_keydata = to->keydata, *alloc_keydata = NULL;
442
443     /* An unassigned key can't be copied */
444     if (from == NULL || from->keydata == NULL)
445         return 0;
446
447     /*
448      * If |to| is unassigned, ensure it gets the same KEYMGMT as |from|,
449      * Note that the final setting of KEYMGMT is done further down, with
450      * EVP_PKEY_set_type_by_keymgmt(); we don't want to do that prematurely.
451      */
452     if (to_keymgmt == NULL)
453         to_keymgmt = from->keymgmt;
454
455     if (to_keymgmt == from->keymgmt && to_keymgmt->dup != NULL
456         && to_keydata == NULL) {
457         to_keydata = alloc_keydata = evp_keymgmt_dup(to_keymgmt,
458                                                      from->keydata,
459                                                      selection);
460         if (to_keydata == NULL)
461             return 0;
462     } else if (match_type(to_keymgmt, from->keymgmt)) {
463         struct evp_keymgmt_util_try_import_data_st import_data;
464
465         import_data.keymgmt = to_keymgmt;
466         import_data.keydata = to_keydata;
467         import_data.selection = selection;
468
469         if (!evp_keymgmt_util_export(from, selection,
470                                      &evp_keymgmt_util_try_import,
471                                      &import_data))
472             return 0;
473
474         /*
475          * In case to_keydata was previously unallocated,
476          * evp_keymgmt_util_try_import() may have created it for us.
477          */
478         if (to_keydata == NULL)
479             to_keydata = alloc_keydata = import_data.keydata;
480     } else {
481         ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
482         return 0;
483     }
484
485     /*
486      * We only need to set the |to| type when its |keymgmt| isn't set.
487      * We can then just set its |keydata| to what we have, which might
488      * be exactly what it had when entering this function.
489      * This is a bit different from using evp_keymgmt_util_assign_pkey(),
490      * which isn't as careful with |to|'s original |keymgmt|, since it's
491      * meant to forcibly reassign an EVP_PKEY no matter what, which is
492      * why we don't use that one here.
493      */
494     if (to->keymgmt == NULL
495         && !EVP_PKEY_set_type_by_keymgmt(to, to_keymgmt)) {
496         evp_keymgmt_freedata(to_keymgmt, alloc_keydata);
497         return 0;
498     }
499     to->keydata = to_keydata;
500     evp_keymgmt_util_cache_keyinfo(to);
501
502     return 1;
503 }
504
505 void *evp_keymgmt_util_gen(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
506                            void *genctx, OSSL_CALLBACK *cb, void *cbarg)
507 {
508     void *keydata = NULL;
509
510     if ((keydata = evp_keymgmt_gen(keymgmt, genctx, cb, cbarg)) == NULL
511         || !evp_keymgmt_util_assign_pkey(target, keymgmt, keydata)) {
512         evp_keymgmt_freedata(keymgmt, keydata);
513         keydata = NULL;
514     }
515
516     return keydata;
517 }
518
519 /*
520  * Returns the same numbers as EVP_PKEY_get_default_digest_name()
521  * When the string from the EVP_KEYMGMT implementation is "", we use
522  * SN_undef, since that corresponds to what EVP_PKEY_get_default_nid()
523  * returns for no digest.
524  */
525 int evp_keymgmt_util_get_deflt_digest_name(EVP_KEYMGMT *keymgmt,
526                                            void *keydata,
527                                            char *mdname, size_t mdname_sz)
528 {
529     OSSL_PARAM params[3];
530     char mddefault[100] = "";
531     char mdmandatory[100] = "";
532     char *result = NULL;
533     int rv = -2;
534
535     params[0] =
536         OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
537                                          mddefault, sizeof(mddefault));
538     params[1] =
539         OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
540                                          mdmandatory,
541                                          sizeof(mdmandatory));
542     params[2] = OSSL_PARAM_construct_end();
543
544     if (!evp_keymgmt_get_params(keymgmt, keydata, params))
545         return 0;
546
547     if (OSSL_PARAM_modified(params + 1)) {
548         if (params[1].return_size <= 1) /* Only a NUL byte */
549             result = SN_undef;
550         else
551             result = mdmandatory;
552         rv = 2;
553     } else if (OSSL_PARAM_modified(params)) {
554         if (params[0].return_size <= 1) /* Only a NUL byte */
555             result = SN_undef;
556         else
557             result = mddefault;
558         rv = 1;
559     }
560     if (rv > 0)
561         OPENSSL_strlcpy(mdname, result, mdname_sz);
562     return rv;
563 }