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