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