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