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