9c11da697efd0590b7bc5e331a5b028159fc51f9
[openssl.git] / crypto / evp / p_lib.c
1 /*
2  * Copyright 1995-2018 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 /*
11  * DSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include "internal/refcount.h"
19 #include <openssl/bn.h>
20 #include <openssl/err.h>
21 #include <openssl/objects.h>
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 #include <openssl/rsa.h>
25 #include <openssl/dsa.h>
26 #include <openssl/dh.h>
27 #include <openssl/cmac.h>
28 #include <openssl/engine.h>
29 #include <openssl/params.h>
30 #include <openssl/serializer.h>
31 #include <openssl/core_names.h>
32
33 #include "crypto/asn1.h"
34 #include "crypto/evp.h"
35 #include "internal/provider.h"
36 #include "evp_local.h"
37
38 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
39                          int len, EVP_KEYMGMT *keymgmt);
40 static void evp_pkey_free_it(EVP_PKEY *key);
41
42 #ifndef FIPS_MODE
43
44 int EVP_PKEY_bits(const EVP_PKEY *pkey)
45 {
46     if (pkey != NULL) {
47         if (pkey->ameth == NULL)
48             return pkey->cache.bits;
49         else if (pkey->ameth->pkey_bits)
50             return pkey->ameth->pkey_bits(pkey);
51     }
52     return 0;
53 }
54
55 int EVP_PKEY_security_bits(const EVP_PKEY *pkey)
56 {
57     if (pkey == NULL)
58         return 0;
59     if (pkey->ameth == NULL)
60         return pkey->cache.security_bits;
61     if (pkey->ameth->pkey_security_bits == NULL)
62         return -2;
63     return pkey->ameth->pkey_security_bits(pkey);
64 }
65
66 int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
67 {
68 # ifndef OPENSSL_NO_DSA
69     if (pkey->type == EVP_PKEY_DSA) {
70         int ret = pkey->save_parameters;
71
72         if (mode >= 0)
73             pkey->save_parameters = mode;
74         return ret;
75     }
76 # endif
77 # ifndef OPENSSL_NO_EC
78     if (pkey->type == EVP_PKEY_EC) {
79         int ret = pkey->save_parameters;
80
81         if (mode >= 0)
82             pkey->save_parameters = mode;
83         return ret;
84     }
85 # endif
86     return 0;
87 }
88
89 int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
90 {
91     /*
92      * TODO: clean up legacy stuff from this function when legacy support
93      * is gone.
94      */
95
96     /*
97      * Only check that type match this early when both keys are legacy.
98      * If either of them is provided, we let evp_keymgmt_util_copy()
99      * do this check, after having exported either of them that isn't
100      * provided.
101      */
102     if (to->keymgmt == NULL && from->keymgmt == NULL) {
103         if (to->type == EVP_PKEY_NONE) {
104             if (EVP_PKEY_set_type(to, from->type) == 0)
105                 return 0;
106         } else if (to->type != from->type) {
107             EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_KEY_TYPES);
108             goto err;
109         }
110     }
111
112     if (EVP_PKEY_missing_parameters(from)) {
113         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_MISSING_PARAMETERS);
114         goto err;
115     }
116
117     if (!EVP_PKEY_missing_parameters(to)) {
118         if (EVP_PKEY_cmp_parameters(to, from) == 1)
119             return 1;
120         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_PARAMETERS);
121         return 0;
122     }
123
124     /*
125      * If |from| is provided, we upgrade |to| to be provided as well.
126      * This drops the legacy key from |to|.
127      * evp_pkey_upgrade_to_provider() checks if |to| is already provided,
128      * we don't need to do that here.
129      *
130      * TODO(3.0) We should investigate if that's too aggressive and make
131      * this scenario unsupported instead.
132      */
133     if (from->keymgmt != NULL) {
134         EVP_KEYMGMT *tmp_keymgmt = from->keymgmt;
135
136         /*
137          * The returned pointer is known to be cached, so we don't have to
138          * save it.  However, if it's NULL, something went wrong and we can't
139          * copy.
140          */
141         if (evp_pkey_upgrade_to_provider(to, NULL,
142                                          &tmp_keymgmt, NULL) == NULL) {
143             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
144             return 0;
145         }
146     }
147
148     /* For purely provided keys, we just call the keymgmt utility */
149     if (to->keymgmt != NULL && from->keymgmt != NULL)
150         return evp_keymgmt_util_copy(to, (EVP_PKEY *)from,
151                                      OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
152
153     /*
154      * If |to| is provided, we know that |from| is legacy at this point.
155      * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_copy()
156      * to copy the appropriate data to |to|'s keydata.
157      */
158     if (to->keymgmt != NULL) {
159         EVP_KEYMGMT *to_keymgmt = to->keymgmt;
160         void *from_keydata =
161             evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt,
162                                         NULL);
163
164         if (from_keydata == NULL) {
165             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
166             return 0;
167         }
168         return evp_keymgmt_copy(to->keymgmt, to->keydata, from_keydata,
169                                 OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
170     }
171
172     /* Both keys are legacy */
173     if (from->ameth != NULL && from->ameth->param_copy != NULL)
174         return from->ameth->param_copy(to, from);
175  err:
176     return 0;
177 }
178
179 int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
180 {
181     if (pkey != NULL) {
182         if (pkey->keymgmt != NULL)
183             return !evp_keymgmt_util_has((EVP_PKEY *)pkey,
184                                          OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
185         else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL)
186             return pkey->ameth->param_missing(pkey);
187     }
188     return 0;
189 }
190
191 /*
192  * This function is called for any mixture of keys except pure legacy pair.
193  * TODO When legacy keys are gone, we replace a call to this functions with
194  * a call to evp_keymgmt_util_match().
195  */
196 static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b,
197                             int selection)
198 {
199     EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
200     void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL;
201
202     /* If none of them are provided, this function shouldn't have been called */
203     if (!ossl_assert(a->keymgmt != NULL || b->keymgmt != NULL))
204         return -2;
205
206     /* For purely provided keys, we just call the keymgmt utility */
207     if (a->keymgmt != NULL && b->keymgmt != NULL)
208         return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection);
209
210     /*
211      * Here, we know that we have a mixture of legacy and provided keys.
212      * Try cross export and compare the resulting key data.
213      */
214     keymgmt1 = a->keymgmt;
215     keydata1 = a->keydata;
216     keymgmt2 = b->keymgmt;
217     keydata2 = b->keydata;
218
219     if ((keymgmt1 == NULL
220          && !EVP_KEYMGMT_is_a(keymgmt2, OBJ_nid2sn(a->type)))
221         || (keymgmt2 == NULL
222             && !EVP_KEYMGMT_is_a(keymgmt1, OBJ_nid2sn(b->type))))
223         return -1;               /* not the same key type */
224
225     if (keymgmt2 != NULL && keymgmt2->match != NULL) {
226         tmp_keydata =
227             evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL);
228         if (tmp_keydata != NULL) {
229             keymgmt1 = keymgmt2;
230             keydata1 = tmp_keydata;
231         }
232     }
233     if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) {
234         tmp_keydata =
235             evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL);
236         if (tmp_keydata != NULL) {
237             keymgmt2 = keymgmt1;
238             keydata2 = tmp_keydata;
239         }
240     }
241
242     /* If we still don't have matching keymgmt implementations, we give up */
243     if (keymgmt1 != keymgmt2)
244         return -2;
245
246     return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
247 }
248
249 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
250 {
251     /*
252      * TODO: clean up legacy stuff from this function when legacy support
253      * is gone.
254      */
255
256     if (a->keymgmt != NULL || b->keymgmt != NULL)
257         return evp_pkey_cmp_any(a, b, OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
258
259     /* All legacy keys */
260     if (a->type != b->type)
261         return -1;
262     if (a->ameth != NULL && a->ameth->param_cmp != NULL)
263         return a->ameth->param_cmp(a, b);
264     return -2;
265 }
266
267 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
268 {
269     /*
270      * TODO: clean up legacy stuff from this function when legacy support
271      * is gone.
272      */
273
274     if (a->keymgmt != NULL || b->keymgmt != NULL)
275         return evp_pkey_cmp_any(a, b,
276                                 OSSL_KEYMGMT_SELECT_ALL_PARAMETERS
277                                 | OSSL_KEYMGMT_SELECT_PUBLIC_KEY);
278
279     /* All legacy keys */
280     if (a->type != b->type)
281         return -1;
282
283     if (a->ameth != NULL) {
284         int ret;
285         /* Compare parameters if the algorithm has them */
286         if (a->ameth->param_cmp != NULL) {
287             ret = a->ameth->param_cmp(a, b);
288             if (ret <= 0)
289                 return ret;
290         }
291
292         if (a->ameth->pub_cmp != NULL)
293             return a->ameth->pub_cmp(a, b);
294     }
295
296     return -2;
297 }
298
299 EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
300                                        const unsigned char *priv,
301                                        size_t len)
302 {
303     EVP_PKEY *ret = EVP_PKEY_new();
304
305     if (ret == NULL
306         || !pkey_set_type(ret, e, type, NULL, -1, NULL)) {
307         /* EVPerr already called */
308         goto err;
309     }
310
311     if (ret->ameth->set_priv_key == NULL) {
312         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY,
313                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
314         goto err;
315     }
316
317     if (!ret->ameth->set_priv_key(ret, priv, len)) {
318         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY, EVP_R_KEY_SETUP_FAILED);
319         goto err;
320     }
321
322     return ret;
323
324  err:
325     EVP_PKEY_free(ret);
326     return NULL;
327 }
328
329 EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
330                                       const unsigned char *pub,
331                                       size_t len)
332 {
333     EVP_PKEY *ret = EVP_PKEY_new();
334
335     if (ret == NULL
336         || !pkey_set_type(ret, e, type, NULL, -1, NULL)) {
337         /* EVPerr already called */
338         goto err;
339     }
340
341     if (ret->ameth->set_pub_key == NULL) {
342         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY,
343                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
344         goto err;
345     }
346
347     if (!ret->ameth->set_pub_key(ret, pub, len)) {
348         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY, EVP_R_KEY_SETUP_FAILED);
349         goto err;
350     }
351
352     return ret;
353
354  err:
355     EVP_PKEY_free(ret);
356     return NULL;
357 }
358
359 int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
360                                  size_t *len)
361 {
362      if (pkey->ameth->get_priv_key == NULL) {
363         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY,
364                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
365         return 0;
366     }
367
368     if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
369         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY, EVP_R_GET_RAW_KEY_FAILED);
370         return 0;
371     }
372
373     return 1;
374 }
375
376 int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
377                                 size_t *len)
378 {
379      if (pkey->ameth->get_pub_key == NULL) {
380         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY,
381                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
382         return 0;
383     }
384
385     if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
386         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY, EVP_R_GET_RAW_KEY_FAILED);
387         return 0;
388     }
389
390     return 1;
391 }
392
393 EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
394                                 size_t len, const EVP_CIPHER *cipher)
395 {
396 # ifndef OPENSSL_NO_CMAC
397 #  ifndef OPENSSL_NO_ENGINE
398     const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
399 #  endif
400     const char *cipher_name = EVP_CIPHER_name(cipher);
401     const OSSL_PROVIDER *prov = EVP_CIPHER_provider(cipher);
402     OPENSSL_CTX *libctx =
403         prov == NULL ? NULL : ossl_provider_library_context(prov);
404     EVP_PKEY *ret = EVP_PKEY_new();
405     EVP_MAC *cmac = EVP_MAC_fetch(libctx, OSSL_MAC_NAME_CMAC, NULL);
406     EVP_MAC_CTX *cmctx = cmac != NULL ? EVP_MAC_CTX_new(cmac) : NULL;
407     OSSL_PARAM params[4];
408     size_t paramsn = 0;
409
410     if (ret == NULL
411         || cmctx == NULL
412         || !pkey_set_type(ret, e, EVP_PKEY_CMAC, NULL, -1, NULL)) {
413         /* EVPerr already called */
414         goto err;
415     }
416
417 #  ifndef OPENSSL_NO_ENGINE
418     if (engine_id != NULL)
419         params[paramsn++] =
420             OSSL_PARAM_construct_utf8_string("engine", (char *)engine_id, 0);
421 #  endif
422
423     params[paramsn++] =
424         OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
425                                          (char *)cipher_name, 0);
426     params[paramsn++] =
427         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
428                                           (char *)priv, len);
429     params[paramsn] = OSSL_PARAM_construct_end();
430
431     if (!EVP_MAC_CTX_set_params(cmctx, params)) {
432         EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY, EVP_R_KEY_SETUP_FAILED);
433         goto err;
434     }
435
436     ret->pkey.ptr = cmctx;
437     return ret;
438
439  err:
440     EVP_PKEY_free(ret);
441     EVP_MAC_CTX_free(cmctx);
442     EVP_MAC_free(cmac);
443     return NULL;
444 # else
445     EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY,
446            EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
447     return NULL;
448 # endif
449 }
450
451 int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
452 {
453     return pkey_set_type(pkey, NULL, type, NULL, -1, NULL);
454 }
455
456 int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
457 {
458     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL);
459 }
460
461 int EVP_PKEY_set_alias_type(EVP_PKEY *pkey, int type)
462 {
463     if (pkey->type == type) {
464         return 1; /* it already is that type */
465     }
466
467     /*
468      * The application is requesting to alias this to a different pkey type,
469      * but not one that resolves to the base type.
470      */
471     if (EVP_PKEY_type(type) != EVP_PKEY_base_id(pkey)) {
472         EVPerr(EVP_F_EVP_PKEY_SET_ALIAS_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
473         return 0;
474     }
475
476     pkey->type = type;
477     return 1;
478 }
479
480 # ifndef OPENSSL_NO_ENGINE
481 int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
482 {
483     if (e != NULL) {
484         if (!ENGINE_init(e)) {
485             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, ERR_R_ENGINE_LIB);
486             return 0;
487         }
488         if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
489             ENGINE_finish(e);
490             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, EVP_R_UNSUPPORTED_ALGORITHM);
491             return 0;
492         }
493     }
494     ENGINE_finish(pkey->pmeth_engine);
495     pkey->pmeth_engine = e;
496     return 1;
497 }
498
499 ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
500 {
501     return pkey->engine;
502 }
503 # endif
504 int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
505 {
506     int alias = type;
507
508 #ifndef OPENSSL_NO_EC
509     if (EVP_PKEY_type(type) == EVP_PKEY_EC) {
510         const EC_GROUP *group = EC_KEY_get0_group(key);
511
512         if (group != NULL && EC_GROUP_get_curve_name(group) == NID_sm2)
513             alias = EVP_PKEY_SM2;
514     }
515 #endif
516
517     if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
518         return 0;
519     if (!EVP_PKEY_set_alias_type(pkey, alias))
520         return 0;
521     pkey->pkey.ptr = key;
522     return (key != NULL);
523 }
524
525 void *EVP_PKEY_get0(const EVP_PKEY *pkey)
526 {
527     return pkey->pkey.ptr;
528 }
529
530 const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
531 {
532     ASN1_OCTET_STRING *os = NULL;
533     if (pkey->type != EVP_PKEY_HMAC) {
534         EVPerr(EVP_F_EVP_PKEY_GET0_HMAC, EVP_R_EXPECTING_AN_HMAC_KEY);
535         return NULL;
536     }
537     os = EVP_PKEY_get0(pkey);
538     *len = os->length;
539     return os->data;
540 }
541
542 # ifndef OPENSSL_NO_POLY1305
543 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
544 {
545     ASN1_OCTET_STRING *os = NULL;
546     if (pkey->type != EVP_PKEY_POLY1305) {
547         EVPerr(EVP_F_EVP_PKEY_GET0_POLY1305, EVP_R_EXPECTING_A_POLY1305_KEY);
548         return NULL;
549     }
550     os = EVP_PKEY_get0(pkey);
551     *len = os->length;
552     return os->data;
553 }
554 # endif
555
556 # ifndef OPENSSL_NO_SIPHASH
557 const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
558 {
559     ASN1_OCTET_STRING *os = NULL;
560
561     if (pkey->type != EVP_PKEY_SIPHASH) {
562         EVPerr(EVP_F_EVP_PKEY_GET0_SIPHASH, EVP_R_EXPECTING_A_SIPHASH_KEY);
563         return NULL;
564     }
565     os = EVP_PKEY_get0(pkey);
566     *len = os->length;
567     return os->data;
568 }
569 # endif
570
571 # ifndef OPENSSL_NO_RSA
572 int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key)
573 {
574     int ret = EVP_PKEY_assign_RSA(pkey, key);
575     if (ret)
576         RSA_up_ref(key);
577     return ret;
578 }
579
580 RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey)
581 {
582     if (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_RSA_PSS) {
583         EVPerr(EVP_F_EVP_PKEY_GET0_RSA, EVP_R_EXPECTING_AN_RSA_KEY);
584         return NULL;
585     }
586     return pkey->pkey.rsa;
587 }
588
589 RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey)
590 {
591     RSA *ret = EVP_PKEY_get0_RSA(pkey);
592     if (ret != NULL)
593         RSA_up_ref(ret);
594     return ret;
595 }
596 # endif
597
598 # ifndef OPENSSL_NO_DSA
599 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
600 {
601     int ret = EVP_PKEY_assign_DSA(pkey, key);
602     if (ret)
603         DSA_up_ref(key);
604     return ret;
605 }
606
607 DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
608 {
609     if (pkey->type != EVP_PKEY_DSA) {
610         EVPerr(EVP_F_EVP_PKEY_GET0_DSA, EVP_R_EXPECTING_A_DSA_KEY);
611         return NULL;
612     }
613     return pkey->pkey.dsa;
614 }
615
616 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
617 {
618     DSA *ret = EVP_PKEY_get0_DSA(pkey);
619     if (ret != NULL)
620         DSA_up_ref(ret);
621     return ret;
622 }
623 # endif
624
625 # ifndef OPENSSL_NO_EC
626
627 int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key)
628 {
629     int ret = EVP_PKEY_assign_EC_KEY(pkey, key);
630     if (ret)
631         EC_KEY_up_ref(key);
632     return ret;
633 }
634
635 EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey)
636 {
637     if (EVP_PKEY_base_id(pkey) != EVP_PKEY_EC) {
638         EVPerr(EVP_F_EVP_PKEY_GET0_EC_KEY, EVP_R_EXPECTING_A_EC_KEY);
639         return NULL;
640     }
641     return pkey->pkey.ec;
642 }
643
644 EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey)
645 {
646     EC_KEY *ret = EVP_PKEY_get0_EC_KEY(pkey);
647     if (ret != NULL)
648         EC_KEY_up_ref(ret);
649     return ret;
650 }
651 # endif
652
653 # ifndef OPENSSL_NO_DH
654
655 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key)
656 {
657     int type = DH_get0_q(key) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
658     int ret = EVP_PKEY_assign(pkey, type, key);
659
660     if (ret)
661         DH_up_ref(key);
662     return ret;
663 }
664
665 DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
666 {
667     if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
668         EVPerr(EVP_F_EVP_PKEY_GET0_DH, EVP_R_EXPECTING_A_DH_KEY);
669         return NULL;
670     }
671     return pkey->pkey.dh;
672 }
673
674 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
675 {
676     DH *ret = EVP_PKEY_get0_DH(pkey);
677     if (ret != NULL)
678         DH_up_ref(ret);
679     return ret;
680 }
681 # endif
682
683 int EVP_PKEY_type(int type)
684 {
685     int ret;
686     const EVP_PKEY_ASN1_METHOD *ameth;
687     ENGINE *e;
688     ameth = EVP_PKEY_asn1_find(&e, type);
689     if (ameth)
690         ret = ameth->pkey_id;
691     else
692         ret = NID_undef;
693 # ifndef OPENSSL_NO_ENGINE
694     ENGINE_finish(e);
695 # endif
696     return ret;
697 }
698
699 int EVP_PKEY_id(const EVP_PKEY *pkey)
700 {
701     return pkey->type;
702 }
703
704 int EVP_PKEY_base_id(const EVP_PKEY *pkey)
705 {
706     return EVP_PKEY_type(pkey->type);
707 }
708
709
710 static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
711 {
712     BIO_set_indent(*out, saved_indent);
713     if (pop_f_prefix) {
714         BIO *next = BIO_pop(*out);
715
716         BIO_free(*out);
717         *out = next;
718     }
719     return 1;
720 }
721
722 static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
723                             long indent)
724 {
725     *pop_f_prefix = 0;
726     *saved_indent = 0;
727     if (indent > 0) {
728         long i = BIO_get_indent(*out);
729
730         *saved_indent =  (i < 0 ? 0 : i);
731         if (BIO_set_indent(*out, indent) <= 0) {
732             if ((*out = BIO_push(BIO_new(BIO_f_prefix()), *out)) == NULL)
733                 return 0;
734             *pop_f_prefix = 1;
735         }
736         if (BIO_set_indent(*out, indent) <= 0) {
737             print_reset_indent(out, *pop_f_prefix, *saved_indent);
738             return 0;
739         }
740     }
741     return 1;
742 }
743
744 static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
745                      const char *kstr)
746 {
747     return BIO_indent(out, indent, 128)
748         && BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
749                       kstr, OBJ_nid2ln(pkey->type)) > 0;
750 }
751
752 static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
753                       const char *propquery /* For provided serialization */,
754                       int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
755                                           int indent, ASN1_PCTX *pctx),
756                       ASN1_PCTX *legacy_pctx /* For legacy print */)
757 {
758     int pop_f_prefix;
759     long saved_indent;
760     OSSL_SERIALIZER_CTX *ctx = NULL;
761     int ret = -2;                /* default to unsupported */
762
763     if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
764         return 0;
765
766     ctx = OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(pkey, propquery);
767     if (OSSL_SERIALIZER_CTX_get_serializer(ctx) != NULL)
768         ret = OSSL_SERIALIZER_to_bio(ctx, out);
769     OSSL_SERIALIZER_CTX_free(ctx);
770
771     if (ret != -2)
772         goto end;
773
774     /* legacy fallback */
775     if (legacy_print != NULL)
776         ret = legacy_print(out, pkey, 0, legacy_pctx);
777     else
778         ret = unsup_alg(out, pkey, 0, "Public Key");
779
780  end:
781     print_reset_indent(&out, pop_f_prefix, saved_indent);
782     return ret;
783 }
784
785 int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
786                           int indent, ASN1_PCTX *pctx)
787 {
788     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PUBKEY_TO_TEXT_PQ,
789                       (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
790                       pctx);
791 }
792
793 int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
794                            int indent, ASN1_PCTX *pctx)
795 {
796     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PrivateKey_TO_TEXT_PQ,
797                       (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL),
798                       pctx);
799 }
800
801 int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
802                           int indent, ASN1_PCTX *pctx)
803 {
804     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_Parameters_TO_TEXT_PQ,
805                       (pkey->ameth != NULL ? pkey->ameth->param_print : NULL),
806                       pctx);
807 }
808
809 static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op,
810                                      int arg1, void *arg2)
811 {
812     if (pkey->keymgmt == NULL)
813         return 0;
814     switch (op) {
815     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
816         {
817             char mdname[80] = "";
818             int nid;
819             int rv = EVP_PKEY_get_default_digest_name(pkey, mdname,
820                                                       sizeof(mdname));
821
822             if (rv <= 0)
823                 return rv;
824             nid = OBJ_sn2nid(mdname);
825             if (nid == NID_undef)
826                 nid = OBJ_ln2nid(mdname);
827             if (nid == NID_undef)
828                 return 0;
829             *(int *)arg2 = nid;
830             return 1;
831         }
832     default:
833         return -2;
834     }
835 }
836
837 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
838 {
839     if (pkey->ameth == NULL)
840         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
841     if (pkey->ameth->pkey_ctrl == NULL)
842         return -2;
843     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
844 }
845
846 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
847 {
848     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
849 }
850
851 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
852                                      char *mdname, size_t mdname_sz)
853 {
854     if (pkey->ameth == NULL) {
855         OSSL_PARAM params[3];
856         char mddefault[100] = "";
857         char mdmandatory[100] = "";
858
859         params[0] =
860             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
861                                              mddefault, sizeof(mddefault));
862         params[1] =
863             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
864                                              mdmandatory,
865                                              sizeof(mdmandatory));
866         params[2] = OSSL_PARAM_construct_end();
867         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
868             return 0;
869         if (mdmandatory[0] != '\0') {
870             OPENSSL_strlcpy(mdname, mdmandatory, mdname_sz);
871             return 2;
872         }
873         OPENSSL_strlcpy(mdname, mddefault, mdname_sz);
874         return 1;
875     }
876
877     {
878         int nid = NID_undef;
879         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
880         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
881
882         if (rv > 0)
883             OPENSSL_strlcpy(mdname, name, mdname_sz);
884         return rv;
885     }
886 }
887
888 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
889 {
890     int rv, default_nid;
891
892     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
893     if (rv == -2) {
894         /*
895          * If there is a mandatory default digest and this isn't it, then
896          * the answer is 'no'.
897          */
898         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
899         if (rv == 2)
900             return (nid == default_nid);
901         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
902         if (rv == 0)
903             return -1;
904     }
905     return rv;
906 }
907
908 int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey,
909                                const unsigned char *pt, size_t ptlen)
910 {
911     if (ptlen > INT_MAX)
912         return 0;
913     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, ptlen,
914                            (void *)pt) <= 0)
915         return 0;
916     return 1;
917 }
918
919 size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *pkey, unsigned char **ppt)
920 {
921     int rv;
922     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppt);
923     if (rv <= 0)
924         return 0;
925     return rv;
926 }
927
928 #endif /* FIPS_MODE */
929
930 /*- All methods below can also be used in FIPS_MODE */
931
932 EVP_PKEY *EVP_PKEY_new(void)
933 {
934     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
935
936     if (ret == NULL) {
937         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
938         return NULL;
939     }
940     ret->type = EVP_PKEY_NONE;
941     ret->save_type = EVP_PKEY_NONE;
942     ret->references = 1;
943     ret->save_parameters = 1;
944     ret->lock = CRYPTO_THREAD_lock_new();
945     if (ret->lock == NULL) {
946         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
947         OPENSSL_free(ret);
948         return NULL;
949     }
950     return ret;
951 }
952
953 /*
954  * Setup a public key management method.
955  *
956  * For legacy keys, either |type| or |str| is expected to have the type
957  * information.  In this case, the setup consists of finding an ASN1 method
958  * and potentially an ENGINE, and setting those fields in |pkey|.
959  *
960  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
961  * case, the setup consists of setting the |keymgmt| field in |pkey|.
962  *
963  * If pkey is NULL just return 1 or 0 if the key management method exists.
964  */
965
966 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
967                          int len, EVP_KEYMGMT *keymgmt)
968 {
969 #ifndef FIPS_MODE
970     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
971     ENGINE **eptr = (e == NULL) ? &e :  NULL;
972 #endif
973
974     /*
975      * The setups can't set both legacy and provider side methods.
976      * It is forbidden
977      */
978     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
979         || !ossl_assert(e == NULL || keymgmt == NULL)) {
980         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
981         return 0;
982     }
983
984     if (pkey != NULL) {
985         int free_it = 0;
986
987 #ifndef FIPS_MODE
988         free_it = free_it || pkey->pkey.ptr != NULL;
989 #endif
990         free_it = free_it || pkey->keydata != NULL;
991         if (free_it)
992             evp_pkey_free_it(pkey);
993 #ifndef FIPS_MODE
994         /*
995          * If key type matches and a method exists then this lookup has
996          * succeeded once so just indicate success.
997          */
998         if (pkey->type != EVP_PKEY_NONE
999             && type == pkey->save_type
1000             && pkey->ameth != NULL)
1001             return 1;
1002 # ifndef OPENSSL_NO_ENGINE
1003         /* If we have ENGINEs release them */
1004         ENGINE_finish(pkey->engine);
1005         pkey->engine = NULL;
1006         ENGINE_finish(pkey->pmeth_engine);
1007         pkey->pmeth_engine = NULL;
1008 # endif
1009 #endif
1010     }
1011 #ifndef FIPS_MODE
1012     if (str != NULL)
1013         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1014     else if (type != EVP_PKEY_NONE)
1015         ameth = EVP_PKEY_asn1_find(eptr, type);
1016 # ifndef OPENSSL_NO_ENGINE
1017     if (pkey == NULL && eptr != NULL)
1018         ENGINE_finish(e);
1019 # endif
1020 #endif
1021
1022
1023     {
1024         int check = 1;
1025
1026 #ifndef FIPS_MODE
1027         check = check && ameth == NULL;
1028 #endif
1029         check = check && keymgmt == NULL;
1030         if (check) {
1031             EVPerr(EVP_F_PKEY_SET_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
1032             return 0;
1033         }
1034     }
1035     if (pkey != NULL) {
1036         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1037             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1038             return 0;
1039         }
1040
1041         pkey->keymgmt = keymgmt;
1042
1043         pkey->save_type = type;
1044         pkey->type = type;
1045
1046 #ifndef FIPS_MODE
1047         /*
1048          * If the internal "origin" key is provider side, don't save |ameth|.
1049          * The main reason is that |ameth| is one factor to detect that the
1050          * internal "origin" key is a legacy one.
1051          */
1052         if (keymgmt == NULL)
1053             pkey->ameth = ameth;
1054         pkey->engine = e;
1055
1056         /*
1057          * The EVP_PKEY_ASN1_METHOD |pkey_id| serves different purposes,
1058          * depending on if we're setting this key to contain a legacy or
1059          * a provider side "origin" key.  For a legacy key, we assign it
1060          * to the |type| field, but for a provider side key, we assign it
1061          * to the |save_type| field, because |type| is supposed to be set
1062          * to EVP_PKEY_NONE in that case.
1063          */
1064         if (keymgmt != NULL)
1065             pkey->save_type = ameth->pkey_id;
1066         else if (pkey->ameth != NULL)
1067             pkey->type = ameth->pkey_id;
1068 #endif
1069     }
1070     return 1;
1071 }
1072
1073 #ifndef FIPS_MODE
1074 static void find_ameth(const char *name, void *data)
1075 {
1076     const char **str = data;
1077
1078     /*
1079      * The error messages from pkey_set_type() are uninteresting here,
1080      * and misleading.
1081      */
1082     ERR_set_mark();
1083
1084     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1085                       NULL)) {
1086         if (str[0] == NULL)
1087             str[0] = name;
1088         else if (str[1] == NULL)
1089             str[1] = name;
1090     }
1091
1092     ERR_pop_to_mark();
1093 }
1094 #endif
1095
1096 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1097 {
1098 #ifndef FIPS_MODE
1099 # define EVP_PKEY_TYPE_STR str[0]
1100 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1101     /*
1102      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1103      * Ideally, only one should be found.  If two (or more) are found, the
1104      * match is ambiguous.  This should never happen, but...
1105      */
1106     const char *str[2] = { NULL, NULL };
1107
1108     EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str);
1109     if (str[1] != NULL) {
1110         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1111         return 0;
1112     }
1113 #else
1114 # define EVP_PKEY_TYPE_STR NULL
1115 # define EVP_PKEY_TYPE_STRLEN -1
1116 #endif
1117     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1118                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1119                          keymgmt);
1120
1121 #undef EVP_PKEY_TYPE_STR
1122 #undef EVP_PKEY_TYPE_STRLEN
1123 }
1124
1125 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1126 {
1127     int i;
1128
1129     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
1130         return 0;
1131
1132     REF_PRINT_COUNT("EVP_PKEY", pkey);
1133     REF_ASSERT_ISNT(i < 2);
1134     return ((i > 1) ? 1 : 0);
1135 }
1136
1137 #ifndef FIPS_MODE
1138 void evp_pkey_free_legacy(EVP_PKEY *x)
1139 {
1140     if (x->ameth != NULL) {
1141         if (x->ameth->pkey_free != NULL)
1142             x->ameth->pkey_free(x);
1143         x->pkey.ptr = NULL;
1144     }
1145 # ifndef OPENSSL_NO_ENGINE
1146     ENGINE_finish(x->engine);
1147     x->engine = NULL;
1148     ENGINE_finish(x->pmeth_engine);
1149     x->pmeth_engine = NULL;
1150 # endif
1151     x->type = EVP_PKEY_NONE;
1152 }
1153 #endif  /* FIPS_MODE */
1154
1155 static void evp_pkey_free_it(EVP_PKEY *x)
1156 {
1157     /* internal function; x is never NULL */
1158
1159     evp_keymgmt_util_clear_operation_cache(x);
1160 #ifndef FIPS_MODE
1161     evp_pkey_free_legacy(x);
1162 #endif
1163
1164     if (x->keymgmt != NULL) {
1165         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1166         EVP_KEYMGMT_free(x->keymgmt);
1167         x->keymgmt = NULL;
1168         x->keydata = NULL;
1169     }
1170 }
1171
1172 void EVP_PKEY_free(EVP_PKEY *x)
1173 {
1174     int i;
1175
1176     if (x == NULL)
1177         return;
1178
1179     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
1180     REF_PRINT_COUNT("EVP_PKEY", x);
1181     if (i > 0)
1182         return;
1183     REF_ASSERT_ISNT(i < 0);
1184     evp_pkey_free_it(x);
1185     CRYPTO_THREAD_lock_free(x->lock);
1186 #ifndef FIPS_MODE
1187     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1188 #endif
1189     OPENSSL_free(x);
1190 }
1191
1192 int EVP_PKEY_size(const EVP_PKEY *pkey)
1193 {
1194     int size = 0;
1195
1196     if (pkey != NULL) {
1197         size = pkey->cache.size;
1198 #ifndef FIPS_MODE
1199         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1200             size = pkey->ameth->pkey_size(pkey);
1201 #endif
1202     }
1203     return size;
1204 }
1205
1206 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
1207                                   EVP_KEYMGMT **keymgmt,
1208                                   const char *propquery)
1209 {
1210     EVP_KEYMGMT *allocated_keymgmt = NULL;
1211     EVP_KEYMGMT *tmp_keymgmt = NULL;
1212     void *keydata = NULL;
1213     int check;
1214
1215     if (pk == NULL)
1216         return NULL;
1217
1218     /* No key data => nothing to export */
1219     check = 1;
1220 #ifndef FIPS_MODE
1221     check = check && pk->pkey.ptr == NULL;
1222 #endif
1223     check = check && pk->keydata == NULL;
1224     if (check)
1225         return NULL;
1226
1227 #ifndef FIPS_MODE
1228     if (pk->pkey.ptr != NULL) {
1229         /*
1230          * If the legacy key doesn't have an dirty counter or export function,
1231          * give up
1232          */
1233         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1234             return NULL;
1235     }
1236 #endif
1237
1238     if (keymgmt != NULL) {
1239         tmp_keymgmt = *keymgmt;
1240         *keymgmt = NULL;
1241     }
1242
1243     /*
1244      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1245      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1246      */
1247     if (tmp_keymgmt == NULL) {
1248         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1249
1250         tmp_keymgmt = ctx->keymgmt;
1251         ctx->keymgmt = NULL;
1252         EVP_PKEY_CTX_free(ctx);
1253     }
1254
1255     /* If there's still no keymgmt to be had, give up */
1256     if (tmp_keymgmt == NULL)
1257         goto end;
1258
1259 #ifndef FIPS_MODE
1260     if (pk->pkey.ptr != NULL) {
1261         size_t i = 0;
1262
1263         /*
1264          * If the legacy "origin" hasn't changed since last time, we try
1265          * to find our keymgmt in the operation cache.  If it has changed,
1266          * |i| remains zero, and we will clear the cache further down.
1267          */
1268         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1269             i = evp_keymgmt_util_find_operation_cache_index(pk, tmp_keymgmt);
1270
1271             /*
1272              * If |tmp_keymgmt| is present in the operation cache, it means
1273              * that export doesn't need to be redone.  In that case, we take
1274              * token copies of the cached pointers, to have token success
1275              * values to return.
1276              */
1277             if (i < OSSL_NELEM(pk->operation_cache)
1278                 && pk->operation_cache[i].keymgmt != NULL) {
1279                 keydata = pk->operation_cache[i].keydata;
1280                 goto end;
1281             }
1282         }
1283
1284         /*
1285          * TODO(3.0) Right now, we assume we have ample space.  We will have
1286          * to think about a cache aging scheme, though, if |i| indexes outside
1287          * the array.
1288          */
1289         if (!ossl_assert(i < OSSL_NELEM(pk->operation_cache)))
1290             goto end;
1291
1292         /* Make sure that the keymgmt key type matches the legacy NID */
1293         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1294             goto end;
1295
1296         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1297             goto end;
1298
1299         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt)) {
1300             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1301             keydata = NULL;
1302             goto end;
1303         }
1304
1305         /*
1306          * If the dirty counter changed since last time, then clear the
1307          * operation cache.  In that case, we know that |i| is zero.  Just
1308          * in case this is a re-export, we increment then decrement the
1309          * keymgmt reference counter.
1310          */
1311         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1312             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1313             keydata = NULL;
1314             goto end;
1315         }
1316         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy)
1317             evp_keymgmt_util_clear_operation_cache(pk);
1318         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1319
1320         /* Add the new export to the operation cache */
1321         if (!evp_keymgmt_util_cache_keydata(pk, i, tmp_keymgmt, keydata)) {
1322             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1323             keydata = NULL;
1324             goto end;
1325         }
1326
1327         /* Synchronize the dirty count */
1328         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1329         goto end;
1330     }
1331 #endif  /* FIPS_MODE */
1332
1333     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1334
1335  end:
1336     /*
1337      * If nothing was exported, |tmp_keymgmt| might point at a freed
1338      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1339      * the caller either way in that case.
1340      */
1341     if (keydata == NULL)
1342         tmp_keymgmt = NULL;
1343
1344     if (keymgmt != NULL)
1345         *keymgmt = tmp_keymgmt;
1346
1347     EVP_KEYMGMT_free(allocated_keymgmt);
1348     return keydata;
1349 }
1350
1351 #ifndef FIPS_MODE
1352 /*
1353  * This differs from exporting in that it releases the legacy key and assigns
1354  * the export keymgmt and keydata to the "origin" provider side key instead
1355  * of the operation cache.
1356  */
1357 void *evp_pkey_upgrade_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
1358                                    EVP_KEYMGMT **keymgmt,
1359                                    const char *propquery)
1360 {
1361     EVP_KEYMGMT *allocated_keymgmt = NULL;
1362     EVP_KEYMGMT *tmp_keymgmt = NULL;
1363     void *keydata = NULL;
1364
1365     if (pk == NULL)
1366         return NULL;
1367
1368     /*
1369      * If this key is already "upgraded", this function shouldn't have been
1370      * called.
1371      */
1372     if (!ossl_assert(pk->keymgmt == NULL))
1373         return NULL;
1374
1375     if (keymgmt != NULL) {
1376         tmp_keymgmt = *keymgmt;
1377         *keymgmt = NULL;
1378     }
1379
1380     /* If the key isn't a legacy one, bail out, but with proper values */
1381     if (pk->pkey.ptr == NULL) {
1382         tmp_keymgmt = pk->keymgmt;
1383         keydata = pk->keydata;
1384     } else {
1385         /* If the legacy key doesn't have an export function, give up */
1386         if (pk->ameth->export_to == NULL)
1387             return NULL;
1388
1389         /*
1390          * If no keymgmt was given or found, get a default keymgmt.  We do
1391          * so by letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we
1392          * steal it.
1393          */
1394         if (tmp_keymgmt == NULL) {
1395             EVP_PKEY_CTX *ctx =
1396                 EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1397
1398             tmp_keymgmt = ctx->keymgmt;
1399             ctx->keymgmt = NULL;
1400             EVP_PKEY_CTX_free(ctx);
1401         }
1402
1403         /* If we still don't have a keymgmt, give up */
1404         if (tmp_keymgmt == NULL)
1405             goto end;
1406
1407         /* Make sure that the keymgmt key type matches the legacy NID */
1408         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1409             goto end;
1410
1411         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1412             goto end;
1413
1414         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt)
1415             || !EVP_KEYMGMT_up_ref(tmp_keymgmt)) {
1416             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1417             keydata = NULL;
1418             goto end;
1419         }
1420
1421         /*
1422          * Clear the operation cache, all the legacy data, as well as the
1423          * dirty counters
1424          */
1425         evp_pkey_free_legacy(pk);
1426         pk->dirty_cnt_copy = 0;
1427
1428         evp_keymgmt_util_clear_operation_cache(pk);
1429         pk->keymgmt = tmp_keymgmt;
1430         pk->keydata = keydata;
1431         evp_keymgmt_util_cache_keyinfo(pk);
1432     }
1433
1434  end:
1435     /*
1436      * If nothing was upgraded, |tmp_keymgmt| might point at a freed
1437      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1438      * the caller either way in that case.
1439      */
1440     if (keydata == NULL)
1441         tmp_keymgmt = NULL;
1442
1443     if (keymgmt != NULL)
1444         *keymgmt = tmp_keymgmt;
1445
1446     EVP_KEYMGMT_free(allocated_keymgmt);
1447     return keydata;
1448 }
1449 #endif  /* FIPS_MODE */