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