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