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