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