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