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