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