Don't copy parameters on setting a key in libssl
[openssl.git] / crypto / evp / p_lib.c
1 /*
2  * Copyright 1995-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 /*
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 "internal/namemap.h"
20 #include <openssl/bn.h>
21 #include <openssl/err.h>
22 #include <openssl/objects.h>
23 #include <openssl/evp.h>
24 #include <openssl/x509.h>
25 #include <openssl/rsa.h>
26 #include <openssl/dsa.h>
27 #include <openssl/dh.h>
28 #include <openssl/ec.h>
29 #include <openssl/cmac.h>
30 #include <openssl/engine.h>
31 #include <openssl/params.h>
32 #include <openssl/param_build.h>
33 #include <openssl/encoder.h>
34 #include <openssl/core_names.h>
35
36 #include "internal/ffc.h"
37 #include "crypto/asn1.h"
38 #include "crypto/evp.h"
39 #include "crypto/ec.h"
40 #include "crypto/ecx.h"
41 #include "internal/provider.h"
42 #include "evp_local.h"
43
44 #include "crypto/ec.h"
45
46 /* TODO remove this when the EVP_PKEY_is_a() #legacy support hack is removed */
47 #include "e_os.h"                /* strcasecmp on Windows */
48
49 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
50                          int len, EVP_KEYMGMT *keymgmt);
51 static void evp_pkey_free_it(EVP_PKEY *key);
52
53 #ifndef FIPS_MODULE
54
55 /* The type of parameters selected in key parameter functions */
56 # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
57
58 int EVP_PKEY_bits(const EVP_PKEY *pkey)
59 {
60     int size = 0;
61
62     if (pkey != NULL) {
63         size = pkey->cache.bits;
64         if (pkey->ameth != NULL && pkey->ameth->pkey_bits != NULL)
65             size = pkey->ameth->pkey_bits(pkey);
66     }
67     return size < 0 ? 0 : size;
68 }
69
70 int EVP_PKEY_security_bits(const EVP_PKEY *pkey)
71 {
72     int size = 0;
73
74     if (pkey != NULL) {
75         size = pkey->cache.security_bits;
76         if (pkey->ameth != NULL && pkey->ameth->pkey_security_bits != NULL)
77             size = pkey->ameth->pkey_security_bits(pkey);
78     }
79     return size < 0 ? 0 : size;
80 }
81
82 int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
83 {
84 # ifndef OPENSSL_NO_DSA
85     if (pkey->type == EVP_PKEY_DSA) {
86         int ret = pkey->save_parameters;
87
88         if (mode >= 0)
89             pkey->save_parameters = mode;
90         return ret;
91     }
92 # endif
93 # ifndef OPENSSL_NO_EC
94     if (pkey->type == EVP_PKEY_EC) {
95         int ret = pkey->save_parameters;
96
97         if (mode >= 0)
98             pkey->save_parameters = mode;
99         return ret;
100     }
101 # endif
102     return 0;
103 }
104
105 int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg)
106 {
107     return CRYPTO_set_ex_data(&key->ex_data, idx, arg);
108 }
109
110 void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx)
111 {
112     return CRYPTO_get_ex_data(&key->ex_data, idx);
113 }
114
115 int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
116 {
117     /*
118      * TODO: clean up legacy stuff from this function when legacy support
119      * is gone.
120      */
121
122     /*
123      * If |to| is a legacy key and |from| isn't, we must downgrade |from|.
124      * If that fails, this function fails.
125      */
126     if (evp_pkey_is_legacy(to) && evp_pkey_is_provided(from))
127         if (!evp_pkey_downgrade((EVP_PKEY *)from))
128             return 0;
129
130     /*
131      * Make sure |to| is typed.  Content is less important at this early
132      * stage.
133      *
134      * 1.  If |to| is untyped, assign |from|'s key type to it.
135      * 2.  If |to| contains a legacy key, compare its |type| to |from|'s.
136      *     (|from| was already downgraded above)
137      *
138      * If |to| is a provided key, there's nothing more to do here, functions
139      * like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called
140      * further down help us find out if they are the same or not.
141      */
142     if (evp_pkey_is_blank(to)) {
143         if (evp_pkey_is_legacy(from)) {
144             if (EVP_PKEY_set_type(to, from->type) == 0)
145                 return 0;
146         } else {
147             if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0)
148                 return 0;
149         }
150     } else if (evp_pkey_is_legacy(to)) {
151         if (to->type != from->type) {
152             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
153             goto err;
154         }
155     }
156
157     if (EVP_PKEY_missing_parameters(from)) {
158         ERR_raise(ERR_LIB_EVP, EVP_R_MISSING_PARAMETERS);
159         goto err;
160     }
161
162     if (!EVP_PKEY_missing_parameters(to)) {
163         if (EVP_PKEY_parameters_eq(to, from) == 1)
164             return 1;
165         ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS);
166         return 0;
167     }
168
169     /* For purely provided keys, we just call the keymgmt utility */
170     if (to->keymgmt != NULL && from->keymgmt != NULL)
171         return evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS);
172
173     /*
174      * If |to| is provided, we know that |from| is legacy at this point.
175      * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_copy()
176      * to copy the appropriate data to |to|'s keydata.
177      */
178     if (to->keymgmt != NULL) {
179         EVP_KEYMGMT *to_keymgmt = to->keymgmt;
180         void *from_keydata =
181             evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt,
182                                         NULL);
183
184         /*
185          * If we get a NULL, it could be an internal error, or it could be
186          * that there's a key mismatch.  We're pretending the latter...
187          */
188         if (from_keydata == NULL) {
189             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
190             return 0;
191         }
192         return evp_keymgmt_copy(to->keymgmt, to->keydata, from_keydata,
193                                 SELECT_PARAMETERS);
194     }
195
196     /* Both keys are legacy */
197     if (from->ameth != NULL && from->ameth->param_copy != NULL)
198         return from->ameth->param_copy(to, from);
199  err:
200     return 0;
201 }
202
203 int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
204 {
205     if (pkey != NULL) {
206         if (pkey->keymgmt != NULL)
207             return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS);
208         else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL)
209             return pkey->ameth->param_missing(pkey);
210     }
211     return 0;
212 }
213
214 /*
215  * This function is called for any mixture of keys except pure legacy pair.
216  * TODO When legacy keys are gone, we replace a call to this functions with
217  * a call to evp_keymgmt_util_match().
218  */
219 static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b,
220                             int selection)
221 {
222     EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
223     void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL;
224
225     /* If none of them are provided, this function shouldn't have been called */
226     if (!ossl_assert(evp_pkey_is_provided(a) || evp_pkey_is_provided(b)))
227         return -2;
228
229     /* For purely provided keys, we just call the keymgmt utility */
230     if (evp_pkey_is_provided(a) && evp_pkey_is_provided(b))
231         return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection);
232
233     /*
234      * At this point, one of them is provided, the other not.  This allows
235      * us to compare types using legacy NIDs.
236      */
237     if (evp_pkey_is_legacy(a)
238         && !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type)))
239         return -1;               /* not the same key type */
240     if (evp_pkey_is_legacy(b)
241         && !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type)))
242         return -1;               /* not the same key type */
243
244     /*
245      * We've determined that they both are the same keytype, so the next
246      * step is to do a bit of cross export to ensure we have keydata for
247      * both keys in the same keymgmt.
248      */
249     keymgmt1 = a->keymgmt;
250     keydata1 = a->keydata;
251     keymgmt2 = b->keymgmt;
252     keydata2 = b->keydata;
253
254     if (keymgmt2 != NULL && keymgmt2->match != NULL) {
255         tmp_keydata =
256             evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL);
257         if (tmp_keydata != NULL) {
258             keymgmt1 = keymgmt2;
259             keydata1 = tmp_keydata;
260         }
261     }
262     if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) {
263         tmp_keydata =
264             evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL);
265         if (tmp_keydata != NULL) {
266             keymgmt2 = keymgmt1;
267             keydata2 = tmp_keydata;
268         }
269     }
270
271     /* If we still don't have matching keymgmt implementations, we give up */
272     if (keymgmt1 != keymgmt2)
273         return -2;
274
275     /* If the keymgmt implementations are NULL, the export failed */
276     if (keymgmt1 == NULL)
277         return -2;
278
279     return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
280 }
281
282 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
283 {
284     return EVP_PKEY_parameters_eq(a, b);
285 }
286
287 int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b)
288 {
289     /*
290      * TODO: clean up legacy stuff from this function when legacy support
291      * is gone.
292      */
293
294     if (a->keymgmt != NULL || b->keymgmt != NULL)
295         return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS);
296
297     /* All legacy keys */
298     if (a->type != b->type)
299         return -1;
300     if (a->ameth != NULL && a->ameth->param_cmp != NULL)
301         return a->ameth->param_cmp(a, b);
302     return -2;
303 }
304
305 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
306 {
307     return EVP_PKEY_eq(a, b);
308 }
309
310 int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b)
311 {
312     /*
313      * TODO: clean up legacy stuff from this function when legacy support
314      * is gone.
315      */
316
317     if (a->keymgmt != NULL || b->keymgmt != NULL)
318         return evp_pkey_cmp_any(a, b, (SELECT_PARAMETERS
319                                        | OSSL_KEYMGMT_SELECT_PUBLIC_KEY));
320
321     /* All legacy keys */
322     if (a->type != b->type)
323         return -1;
324
325     if (a->ameth != NULL) {
326         int ret;
327         /* Compare parameters if the algorithm has them */
328         if (a->ameth->param_cmp != NULL) {
329             ret = a->ameth->param_cmp(a, b);
330             if (ret <= 0)
331                 return ret;
332         }
333
334         if (a->ameth->pub_cmp != NULL)
335             return a->ameth->pub_cmp(a, b);
336     }
337
338     return -2;
339 }
340
341
342 static EVP_PKEY *new_raw_key_int(OSSL_LIB_CTX *libctx,
343                                  const char *strtype,
344                                  const char *propq,
345                                  int nidtype,
346                                  ENGINE *e,
347                                  const unsigned char *key,
348                                  size_t len,
349                                  int key_is_priv)
350 {
351     EVP_PKEY *pkey = NULL;
352     EVP_PKEY_CTX *ctx = NULL;
353     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
354     int result = 0;
355
356 # ifndef OPENSSL_NO_ENGINE
357     /* Check if there is an Engine for this type */
358     if (e == NULL) {
359         ENGINE *tmpe = NULL;
360
361         if (strtype != NULL)
362             ameth = EVP_PKEY_asn1_find_str(&tmpe, strtype, -1);
363         else if (nidtype != EVP_PKEY_NONE)
364             ameth = EVP_PKEY_asn1_find(&tmpe, nidtype);
365
366         /* If tmpe is NULL then no engine is claiming to support this type */
367         if (tmpe == NULL)
368             ameth = NULL;
369
370         ENGINE_finish(tmpe);
371     }
372 # endif
373
374     if (e == NULL && ameth == NULL) {
375         /*
376          * No engine is claiming to support this type, so lets see if we have
377          * a provider.
378          */
379         ctx = EVP_PKEY_CTX_new_from_name(libctx,
380                                          strtype != NULL ? strtype
381                                                          : OBJ_nid2sn(nidtype),
382                                          propq);
383         if (ctx == NULL)
384             goto err;
385         /* May fail if no provider available */
386         ERR_set_mark();
387         if (EVP_PKEY_key_fromdata_init(ctx) == 1) {
388             OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
389
390             ERR_clear_last_mark();
391             params[0] = OSSL_PARAM_construct_octet_string(
392                             key_is_priv ? OSSL_PKEY_PARAM_PRIV_KEY
393                                         : OSSL_PKEY_PARAM_PUB_KEY,
394                             (void *)key, len);
395
396             if (EVP_PKEY_fromdata(ctx, &pkey, params) != 1) {
397                 ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
398                 goto err;
399             }
400
401             EVP_PKEY_CTX_free(ctx);
402
403             return pkey;
404         }
405         ERR_pop_to_mark();
406         /* else not supported so fallback to legacy */
407     }
408
409     /* Legacy code path */
410
411     pkey = EVP_PKEY_new();
412     if (pkey == NULL) {
413         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
414         goto err;
415     }
416
417     if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) {
418         /* EVPerr already called */
419         goto err;
420     }
421
422     if (!ossl_assert(pkey->ameth != NULL))
423         goto err;
424
425     if (key_is_priv) {
426         if (pkey->ameth->set_priv_key == NULL) {
427             ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
428             goto err;
429         }
430
431         if (!pkey->ameth->set_priv_key(pkey, key, len)) {
432             ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
433             goto err;
434         }
435     } else {
436         if (pkey->ameth->set_pub_key == NULL) {
437             ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
438             goto err;
439         }
440
441         if (!pkey->ameth->set_pub_key(pkey, key, len)) {
442             ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
443             goto err;
444         }
445     }
446
447     result = 1;
448  err:
449     if (!result) {
450         EVP_PKEY_free(pkey);
451         pkey = NULL;
452     }
453     EVP_PKEY_CTX_free(ctx);
454     return pkey;
455 }
456
457 EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx,
458                                           const char *keytype,
459                                           const char *propq,
460                                           const unsigned char *priv, size_t len)
461 {
462     return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, priv,
463                            len, 1);
464 }
465
466 EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
467                                        const unsigned char *priv,
468                                        size_t len)
469 {
470     return new_raw_key_int(NULL, NULL, NULL, type, e, priv, len, 1);
471 }
472
473 EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx,
474                                          const char *keytype, const char *propq,
475                                          const unsigned char *pub, size_t len)
476 {
477     return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, pub,
478                            len, 0);
479 }
480
481 EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
482                                       const unsigned char *pub,
483                                       size_t len)
484 {
485     return new_raw_key_int(NULL, NULL, NULL, type, e, pub, len, 0);
486 }
487
488 struct raw_key_details_st
489 {
490     unsigned char **key;
491     size_t *len;
492     int selection;
493 };
494
495 static OSSL_CALLBACK get_raw_key_details;
496 static int get_raw_key_details(const OSSL_PARAM params[], void *arg)
497 {
498     const OSSL_PARAM *p = NULL;
499     struct raw_key_details_st *raw_key = arg;
500
501     if (raw_key->selection == OSSL_KEYMGMT_SELECT_PRIVATE_KEY) {
502         if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY))
503                 != NULL)
504             return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
505                                                SIZE_MAX, raw_key->len);
506     } else if (raw_key->selection == OSSL_KEYMGMT_SELECT_PUBLIC_KEY) {
507         if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY))
508                 != NULL)
509             return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
510                                                SIZE_MAX, raw_key->len);
511     }
512
513     return 0;
514 }
515
516 int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
517                                  size_t *len)
518 {
519     if (pkey->keymgmt != NULL) {
520         struct raw_key_details_st raw_key;
521
522         raw_key.key = priv == NULL ? NULL : &priv;
523         raw_key.len = len;
524         raw_key.selection = OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
525
526         return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
527                                        get_raw_key_details, &raw_key);
528     }
529
530     if (pkey->ameth == NULL) {
531         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
532         return 0;
533     }
534
535     if (pkey->ameth->get_priv_key == NULL) {
536         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
537         return 0;
538     }
539
540     if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
541         ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
542         return 0;
543     }
544
545     return 1;
546 }
547
548 int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
549                                 size_t *len)
550 {
551     if (pkey->keymgmt != NULL) {
552         struct raw_key_details_st raw_key;
553
554         raw_key.key = pub == NULL ? NULL : &pub;
555         raw_key.len = len;
556         raw_key.selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
557
558         return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PUBLIC_KEY,
559                                        get_raw_key_details, &raw_key);
560     }
561
562     if (pkey->ameth == NULL) {
563         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
564         return 0;
565     }
566
567      if (pkey->ameth->get_pub_key == NULL) {
568         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
569         return 0;
570     }
571
572     if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
573         ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
574         return 0;
575     }
576
577     return 1;
578 }
579
580 static EVP_PKEY *new_cmac_key_int(const unsigned char *priv, size_t len,
581                                   const char *cipher_name,
582                                   const EVP_CIPHER *cipher,
583                                   OSSL_LIB_CTX *libctx,
584                                   const char *propq, ENGINE *e)
585 {
586 # ifndef OPENSSL_NO_CMAC
587 #  ifndef OPENSSL_NO_ENGINE
588     const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
589 #  endif
590     OSSL_PARAM params[5], *p = params;
591     EVP_PKEY *pkey = NULL;
592     EVP_PKEY_CTX *ctx;
593
594     if (cipher != NULL)
595         cipher_name = EVP_CIPHER_name(cipher);
596
597     if (cipher_name == NULL) {
598         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
599         return NULL;
600     }
601
602     ctx = EVP_PKEY_CTX_new_from_name(libctx, "CMAC", propq);
603     if (ctx == NULL)
604         goto err;
605
606     if (!EVP_PKEY_key_fromdata_init(ctx)) {
607         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
608         goto err;
609     }
610
611     *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
612                                             (void *)priv, len);
613     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_CIPHER,
614                                             (char *)cipher_name, 0);
615     if (propq != NULL)
616         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_PROPERTIES,
617                                                 (char *)propq, 0);
618 #  ifndef OPENSSL_NO_ENGINE
619     if (engine_id != NULL)
620         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_ENGINE,
621                                                 (char *)engine_id, 0);
622 #  endif
623     *p = OSSL_PARAM_construct_end();
624
625     if (!EVP_PKEY_fromdata(ctx, &pkey, params)) {
626         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
627         goto err;
628     }
629
630  err:
631     EVP_PKEY_CTX_free(ctx);
632
633     return pkey;
634 # else
635     ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
636     return NULL;
637 # endif
638 }
639
640 EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
641                                 size_t len, const EVP_CIPHER *cipher)
642 {
643     return new_cmac_key_int(priv, len, NULL, cipher, NULL, NULL, e);
644 }
645
646 int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
647 {
648     return pkey_set_type(pkey, NULL, type, NULL, -1, NULL);
649 }
650
651 int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
652 {
653     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL);
654 }
655
656 #ifndef OPENSSL_NO_DEPRECATED_3_0
657 int EVP_PKEY_set_alias_type(EVP_PKEY *pkey, int type)
658 {
659     if (!evp_pkey_is_legacy(pkey)) {
660         const char *name = OBJ_nid2sn(type);
661
662         if (name != NULL && EVP_PKEY_is_a(pkey, name))
663             return 1;
664
665         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
666         return 0;
667     }
668
669     if (pkey->type == type) {
670         return 1; /* it already is that type */
671     }
672
673     /*
674      * The application is requesting to alias this to a different pkey type,
675      * but not one that resolves to the base type.
676      */
677     if (EVP_PKEY_type(type) != EVP_PKEY_base_id(pkey)) {
678         ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
679         return 0;
680     }
681
682     pkey->type = type;
683     return 1;
684 }
685 #endif
686
687 # ifndef OPENSSL_NO_ENGINE
688 int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
689 {
690     if (e != NULL) {
691         if (!ENGINE_init(e)) {
692             ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
693             return 0;
694         }
695         if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
696             ENGINE_finish(e);
697             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
698             return 0;
699         }
700     }
701     ENGINE_finish(pkey->pmeth_engine);
702     pkey->pmeth_engine = e;
703     return 1;
704 }
705
706 ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
707 {
708     return pkey->engine;
709 }
710 # endif
711 int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
712 {
713     int alias = type;
714
715 #ifndef OPENSSL_NO_EC
716     if ((key != NULL) && (EVP_PKEY_type(type) == EVP_PKEY_EC)) {
717         const EC_GROUP *group = EC_KEY_get0_group(key);
718
719         if (group != NULL && EC_GROUP_get_curve_name(group) == NID_sm2)
720             alias = EVP_PKEY_SM2;
721     }
722 #endif
723
724     if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
725         return 0;
726     if (!EVP_PKEY_set_alias_type(pkey, alias))
727         return 0;
728     pkey->pkey.ptr = key;
729     return (key != NULL);
730 }
731
732 void *EVP_PKEY_get0(const EVP_PKEY *pkey)
733 {
734     if (pkey == NULL)
735         return NULL;
736     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
737         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
738         return NULL;
739     }
740     return pkey->pkey.ptr;
741 }
742
743 const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
744 {
745     ASN1_OCTET_STRING *os = NULL;
746     if (pkey->type != EVP_PKEY_HMAC) {
747         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_HMAC_KEY);
748         return NULL;
749     }
750     os = EVP_PKEY_get0(pkey);
751     *len = os->length;
752     return os->data;
753 }
754
755 # ifndef OPENSSL_NO_POLY1305
756 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
757 {
758     ASN1_OCTET_STRING *os = NULL;
759     if (pkey->type != EVP_PKEY_POLY1305) {
760         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_POLY1305_KEY);
761         return NULL;
762     }
763     os = EVP_PKEY_get0(pkey);
764     *len = os->length;
765     return os->data;
766 }
767 # endif
768
769 # ifndef OPENSSL_NO_SIPHASH
770 const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
771 {
772     ASN1_OCTET_STRING *os = NULL;
773
774     if (pkey->type != EVP_PKEY_SIPHASH) {
775         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_SIPHASH_KEY);
776         return NULL;
777     }
778     os = EVP_PKEY_get0(pkey);
779     *len = os->length;
780     return os->data;
781 }
782 # endif
783
784 # ifndef OPENSSL_NO_DSA
785 DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
786 {
787     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
788         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
789         return NULL;
790     }
791     if (pkey->type != EVP_PKEY_DSA) {
792         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DSA_KEY);
793         return NULL;
794     }
795     return pkey->pkey.dsa;
796 }
797
798 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
799 {
800     int ret = EVP_PKEY_assign_DSA(pkey, key);
801     if (ret)
802         DSA_up_ref(key);
803     return ret;
804 }
805 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
806 {
807     DSA *ret = EVP_PKEY_get0_DSA(pkey);
808     if (ret != NULL)
809         DSA_up_ref(ret);
810     return ret;
811 }
812 # endif /*  OPENSSL_NO_DSA */
813 #endif /* FIPS_MODULE */
814
815 #ifndef FIPS_MODULE
816 # ifndef OPENSSL_NO_EC
817 int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key)
818 {
819     int ret = EVP_PKEY_assign_EC_KEY(pkey, key);
820     if (ret)
821         EC_KEY_up_ref(key);
822     return ret;
823 }
824
825 EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey)
826 {
827     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
828         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
829         return NULL;
830     }
831     if (EVP_PKEY_base_id(pkey) != EVP_PKEY_EC) {
832         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_EC_KEY);
833         return NULL;
834     }
835     return pkey->pkey.ec;
836 }
837
838 EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey)
839 {
840     EC_KEY *ret = EVP_PKEY_get0_EC_KEY(pkey);
841     if (ret != NULL)
842         EC_KEY_up_ref(ret);
843     return ret;
844 }
845
846 static ECX_KEY *evp_pkey_get0_ECX_KEY(const EVP_PKEY *pkey, int type)
847 {
848     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
849         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
850         return NULL;
851     }
852     if (EVP_PKEY_base_id(pkey) != type) {
853         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_ECX_KEY);
854         return NULL;
855     }
856     return pkey->pkey.ecx;
857 }
858
859 static ECX_KEY *evp_pkey_get1_ECX_KEY(EVP_PKEY *pkey, int type)
860 {
861     ECX_KEY *ret = evp_pkey_get0_ECX_KEY(pkey, type);
862     if (ret != NULL)
863         ecx_key_up_ref(ret);
864     return ret;
865 }
866
867 #  define IMPLEMENT_ECX_VARIANT(NAME)                                   \
868     ECX_KEY *evp_pkey_get1_##NAME(EVP_PKEY *pkey)                       \
869     {                                                                   \
870         return evp_pkey_get1_ECX_KEY(pkey, EVP_PKEY_##NAME);            \
871     }
872 IMPLEMENT_ECX_VARIANT(X25519)
873 IMPLEMENT_ECX_VARIANT(X448)
874 IMPLEMENT_ECX_VARIANT(ED25519)
875 IMPLEMENT_ECX_VARIANT(ED448)
876
877 # endif
878
879 # if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0)
880
881 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key)
882 {
883     int type = DH_get0_q(key) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
884     int ret = EVP_PKEY_assign(pkey, type, key);
885
886     if (ret)
887         DH_up_ref(key);
888     return ret;
889 }
890
891 DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
892 {
893     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
894         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
895         return NULL;
896     }
897     if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
898         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DH_KEY);
899         return NULL;
900     }
901     return pkey->pkey.dh;
902 }
903
904 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
905 {
906     DH *ret = EVP_PKEY_get0_DH(pkey);
907     if (ret != NULL)
908         DH_up_ref(ret);
909     return ret;
910 }
911 # endif
912
913 int EVP_PKEY_type(int type)
914 {
915     int ret;
916     const EVP_PKEY_ASN1_METHOD *ameth;
917     ENGINE *e;
918     ameth = EVP_PKEY_asn1_find(&e, type);
919     if (ameth)
920         ret = ameth->pkey_id;
921     else
922         ret = NID_undef;
923 # ifndef OPENSSL_NO_ENGINE
924     ENGINE_finish(e);
925 # endif
926     return ret;
927 }
928
929 int EVP_PKEY_id(const EVP_PKEY *pkey)
930 {
931     return pkey->type;
932 }
933
934 int EVP_PKEY_base_id(const EVP_PKEY *pkey)
935 {
936     return EVP_PKEY_type(pkey->type);
937 }
938
939 #ifndef FIPS_MODULE
940 int evp_pkey_name2type(const char *name)
941 {
942     /*
943      * These hard coded cases are pure hackery to get around the fact
944      * that names in crypto/objects/objects.txt are a mess.  There is
945      * no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's
946      * fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1,
947      * the NID of which is used for EVP_PKEY_RSA.  Strangely enough,
948      * "DSA" is accurate...  but still, better be safe and hard-code
949      * names that we know.
950      * On a similar topic, EVP_PKEY_type(EVP_PKEY_SM2) will result in
951      * EVP_PKEY_EC, because of aliasing.
952      * TODO Clean this away along with all other #legacy support.
953      */
954     int type = NID_undef;
955
956     if (strcasecmp(name, "RSA") == 0)
957         type = EVP_PKEY_RSA;
958     else if (strcasecmp(name, "RSA-PSS") == 0)
959         type = EVP_PKEY_RSA_PSS;
960     else if (strcasecmp(name, "EC") == 0)
961         type = EVP_PKEY_EC;
962     else if (strcasecmp(name, "ED25519") == 0)
963         type = EVP_PKEY_ED25519;
964     else if (strcasecmp(name, "ED448") == 0)
965         type = EVP_PKEY_ED448;
966     else if (strcasecmp(name, "X25519") == 0)
967         type = EVP_PKEY_X25519;
968     else if (strcasecmp(name, "X448") == 0)
969         type = EVP_PKEY_X448;
970     else if (strcasecmp(name, "SM2") == 0)
971         type = EVP_PKEY_SM2;
972     else if (strcasecmp(name, "DH") == 0)
973         type = EVP_PKEY_DH;
974     else if (strcasecmp(name, "X9.42 DH") == 0)
975         type = EVP_PKEY_DHX;
976     else if (strcasecmp(name, "DHX") == 0)
977         type = EVP_PKEY_DHX;
978     else if (strcasecmp(name, "DSA") == 0)
979         type = EVP_PKEY_DSA;
980
981     if (type == NID_undef)
982         type = EVP_PKEY_type(OBJ_sn2nid(name));
983     if (type == NID_undef)
984         type = EVP_PKEY_type(OBJ_ln2nid(name));
985
986     return type;
987 }
988 #endif
989
990 int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name)
991 {
992 #ifndef FIPS_MODULE
993     if (pkey->keymgmt == NULL) {
994         int type = evp_pkey_name2type(name);
995
996         return pkey->type == type;
997     }
998 #endif
999     return EVP_KEYMGMT_is_a(pkey->keymgmt, name);
1000 }
1001
1002 void EVP_PKEY_typenames_do_all(const EVP_PKEY *pkey,
1003                                void (*fn)(const char *name, void *data),
1004                                void *data)
1005 {
1006     if (!evp_pkey_is_typed(pkey))
1007         return;
1008
1009     if (!evp_pkey_is_provided(pkey)) {
1010         const char *name = OBJ_nid2sn(EVP_PKEY_id(pkey));
1011
1012         fn(name, data);
1013         return;
1014     }
1015     EVP_KEYMGMT_names_do_all(pkey->keymgmt, fn, data);
1016 }
1017
1018 int EVP_PKEY_can_sign(const EVP_PKEY *pkey)
1019 {
1020     if (pkey->keymgmt == NULL) {
1021         switch (EVP_PKEY_base_id(pkey)) {
1022         case EVP_PKEY_RSA:
1023             return 1;
1024 #ifndef OPENSSL_NO_DSA
1025         case EVP_PKEY_DSA:
1026             return 1;
1027 #endif
1028 #ifndef OPENSSL_NO_EC
1029         case EVP_PKEY_ED25519:
1030         case EVP_PKEY_ED448:
1031             return 1;
1032         case EVP_PKEY_EC:        /* Including SM2 */
1033             return EC_KEY_can_sign(pkey->pkey.ec);
1034 #endif
1035         default:
1036             break;
1037         }
1038     } else {
1039         const OSSL_PROVIDER *prov = EVP_KEYMGMT_provider(pkey->keymgmt);
1040         OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov);
1041         const char *supported_sig =
1042             pkey->keymgmt->query_operation_name != NULL
1043             ? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE)
1044             : evp_first_name(prov, pkey->keymgmt->name_id);
1045         EVP_SIGNATURE *signature = NULL;
1046
1047         signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL);
1048         if (signature != NULL) {
1049             EVP_SIGNATURE_free(signature);
1050             return 1;
1051         }
1052     }
1053     return 0;
1054 }
1055
1056 static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
1057 {
1058     BIO_set_indent(*out, saved_indent);
1059     if (pop_f_prefix) {
1060         BIO *next = BIO_pop(*out);
1061
1062         BIO_free(*out);
1063         *out = next;
1064     }
1065     return 1;
1066 }
1067
1068 static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
1069                             long indent)
1070 {
1071     *pop_f_prefix = 0;
1072     *saved_indent = 0;
1073     if (indent > 0) {
1074         long i = BIO_get_indent(*out);
1075
1076         *saved_indent =  (i < 0 ? 0 : i);
1077         if (BIO_set_indent(*out, indent) <= 0) {
1078             if ((*out = BIO_push(BIO_new(BIO_f_prefix()), *out)) == NULL)
1079                 return 0;
1080             *pop_f_prefix = 1;
1081         }
1082         if (BIO_set_indent(*out, indent) <= 0) {
1083             print_reset_indent(out, *pop_f_prefix, *saved_indent);
1084             return 0;
1085         }
1086     }
1087     return 1;
1088 }
1089
1090 static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
1091                      const char *kstr)
1092 {
1093     return BIO_indent(out, indent, 128)
1094         && BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
1095                       kstr, OBJ_nid2ln(pkey->type)) > 0;
1096 }
1097
1098 static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
1099                       int selection /* For provided encoding */,
1100                       const char *propquery /* For provided encoding */,
1101                       int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
1102                                           int indent, ASN1_PCTX *pctx),
1103                       ASN1_PCTX *legacy_pctx /* For legacy print */)
1104 {
1105     int pop_f_prefix;
1106     long saved_indent;
1107     OSSL_ENCODER_CTX *ctx = NULL;
1108     int ret = -2;                /* default to unsupported */
1109
1110     if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
1111         return 0;
1112
1113     ctx = OSSL_ENCODER_CTX_new_by_EVP_PKEY(pkey, selection, "TEXT", NULL,
1114                                            propquery);
1115     if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0)
1116         ret = OSSL_ENCODER_to_bio(ctx, out);
1117     OSSL_ENCODER_CTX_free(ctx);
1118
1119     if (ret != -2)
1120         goto end;
1121
1122     /* legacy fallback */
1123     if (legacy_print != NULL)
1124         ret = legacy_print(out, pkey, 0, legacy_pctx);
1125     else
1126         ret = unsup_alg(out, pkey, 0, "Public Key");
1127
1128  end:
1129     print_reset_indent(&out, pop_f_prefix, saved_indent);
1130     return ret;
1131 }
1132
1133 int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
1134                           int indent, ASN1_PCTX *pctx)
1135 {
1136     return print_pkey(pkey, out, indent, EVP_PKEY_PUBLIC_KEY, NULL,
1137                       (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
1138                       pctx);
1139 }
1140
1141 int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
1142                            int indent, ASN1_PCTX *pctx)
1143 {
1144     return print_pkey(pkey, out, indent, EVP_PKEY_KEYPAIR, NULL,
1145                       (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL),
1146                       pctx);
1147 }
1148
1149 int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
1150                           int indent, ASN1_PCTX *pctx)
1151 {
1152     return print_pkey(pkey, out, indent, EVP_PKEY_KEY_PARAMETERS, NULL,
1153                       (pkey->ameth != NULL ? pkey->ameth->param_print : NULL),
1154                       pctx);
1155 }
1156
1157 static void mdname2nid(const char *mdname, void *data)
1158 {
1159     int *nid = (int *)data;
1160
1161     if (*nid != NID_undef)
1162         return;
1163
1164     *nid = OBJ_sn2nid(mdname);
1165     if (*nid == NID_undef)
1166         *nid = OBJ_ln2nid(mdname);
1167 }
1168
1169 static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op,
1170                                      int arg1, void *arg2)
1171 {
1172     if (pkey->keymgmt == NULL)
1173         return 0;
1174     switch (op) {
1175     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
1176         {
1177             char mdname[80] = "";
1178             int rv = EVP_PKEY_get_default_digest_name(pkey, mdname,
1179                                                       sizeof(mdname));
1180
1181             if (rv > 0) {
1182                 int mdnum;
1183                 OSSL_LIB_CTX *libctx = ossl_provider_libctx(pkey->keymgmt->prov);
1184                 /* Make sure the MD is in the namemap if available */
1185                 EVP_MD *md = EVP_MD_fetch(libctx, mdname, NULL);
1186                 OSSL_NAMEMAP *namemap = ossl_namemap_stored(libctx);
1187                 int nid = NID_undef;
1188
1189                 /*
1190                  * The only reason to fetch the MD was to make sure it is in the
1191                  * namemap. We can immediately free it.
1192                  */
1193                 EVP_MD_free(md);
1194                 mdnum = ossl_namemap_name2num(namemap, mdname);
1195                 if (mdnum == 0)
1196                     return 0;
1197
1198                 /*
1199                  * We have the namemap number - now we need to find the
1200                  * associated nid
1201                  */
1202                 ossl_namemap_doall_names(namemap, mdnum, mdname2nid, &nid);
1203                 *(int *)arg2 = nid;
1204             }
1205             return rv;
1206         }
1207     default:
1208         return -2;
1209     }
1210 }
1211
1212 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
1213 {
1214     if (pkey->ameth == NULL)
1215         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
1216     if (pkey->ameth->pkey_ctrl == NULL)
1217         return -2;
1218     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
1219 }
1220
1221 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
1222 {
1223     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
1224 }
1225
1226 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
1227                                      char *mdname, size_t mdname_sz)
1228 {
1229     if (pkey->ameth == NULL)
1230         return evp_keymgmt_util_get_deflt_digest_name(pkey->keymgmt,
1231                                                       pkey->keydata,
1232                                                       mdname, mdname_sz);
1233
1234     {
1235         int nid = NID_undef;
1236         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
1237         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
1238
1239         if (rv > 0)
1240             OPENSSL_strlcpy(mdname, name, mdname_sz);
1241         return rv;
1242     }
1243 }
1244
1245 int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *gname, size_t gname_sz,
1246                             size_t *gname_len)
1247 {
1248     if (evp_pkey_is_legacy(pkey)) {
1249         const char *name = NULL;
1250
1251         switch (EVP_PKEY_base_id(pkey)) {
1252 #ifndef OPENSSL_NO_EC
1253         case EVP_PKEY_EC:
1254             {
1255                 EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
1256                 int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1257
1258                 if (nid != NID_undef)
1259                     name = ec_curve_nid2name(nid);
1260             }
1261             break;
1262 #endif
1263 #ifndef OPENSSL_NO_DH
1264         case EVP_PKEY_DH:
1265             {
1266                 DH *dh = EVP_PKEY_get0_DH(pkey);
1267                 int uid = DH_get_nid(dh);
1268
1269                 if (uid != NID_undef) {
1270                     const DH_NAMED_GROUP *dh_group =
1271                         ossl_ffc_uid_to_dh_named_group(uid);
1272
1273                     name = ossl_ffc_named_group_get_name(dh_group);
1274                 }
1275             }
1276             break;
1277 #endif
1278         default:
1279             break;
1280         }
1281
1282         if (gname_len != NULL)
1283             *gname_len = (name == NULL ? 0 : strlen(name));
1284         if (name != NULL) {
1285             if (gname != NULL)
1286                 OPENSSL_strlcpy(gname, name, gname_sz);
1287             return 1;
1288         }
1289     } else if (evp_pkey_is_provided(pkey)) {
1290         if (EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME,
1291                                            gname, gname_sz, gname_len))
1292             return 1;
1293     } else {
1294         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
1295         return 0;
1296     }
1297
1298     ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
1299     return 0;
1300 }
1301
1302 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
1303 {
1304     int rv, default_nid;
1305
1306     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
1307     if (rv == -2) {
1308         /*
1309          * If there is a mandatory default digest and this isn't it, then
1310          * the answer is 'no'.
1311          */
1312         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
1313         if (rv == 2)
1314             return (nid == default_nid);
1315         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
1316         if (rv == 0)
1317             return -1;
1318     }
1319     return rv;
1320 }
1321
1322 int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub,
1323                                      size_t publen)
1324 {
1325     if (pkey->ameth == NULL) {
1326         OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1327
1328         if (pkey->keymgmt == NULL || pkey->keydata == NULL)
1329             return 0;
1330
1331         params[0] =
1332             OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1333                                               (unsigned char *)pub, publen);
1334         return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params);
1335     }
1336
1337     if (publen > INT_MAX)
1338         return 0;
1339     /* Historically this function was EVP_PKEY_set1_tls_encodedpoint */
1340     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen,
1341                            (void *)pub) <= 0)
1342         return 0;
1343     return 1;
1344 }
1345
1346 size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub)
1347 {
1348     int rv;
1349
1350     if (pkey->ameth == NULL) {
1351         OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1352
1353         if (pkey->keymgmt == NULL || pkey->keydata == NULL)
1354             return 0;
1355
1356         params[0] =
1357             OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1358                                               NULL, 0);
1359         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1360             return 0;
1361
1362         *ppub = OPENSSL_malloc(params[0].return_size);
1363         if (*ppub == NULL)
1364             return 0;
1365
1366         params[0] =
1367             OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1368                                               *ppub, params[0].return_size);
1369         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1370             return 0;
1371
1372         return params[0].return_size;
1373     }
1374
1375
1376     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub);
1377     if (rv <= 0)
1378         return 0;
1379     return rv;
1380 }
1381
1382 #endif /* FIPS_MODULE */
1383
1384 /*- All methods below can also be used in FIPS_MODULE */
1385
1386 /*
1387  * This reset function must be used very carefully, as it literally throws
1388  * away everything in an EVP_PKEY without freeing them, and may cause leaks
1389  * of memory, what have you.
1390  * The only reason we have this is to have the same code for EVP_PKEY_new()
1391  * and evp_pkey_downgrade().
1392  */
1393 static int evp_pkey_reset_unlocked(EVP_PKEY *pk)
1394 {
1395     if (pk == NULL)
1396         return 0;
1397
1398     if (pk->lock != NULL) {
1399       const size_t offset = (unsigned char *)&pk->lock - (unsigned char *)pk;
1400
1401       memset(pk, 0, offset);
1402       memset((unsigned char *)pk + offset + sizeof(pk->lock),
1403              0,
1404              sizeof(*pk) - offset - sizeof(pk->lock));
1405     }
1406     /* EVP_PKEY_new uses zalloc so no need to call memset if pk->lock is NULL */
1407
1408     pk->type = EVP_PKEY_NONE;
1409     pk->save_type = EVP_PKEY_NONE;
1410     pk->references = 1;
1411     pk->save_parameters = 1;
1412
1413     return 1;
1414 }
1415
1416 EVP_PKEY *EVP_PKEY_new(void)
1417 {
1418     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
1419
1420     if (ret == NULL) {
1421         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1422         return NULL;
1423     }
1424
1425     if (!evp_pkey_reset_unlocked(ret))
1426         goto err;
1427
1428     ret->lock = CRYPTO_THREAD_lock_new();
1429     if (ret->lock == NULL) {
1430         EVPerr(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1431         goto err;
1432     }
1433
1434 #ifndef FIPS_MODULE
1435     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) {
1436         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1437         goto err;
1438     }
1439 #endif
1440     return ret;
1441
1442  err:
1443     CRYPTO_THREAD_lock_free(ret->lock);
1444     OPENSSL_free(ret);
1445     return NULL;
1446 }
1447
1448 /*
1449  * Setup a public key management method.
1450  *
1451  * For legacy keys, either |type| or |str| is expected to have the type
1452  * information.  In this case, the setup consists of finding an ASN1 method
1453  * and potentially an ENGINE, and setting those fields in |pkey|.
1454  *
1455  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
1456  * case, the setup consists of setting the |keymgmt| field in |pkey|.
1457  *
1458  * If pkey is NULL just return 1 or 0 if the key management method exists.
1459  */
1460
1461 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
1462                          int len, EVP_KEYMGMT *keymgmt)
1463 {
1464 #ifndef FIPS_MODULE
1465     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
1466     ENGINE **eptr = (e == NULL) ? &e :  NULL;
1467 #endif
1468
1469     /*
1470      * The setups can't set both legacy and provider side methods.
1471      * It is forbidden
1472      */
1473     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
1474         || !ossl_assert(e == NULL || keymgmt == NULL)) {
1475         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1476         return 0;
1477     }
1478
1479     if (pkey != NULL) {
1480         int free_it = 0;
1481
1482 #ifndef FIPS_MODULE
1483         free_it = free_it || pkey->pkey.ptr != NULL;
1484 #endif
1485         free_it = free_it || pkey->keydata != NULL;
1486         if (free_it)
1487             evp_pkey_free_it(pkey);
1488 #ifndef FIPS_MODULE
1489         /*
1490          * If key type matches and a method exists then this lookup has
1491          * succeeded once so just indicate success.
1492          */
1493         if (pkey->type != EVP_PKEY_NONE
1494             && type == pkey->save_type
1495             && pkey->ameth != NULL)
1496             return 1;
1497 # ifndef OPENSSL_NO_ENGINE
1498         /* If we have ENGINEs release them */
1499         ENGINE_finish(pkey->engine);
1500         pkey->engine = NULL;
1501         ENGINE_finish(pkey->pmeth_engine);
1502         pkey->pmeth_engine = NULL;
1503 # endif
1504 #endif
1505     }
1506 #ifndef FIPS_MODULE
1507     if (str != NULL)
1508         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1509     else if (type != EVP_PKEY_NONE)
1510         ameth = EVP_PKEY_asn1_find(eptr, type);
1511 # ifndef OPENSSL_NO_ENGINE
1512     if (pkey == NULL && eptr != NULL)
1513         ENGINE_finish(e);
1514 # endif
1515 #endif
1516
1517
1518     {
1519         int check = 1;
1520
1521 #ifndef FIPS_MODULE
1522         check = check && ameth == NULL;
1523 #endif
1524         check = check && keymgmt == NULL;
1525         if (check) {
1526             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
1527             return 0;
1528         }
1529     }
1530     if (pkey != NULL) {
1531         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1532             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1533             return 0;
1534         }
1535
1536         pkey->keymgmt = keymgmt;
1537
1538         pkey->save_type = type;
1539         pkey->type = type;
1540
1541 #ifndef FIPS_MODULE
1542         /*
1543          * If the internal "origin" key is provider side, don't save |ameth|.
1544          * The main reason is that |ameth| is one factor to detect that the
1545          * internal "origin" key is a legacy one.
1546          */
1547         if (keymgmt == NULL)
1548             pkey->ameth = ameth;
1549         pkey->engine = e;
1550
1551         /*
1552          * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose
1553          * for any key type that has a legacy implementation, regardless of
1554          * if the internal key is a legacy or a provider side one.  When
1555          * there is no legacy implementation for the key, the type becomes
1556          * EVP_PKEY_KEYMGMT, which indicates that one should be cautious
1557          * with functions that expect legacy internal keys.
1558          */
1559         if (ameth != NULL)
1560             pkey->type = ameth->pkey_id;
1561         else
1562             pkey->type = EVP_PKEY_KEYMGMT;
1563 #endif
1564     }
1565     return 1;
1566 }
1567
1568 #ifndef FIPS_MODULE
1569 static void find_ameth(const char *name, void *data)
1570 {
1571     const char **str = data;
1572
1573     /*
1574      * The error messages from pkey_set_type() are uninteresting here,
1575      * and misleading.
1576      */
1577     ERR_set_mark();
1578
1579     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1580                       NULL)) {
1581         if (str[0] == NULL)
1582             str[0] = name;
1583         else if (str[1] == NULL)
1584             str[1] = name;
1585     }
1586
1587     ERR_pop_to_mark();
1588 }
1589 #endif
1590
1591 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1592 {
1593 #ifndef FIPS_MODULE
1594 # define EVP_PKEY_TYPE_STR str[0]
1595 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1596     /*
1597      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1598      * Ideally, only one should be found.  If two (or more) are found, the
1599      * match is ambiguous.  This should never happen, but...
1600      */
1601     const char *str[2] = { NULL, NULL };
1602
1603     EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str);
1604     if (str[1] != NULL) {
1605         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1606         return 0;
1607     }
1608 #else
1609 # define EVP_PKEY_TYPE_STR NULL
1610 # define EVP_PKEY_TYPE_STRLEN -1
1611 #endif
1612     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1613                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1614                          keymgmt);
1615
1616 #undef EVP_PKEY_TYPE_STR
1617 #undef EVP_PKEY_TYPE_STRLEN
1618 }
1619
1620 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1621 {
1622     int i;
1623
1624     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
1625         return 0;
1626
1627     REF_PRINT_COUNT("EVP_PKEY", pkey);
1628     REF_ASSERT_ISNT(i < 2);
1629     return ((i > 1) ? 1 : 0);
1630 }
1631
1632 #ifndef FIPS_MODULE
1633 void evp_pkey_free_legacy(EVP_PKEY *x)
1634 {
1635     if (x->ameth != NULL) {
1636         if (x->ameth->pkey_free != NULL)
1637             x->ameth->pkey_free(x);
1638         x->pkey.ptr = NULL;
1639     }
1640 # ifndef OPENSSL_NO_ENGINE
1641     ENGINE_finish(x->engine);
1642     x->engine = NULL;
1643     ENGINE_finish(x->pmeth_engine);
1644     x->pmeth_engine = NULL;
1645 # endif
1646 }
1647 #endif  /* FIPS_MODULE */
1648
1649 static void evp_pkey_free_it(EVP_PKEY *x)
1650 {
1651     /* internal function; x is never NULL */
1652
1653     evp_keymgmt_util_clear_operation_cache(x);
1654 #ifndef FIPS_MODULE
1655     evp_pkey_free_legacy(x);
1656 #endif
1657
1658     if (x->keymgmt != NULL) {
1659         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1660         EVP_KEYMGMT_free(x->keymgmt);
1661         x->keymgmt = NULL;
1662         x->keydata = NULL;
1663     }
1664     x->type = EVP_PKEY_NONE;
1665 }
1666
1667 void EVP_PKEY_free(EVP_PKEY *x)
1668 {
1669     int i;
1670
1671     if (x == NULL)
1672         return;
1673
1674     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
1675     REF_PRINT_COUNT("EVP_PKEY", x);
1676     if (i > 0)
1677         return;
1678     REF_ASSERT_ISNT(i < 0);
1679     evp_pkey_free_it(x);
1680 #ifndef FIPS_MODULE
1681     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data);
1682 #endif
1683     CRYPTO_THREAD_lock_free(x->lock);
1684 #ifndef FIPS_MODULE
1685     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1686 #endif
1687     OPENSSL_free(x);
1688 }
1689
1690 int EVP_PKEY_size(const EVP_PKEY *pkey)
1691 {
1692     int size = 0;
1693
1694     if (pkey != NULL) {
1695         size = pkey->cache.size;
1696 #ifndef FIPS_MODULE
1697         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1698             size = pkey->ameth->pkey_size(pkey);
1699 #endif
1700     }
1701     return size < 0 ? 0 : size;
1702 }
1703
1704 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
1705                                   EVP_KEYMGMT **keymgmt,
1706                                   const char *propquery)
1707 {
1708     EVP_KEYMGMT *allocated_keymgmt = NULL;
1709     EVP_KEYMGMT *tmp_keymgmt = NULL;
1710     void *keydata = NULL;
1711     int check;
1712
1713     if (pk == NULL)
1714         return NULL;
1715
1716     /* No key data => nothing to export */
1717     check = 1;
1718 #ifndef FIPS_MODULE
1719     check = check && pk->pkey.ptr == NULL;
1720 #endif
1721     check = check && pk->keydata == NULL;
1722     if (check)
1723         return NULL;
1724
1725 #ifndef FIPS_MODULE
1726     if (pk->pkey.ptr != NULL) {
1727         /*
1728          * If the legacy key doesn't have an dirty counter or export function,
1729          * give up
1730          */
1731         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1732             return NULL;
1733     }
1734 #endif
1735
1736     if (keymgmt != NULL) {
1737         tmp_keymgmt = *keymgmt;
1738         *keymgmt = NULL;
1739     }
1740
1741     /*
1742      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1743      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1744      */
1745     if (tmp_keymgmt == NULL) {
1746         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1747
1748         tmp_keymgmt = ctx->keymgmt;
1749         ctx->keymgmt = NULL;
1750         EVP_PKEY_CTX_free(ctx);
1751     }
1752
1753     /* If there's still no keymgmt to be had, give up */
1754     if (tmp_keymgmt == NULL)
1755         goto end;
1756
1757 #ifndef FIPS_MODULE
1758     if (pk->pkey.ptr != NULL) {
1759         size_t i = 0;
1760
1761         /*
1762          * If the legacy "origin" hasn't changed since last time, we try
1763          * to find our keymgmt in the operation cache.  If it has changed,
1764          * |i| remains zero, and we will clear the cache further down.
1765          */
1766         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1767             i = evp_keymgmt_util_find_operation_cache_index(pk, tmp_keymgmt);
1768
1769             /*
1770              * If |tmp_keymgmt| is present in the operation cache, it means
1771              * that export doesn't need to be redone.  In that case, we take
1772              * token copies of the cached pointers, to have token success
1773              * values to return.
1774              */
1775             if (i < OSSL_NELEM(pk->operation_cache)
1776                 && pk->operation_cache[i].keymgmt != NULL) {
1777                 keydata = pk->operation_cache[i].keydata;
1778                 goto end;
1779             }
1780         }
1781
1782         /*
1783          * TODO(3.0) Right now, we assume we have ample space.  We will have
1784          * to think about a cache aging scheme, though, if |i| indexes outside
1785          * the array.
1786          */
1787         if (!ossl_assert(i < OSSL_NELEM(pk->operation_cache)))
1788             goto end;
1789
1790         /* Make sure that the keymgmt key type matches the legacy NID */
1791         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1792             goto end;
1793
1794         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1795             goto end;
1796
1797         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt, libctx, propquery)) {
1798             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1799             keydata = NULL;
1800             goto end;
1801         }
1802
1803         /*
1804          * If the dirty counter changed since last time, then clear the
1805          * operation cache.  In that case, we know that |i| is zero.  Just
1806          * in case this is a re-export, we increment then decrement the
1807          * keymgmt reference counter.
1808          */
1809         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1810             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1811             keydata = NULL;
1812             goto end;
1813         }
1814         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy)
1815             evp_keymgmt_util_clear_operation_cache(pk);
1816         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1817
1818         /* Add the new export to the operation cache */
1819         if (!evp_keymgmt_util_cache_keydata(pk, i, tmp_keymgmt, keydata)) {
1820             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1821             keydata = NULL;
1822             goto end;
1823         }
1824
1825         /* Synchronize the dirty count */
1826         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1827         goto end;
1828     }
1829 #endif  /* FIPS_MODULE */
1830
1831     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1832
1833  end:
1834     /*
1835      * If nothing was exported, |tmp_keymgmt| might point at a freed
1836      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1837      * the caller either way in that case.
1838      */
1839     if (keydata == NULL)
1840         tmp_keymgmt = NULL;
1841
1842     if (keymgmt != NULL)
1843         *keymgmt = tmp_keymgmt;
1844
1845     EVP_KEYMGMT_free(allocated_keymgmt);
1846     return keydata;
1847 }
1848
1849 #ifndef FIPS_MODULE
1850 int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
1851 {
1852     if (!ossl_assert(dest != NULL))
1853         return 0;
1854
1855     if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) {
1856         EVP_KEYMGMT *keymgmt = src->keymgmt;
1857         void *keydata = src->keydata;
1858         int type = src->type;
1859         const char *keytype = NULL;
1860
1861         keytype = evp_first_name(EVP_KEYMGMT_provider(keymgmt),
1862                                  keymgmt->name_id);
1863
1864         /*
1865          * If the type is EVP_PKEY_NONE, then we have a problem somewhere
1866          * else in our code.  If it's not one of the well known EVP_PKEY_xxx
1867          * values, it should at least be EVP_PKEY_KEYMGMT at this point.
1868          * TODO(3.0) remove this check when we're confident that the rest
1869          * of the code treats this correctly.
1870          */
1871         if (!ossl_assert(type != EVP_PKEY_NONE)) {
1872             ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR,
1873                            "keymgmt key type = %s but legacy type = EVP_PKEY_NONE",
1874                            keytype);
1875             return 0;
1876         }
1877
1878         /* Prefer the legacy key type name for error reporting */
1879         if (type != EVP_PKEY_KEYMGMT)
1880             keytype = OBJ_nid2sn(type);
1881
1882         /* Make sure we have a clean slate to copy into */
1883         if (*dest == NULL)
1884             *dest = EVP_PKEY_new();
1885         else
1886             evp_pkey_free_it(*dest);
1887
1888         if (EVP_PKEY_set_type(*dest, type)) {
1889             /* If the key is typed but empty, we're done */
1890             if (keydata == NULL)
1891                 return 1;
1892
1893             if ((*dest)->ameth->import_from == NULL) {
1894                 ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
1895                                "key type = %s", keytype);
1896             } else {
1897                 /*
1898                  * We perform the export in the same libctx as the keymgmt
1899                  * that we are using.
1900                  */
1901                 OSSL_LIB_CTX *libctx =
1902                     ossl_provider_libctx(keymgmt->prov);
1903                 EVP_PKEY_CTX *pctx =
1904                     EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL);
1905
1906                 if (pctx == NULL)
1907                     ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1908
1909                 if (pctx != NULL
1910                     && evp_keymgmt_export(keymgmt, keydata,
1911                                           OSSL_KEYMGMT_SELECT_ALL,
1912                                           (*dest)->ameth->import_from,
1913                                           pctx)) {
1914                     /* Synchronize the dirty count */
1915                     (*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest);
1916
1917                     EVP_PKEY_CTX_free(pctx);
1918                     return 1;
1919                 }
1920                 EVP_PKEY_CTX_free(pctx);
1921             }
1922
1923             ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
1924                            "key type = %s", keytype);
1925         }
1926     }
1927
1928     return 0;
1929 }
1930
1931 int evp_pkey_downgrade(EVP_PKEY *pk)
1932 {
1933     EVP_PKEY tmp_copy;              /* Stack allocated! */
1934     int rv = 0;
1935
1936     if (!ossl_assert(pk != NULL))
1937         return 0;
1938
1939     /*
1940      * Throughout this whole function, we must ensure that we lock / unlock
1941      * the exact same lock.  Note that we do pass it around a bit.
1942      */
1943     if (!CRYPTO_THREAD_write_lock(pk->lock))
1944         return 0;
1945
1946     /* If this isn't an assigned provider side key, we're done */
1947     if (!evp_pkey_is_assigned(pk) || !evp_pkey_is_provided(pk)) {
1948         rv = 1;
1949         goto end;
1950     }
1951
1952     /*
1953      * To be able to downgrade, we steal the contents of |pk|, then reset
1954      * it, and finally try to make it a downgraded copy.  If any of that
1955      * fails, we restore the copied contents into |pk|.
1956      */
1957     tmp_copy = *pk;              /* |tmp_copy| now owns THE lock */
1958
1959     if (evp_pkey_reset_unlocked(pk)
1960         && evp_pkey_copy_downgraded(&pk, &tmp_copy)) {
1961
1962         /* Restore the common attributes, then empty |tmp_copy| */
1963         pk->references = tmp_copy.references;
1964         pk->attributes = tmp_copy.attributes;
1965         pk->save_parameters = tmp_copy.save_parameters;
1966         pk->ex_data = tmp_copy.ex_data;
1967
1968         /* Ensure that stuff we've copied won't be freed */
1969         tmp_copy.lock = NULL;
1970         tmp_copy.attributes = NULL;
1971         memset(&tmp_copy.ex_data, 0, sizeof(tmp_copy.ex_data));
1972
1973         /*
1974          * Save the provider side data in the operation cache, so they'll
1975          * find it again.  |pk| is new, so it's safe to assume slot zero
1976          * is free.
1977          * Note that evp_keymgmt_util_cache_keydata() increments keymgmt's
1978          * reference count, so we need to decrement it, or there will be a
1979          * leak.
1980          */
1981         evp_keymgmt_util_cache_keydata(pk, 0, tmp_copy.keymgmt,
1982                                        tmp_copy.keydata);
1983         EVP_KEYMGMT_free(tmp_copy.keymgmt);
1984
1985         /*
1986          * Clear keymgmt and keydata from |tmp_copy|, or they'll get
1987          * inadvertently freed.
1988          */
1989         tmp_copy.keymgmt = NULL;
1990         tmp_copy.keydata = NULL;
1991
1992         evp_pkey_free_it(&tmp_copy);
1993         rv = 1;
1994     } else {
1995         /* Restore the original key */
1996         *pk = tmp_copy;
1997     }
1998
1999  end:
2000     if (!CRYPTO_THREAD_unlock(pk->lock))
2001         return 0;
2002     return rv;
2003 }
2004 #endif  /* FIPS_MODULE */
2005
2006 const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey)
2007 {
2008     if (pkey == NULL
2009         || pkey->keymgmt == NULL
2010         || pkey->keydata == NULL)
2011         return 0;
2012     return EVP_KEYMGMT_gettable_params(pkey->keymgmt);
2013 }
2014
2015 int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name,
2016                           BIGNUM **bn)
2017 {
2018     int ret = 0;
2019     OSSL_PARAM params[2];
2020     unsigned char buffer[2048];
2021     unsigned char *buf = NULL;
2022     size_t buf_sz = 0;
2023
2024     if (pkey == NULL
2025         || pkey->keymgmt == NULL
2026         || pkey->keydata == NULL
2027         || key_name == NULL
2028         || bn == NULL)
2029         return 0;
2030
2031     memset(buffer, 0, sizeof(buffer));
2032     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
2033     params[1] = OSSL_PARAM_construct_end();
2034     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)) {
2035         if (!OSSL_PARAM_modified(params) || params[0].return_size == 0)
2036             return 0;
2037         buf_sz = params[0].return_size;
2038         /*
2039          * If it failed because the buffer was too small then allocate the
2040          * required buffer size and retry.
2041          */
2042         buf = OPENSSL_zalloc(buf_sz);
2043         if (buf == NULL)
2044             return 0;
2045         params[0].data = buf;
2046         params[0].data_size = buf_sz;
2047
2048         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
2049             goto err;
2050     }
2051     /* Fail if the param was not found */
2052     if (!OSSL_PARAM_modified(params))
2053         goto err;
2054     ret = OSSL_PARAM_get_BN(params, bn);
2055 err:
2056     OPENSSL_free(buf);
2057     return ret;
2058 }
2059
2060 int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name,
2061                                     unsigned char *buf, size_t max_buf_sz,
2062                                     size_t *out_sz)
2063 {
2064     OSSL_PARAM params[2];
2065
2066     if (pkey == NULL
2067         || pkey->keymgmt == NULL
2068         || pkey->keydata == NULL
2069         || key_name == NULL)
2070         return 0;
2071
2072     params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
2073     params[1] = OSSL_PARAM_construct_end();
2074     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)
2075         || !OSSL_PARAM_modified(params))
2076         return 0;
2077     if (out_sz != NULL)
2078         *out_sz = params[0].return_size;
2079     return 1;
2080 }
2081
2082 int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name,
2083                                     char *str, size_t max_buf_sz,
2084                                     size_t *out_sz)
2085 {
2086     OSSL_PARAM params[2];
2087
2088     if (pkey == NULL
2089         || pkey->keymgmt == NULL
2090         || pkey->keydata == NULL
2091         || key_name == NULL)
2092         return 0;
2093
2094     params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
2095     params[1] = OSSL_PARAM_construct_end();
2096     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)
2097         || !OSSL_PARAM_modified(params))
2098         return 0;
2099     if (out_sz != NULL)
2100         *out_sz = params[0].return_size;
2101     return 1;
2102 }
2103
2104 int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name,
2105                            int *out)
2106 {
2107     OSSL_PARAM params[2];
2108
2109     if (pkey == NULL
2110         || pkey->keymgmt == NULL
2111         || pkey->keydata == NULL
2112         || key_name == NULL)
2113         return 0;
2114
2115     params[0] = OSSL_PARAM_construct_int(key_name, out);
2116     params[1] = OSSL_PARAM_construct_end();
2117     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)
2118         || !OSSL_PARAM_modified(params))
2119         return 0;
2120     return 1;
2121 }
2122
2123 int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name,
2124                               size_t *out)
2125 {
2126     OSSL_PARAM params[2];
2127
2128     if (pkey == NULL
2129         || pkey->keymgmt == NULL
2130         || pkey->keydata == NULL
2131         || key_name == NULL)
2132         return 0;
2133
2134     params[0] = OSSL_PARAM_construct_size_t(key_name, out);
2135     params[1] = OSSL_PARAM_construct_end();
2136     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)
2137         || !OSSL_PARAM_modified(params))
2138         return 0;
2139     return 1;
2140 }