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