63f3f4cbc7b1eb81974a3da1fd2c3777ca146275
[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         ossl_ecx_key_up_ref(ret);
842     return ret;
843 }
844
845 #  define IMPLEMENT_ECX_VARIANT(NAME)                                   \
846     ECX_KEY *ossl_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 int 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 0;
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 1;
997     }
998     return 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                 if (!ossl_namemap_doall_names(namemap, mdnum, mdname2nid, &nid))
1186                     return 0;
1187                 *(int *)arg2 = nid;
1188             }
1189             return rv;
1190         }
1191     default:
1192         return -2;
1193     }
1194 }
1195
1196 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
1197 {
1198     if (pkey->ameth == NULL)
1199         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
1200     if (pkey->ameth->pkey_ctrl == NULL)
1201         return -2;
1202     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
1203 }
1204
1205 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
1206 {
1207     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
1208 }
1209
1210 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
1211                                      char *mdname, size_t mdname_sz)
1212 {
1213     if (pkey->ameth == NULL)
1214         return evp_keymgmt_util_get_deflt_digest_name(pkey->keymgmt,
1215                                                       pkey->keydata,
1216                                                       mdname, mdname_sz);
1217
1218     {
1219         int nid = NID_undef;
1220         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
1221         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
1222
1223         if (rv > 0)
1224             OPENSSL_strlcpy(mdname, name, mdname_sz);
1225         return rv;
1226     }
1227 }
1228
1229 int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *gname, size_t gname_sz,
1230                             size_t *gname_len)
1231 {
1232     return EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME,
1233                                           gname, gname_sz, gname_len);
1234 }
1235
1236 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
1237 {
1238     int rv, default_nid;
1239
1240     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
1241     if (rv == -2) {
1242         /*
1243          * If there is a mandatory default digest and this isn't it, then
1244          * the answer is 'no'.
1245          */
1246         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
1247         if (rv == 2)
1248             return (nid == default_nid);
1249         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
1250         if (rv == 0)
1251             return -1;
1252     }
1253     return rv;
1254 }
1255
1256 int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub,
1257                                      size_t publen)
1258 {
1259     if (pkey != NULL && evp_pkey_is_provided(pkey))
1260         return
1261             EVP_PKEY_set_octet_string_param(pkey,
1262                                             OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1263                                             (unsigned char *)pub, publen);
1264
1265     if (publen > INT_MAX)
1266         return 0;
1267     /* Historically this function was EVP_PKEY_set1_tls_encodedpoint */
1268     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen,
1269                            (void *)pub) <= 0)
1270         return 0;
1271     return 1;
1272 }
1273
1274 size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub)
1275 {
1276     int rv;
1277
1278     if (pkey != NULL && evp_pkey_is_provided(pkey)) {
1279         size_t return_size = OSSL_PARAM_UNMODIFIED;
1280
1281         /*
1282          * We know that this is going to fail, but it will give us a size
1283          * to allocate.
1284          */
1285         EVP_PKEY_get_octet_string_param(pkey,
1286                                         OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1287                                         NULL, 0, &return_size);
1288         if (return_size == OSSL_PARAM_UNMODIFIED)
1289             return 0;
1290
1291         *ppub = OPENSSL_malloc(return_size);
1292         if (*ppub == NULL)
1293             return 0;
1294
1295         if (!EVP_PKEY_get_octet_string_param(pkey,
1296                                              OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1297                                              *ppub, return_size, NULL))
1298             return 0;
1299         return return_size;
1300     }
1301
1302
1303     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub);
1304     if (rv <= 0)
1305         return 0;
1306     return rv;
1307 }
1308
1309 #endif /* FIPS_MODULE */
1310
1311 /*- All methods below can also be used in FIPS_MODULE */
1312
1313 /*
1314  * This reset function must be used very carefully, as it literally throws
1315  * away everything in an EVP_PKEY without freeing them, and may cause leaks
1316  * of memory, what have you.
1317  * The only reason we have this is to have the same code for EVP_PKEY_new()
1318  * and evp_pkey_downgrade().
1319  */
1320 static int evp_pkey_reset_unlocked(EVP_PKEY *pk)
1321 {
1322     if (pk == NULL)
1323         return 0;
1324
1325     if (pk->lock != NULL) {
1326       const size_t offset = (unsigned char *)&pk->lock - (unsigned char *)pk;
1327
1328       memset(pk, 0, offset);
1329       memset((unsigned char *)pk + offset + sizeof(pk->lock),
1330              0,
1331              sizeof(*pk) - offset - sizeof(pk->lock));
1332     }
1333     /* EVP_PKEY_new uses zalloc so no need to call memset if pk->lock is NULL */
1334
1335     pk->type = EVP_PKEY_NONE;
1336     pk->save_type = EVP_PKEY_NONE;
1337     pk->references = 1;
1338     pk->save_parameters = 1;
1339
1340     return 1;
1341 }
1342
1343 EVP_PKEY *EVP_PKEY_new(void)
1344 {
1345     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
1346
1347     if (ret == NULL) {
1348         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1349         return NULL;
1350     }
1351
1352     if (!evp_pkey_reset_unlocked(ret))
1353         goto err;
1354
1355     ret->lock = CRYPTO_THREAD_lock_new();
1356     if (ret->lock == NULL) {
1357         EVPerr(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1358         goto err;
1359     }
1360
1361 #ifndef FIPS_MODULE
1362     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) {
1363         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1364         goto err;
1365     }
1366 #endif
1367     return ret;
1368
1369  err:
1370     CRYPTO_THREAD_lock_free(ret->lock);
1371     OPENSSL_free(ret);
1372     return NULL;
1373 }
1374
1375 /*
1376  * Setup a public key management method.
1377  *
1378  * For legacy keys, either |type| or |str| is expected to have the type
1379  * information.  In this case, the setup consists of finding an ASN1 method
1380  * and potentially an ENGINE, and setting those fields in |pkey|.
1381  *
1382  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
1383  * case, the setup consists of setting the |keymgmt| field in |pkey|.
1384  *
1385  * If pkey is NULL just return 1 or 0 if the key management method exists.
1386  */
1387
1388 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
1389                          int len, EVP_KEYMGMT *keymgmt)
1390 {
1391 #ifndef FIPS_MODULE
1392     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
1393     ENGINE **eptr = (e == NULL) ? &e :  NULL;
1394 #endif
1395
1396     /*
1397      * The setups can't set both legacy and provider side methods.
1398      * It is forbidden
1399      */
1400     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
1401         || !ossl_assert(e == NULL || keymgmt == NULL)) {
1402         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1403         return 0;
1404     }
1405
1406     if (pkey != NULL) {
1407         int free_it = 0;
1408
1409 #ifndef FIPS_MODULE
1410         free_it = free_it || pkey->pkey.ptr != NULL;
1411 #endif
1412         free_it = free_it || pkey->keydata != NULL;
1413         if (free_it)
1414             evp_pkey_free_it(pkey);
1415 #ifndef FIPS_MODULE
1416         /*
1417          * If key type matches and a method exists then this lookup has
1418          * succeeded once so just indicate success.
1419          */
1420         if (pkey->type != EVP_PKEY_NONE
1421             && type == pkey->save_type
1422             && pkey->ameth != NULL)
1423             return 1;
1424 # ifndef OPENSSL_NO_ENGINE
1425         /* If we have ENGINEs release them */
1426         ENGINE_finish(pkey->engine);
1427         pkey->engine = NULL;
1428         ENGINE_finish(pkey->pmeth_engine);
1429         pkey->pmeth_engine = NULL;
1430 # endif
1431 #endif
1432     }
1433 #ifndef FIPS_MODULE
1434     if (str != NULL)
1435         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1436     else if (type != EVP_PKEY_NONE)
1437         ameth = EVP_PKEY_asn1_find(eptr, type);
1438 # ifndef OPENSSL_NO_ENGINE
1439     if (pkey == NULL && eptr != NULL)
1440         ENGINE_finish(e);
1441 # endif
1442 #endif
1443
1444
1445     {
1446         int check = 1;
1447
1448 #ifndef FIPS_MODULE
1449         check = check && ameth == NULL;
1450 #endif
1451         check = check && keymgmt == NULL;
1452         if (check) {
1453             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
1454             return 0;
1455         }
1456     }
1457     if (pkey != NULL) {
1458         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1459             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1460             return 0;
1461         }
1462
1463         pkey->keymgmt = keymgmt;
1464
1465         pkey->save_type = type;
1466         pkey->type = type;
1467
1468 #ifndef FIPS_MODULE
1469         /*
1470          * If the internal "origin" key is provider side, don't save |ameth|.
1471          * The main reason is that |ameth| is one factor to detect that the
1472          * internal "origin" key is a legacy one.
1473          */
1474         if (keymgmt == NULL)
1475             pkey->ameth = ameth;
1476         pkey->engine = e;
1477
1478         /*
1479          * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose
1480          * for any key type that has a legacy implementation, regardless of
1481          * if the internal key is a legacy or a provider side one.  When
1482          * there is no legacy implementation for the key, the type becomes
1483          * EVP_PKEY_KEYMGMT, which indicates that one should be cautious
1484          * with functions that expect legacy internal keys.
1485          */
1486         if (ameth != NULL)
1487             pkey->type = ameth->pkey_id;
1488         else
1489             pkey->type = EVP_PKEY_KEYMGMT;
1490 #endif
1491     }
1492     return 1;
1493 }
1494
1495 #ifndef FIPS_MODULE
1496 static void find_ameth(const char *name, void *data)
1497 {
1498     const char **str = data;
1499
1500     /*
1501      * The error messages from pkey_set_type() are uninteresting here,
1502      * and misleading.
1503      */
1504     ERR_set_mark();
1505
1506     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1507                       NULL)) {
1508         if (str[0] == NULL)
1509             str[0] = name;
1510         else if (str[1] == NULL)
1511             str[1] = name;
1512     }
1513
1514     ERR_pop_to_mark();
1515 }
1516 #endif
1517
1518 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1519 {
1520 #ifndef FIPS_MODULE
1521 # define EVP_PKEY_TYPE_STR str[0]
1522 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1523     /*
1524      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1525      * Ideally, only one should be found.  If two (or more) are found, the
1526      * match is ambiguous.  This should never happen, but...
1527      */
1528     const char *str[2] = { NULL, NULL };
1529
1530     if (!EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str)
1531             || str[1] != NULL) {
1532         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1533         return 0;
1534     }
1535 #else
1536 # define EVP_PKEY_TYPE_STR NULL
1537 # define EVP_PKEY_TYPE_STRLEN -1
1538 #endif
1539     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1540                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1541                          keymgmt);
1542
1543 #undef EVP_PKEY_TYPE_STR
1544 #undef EVP_PKEY_TYPE_STRLEN
1545 }
1546
1547 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1548 {
1549     int i;
1550
1551     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
1552         return 0;
1553
1554     REF_PRINT_COUNT("EVP_PKEY", pkey);
1555     REF_ASSERT_ISNT(i < 2);
1556     return ((i > 1) ? 1 : 0);
1557 }
1558
1559 #ifndef FIPS_MODULE
1560 void evp_pkey_free_legacy(EVP_PKEY *x)
1561 {
1562     if (x->ameth != NULL) {
1563         if (x->ameth->pkey_free != NULL)
1564             x->ameth->pkey_free(x);
1565         x->pkey.ptr = NULL;
1566     }
1567 # ifndef OPENSSL_NO_ENGINE
1568     ENGINE_finish(x->engine);
1569     x->engine = NULL;
1570     ENGINE_finish(x->pmeth_engine);
1571     x->pmeth_engine = NULL;
1572 # endif
1573 }
1574 #endif  /* FIPS_MODULE */
1575
1576 static void evp_pkey_free_it(EVP_PKEY *x)
1577 {
1578     /* internal function; x is never NULL */
1579     evp_keymgmt_util_clear_operation_cache(x, 1);
1580 #ifndef FIPS_MODULE
1581     evp_pkey_free_legacy(x);
1582 #endif
1583
1584     if (x->keymgmt != NULL) {
1585         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1586         EVP_KEYMGMT_free(x->keymgmt);
1587         x->keymgmt = NULL;
1588         x->keydata = NULL;
1589     }
1590     x->type = EVP_PKEY_NONE;
1591 }
1592
1593 void EVP_PKEY_free(EVP_PKEY *x)
1594 {
1595     int i;
1596
1597     if (x == NULL)
1598         return;
1599
1600     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
1601     REF_PRINT_COUNT("EVP_PKEY", x);
1602     if (i > 0)
1603         return;
1604     REF_ASSERT_ISNT(i < 0);
1605     evp_pkey_free_it(x);
1606 #ifndef FIPS_MODULE
1607     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data);
1608 #endif
1609     CRYPTO_THREAD_lock_free(x->lock);
1610 #ifndef FIPS_MODULE
1611     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1612 #endif
1613     OPENSSL_free(x);
1614 }
1615
1616 int EVP_PKEY_size(const EVP_PKEY *pkey)
1617 {
1618     int size = 0;
1619
1620     if (pkey != NULL) {
1621         size = pkey->cache.size;
1622 #ifndef FIPS_MODULE
1623         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1624             size = pkey->ameth->pkey_size(pkey);
1625 #endif
1626     }
1627     return size < 0 ? 0 : size;
1628 }
1629
1630 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
1631                                   EVP_KEYMGMT **keymgmt,
1632                                   const char *propquery)
1633 {
1634     EVP_KEYMGMT *allocated_keymgmt = NULL;
1635     EVP_KEYMGMT *tmp_keymgmt = NULL;
1636     void *keydata = NULL;
1637     int check;
1638
1639     if (pk == NULL)
1640         return NULL;
1641
1642     /* No key data => nothing to export */
1643     check = 1;
1644 #ifndef FIPS_MODULE
1645     check = check && pk->pkey.ptr == NULL;
1646 #endif
1647     check = check && pk->keydata == NULL;
1648     if (check)
1649         return NULL;
1650
1651 #ifndef FIPS_MODULE
1652     if (pk->pkey.ptr != NULL) {
1653         /*
1654          * If the legacy key doesn't have an dirty counter or export function,
1655          * give up
1656          */
1657         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1658             return NULL;
1659     }
1660 #endif
1661
1662     if (keymgmt != NULL) {
1663         tmp_keymgmt = *keymgmt;
1664         *keymgmt = NULL;
1665     }
1666
1667     /*
1668      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1669      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1670      */
1671     if (tmp_keymgmt == NULL) {
1672         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1673
1674         tmp_keymgmt = ctx->keymgmt;
1675         ctx->keymgmt = NULL;
1676         EVP_PKEY_CTX_free(ctx);
1677     }
1678
1679     /* If there's still no keymgmt to be had, give up */
1680     if (tmp_keymgmt == NULL)
1681         goto end;
1682
1683 #ifndef FIPS_MODULE
1684     if (pk->pkey.ptr != NULL) {
1685         OP_CACHE_ELEM *op;
1686
1687         /*
1688          * If the legacy "origin" hasn't changed since last time, we try
1689          * to find our keymgmt in the operation cache.  If it has changed,
1690          * |i| remains zero, and we will clear the cache further down.
1691          */
1692         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1693             if (!CRYPTO_THREAD_read_lock(pk->lock))
1694                 goto end;
1695             op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt);
1696
1697             /*
1698              * If |tmp_keymgmt| is present in the operation cache, it means
1699              * that export doesn't need to be redone.  In that case, we take
1700              * token copies of the cached pointers, to have token success
1701              * values to return.
1702              */
1703             if (op != NULL && op->keymgmt != NULL) {
1704                 keydata = op->keydata;
1705                 CRYPTO_THREAD_unlock(pk->lock);
1706                 goto end;
1707             }
1708             CRYPTO_THREAD_unlock(pk->lock);
1709         }
1710
1711         /* Make sure that the keymgmt key type matches the legacy NID */
1712         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1713             goto end;
1714
1715         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1716             goto end;
1717
1718         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt, libctx, propquery)) {
1719             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1720             keydata = NULL;
1721             goto end;
1722         }
1723
1724         /*
1725          * If the dirty counter changed since last time, then clear the
1726          * operation cache.  In that case, we know that |i| is zero.  Just
1727          * in case this is a re-export, we increment then decrement the
1728          * keymgmt reference counter.
1729          */
1730         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1731             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1732             keydata = NULL;
1733             goto end;
1734         }
1735
1736         if (!CRYPTO_THREAD_write_lock(pk->lock))
1737             goto end;
1738         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy
1739                 && !evp_keymgmt_util_clear_operation_cache(pk, 0)) {
1740             CRYPTO_THREAD_unlock(pk->lock);
1741             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1742             keydata = NULL;
1743             EVP_KEYMGMT_free(tmp_keymgmt);
1744             goto end;
1745         }
1746         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1747
1748         /* Check to make sure some other thread didn't get there first */
1749         op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt);
1750         if (op != NULL && op->keymgmt != NULL) {
1751             void *tmp_keydata = op->keydata;
1752
1753             CRYPTO_THREAD_unlock(pk->lock);
1754             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1755             keydata = tmp_keydata;
1756             goto end;
1757         }
1758
1759         /* Add the new export to the operation cache */
1760         if (!evp_keymgmt_util_cache_keydata(pk, tmp_keymgmt, keydata)) {
1761             CRYPTO_THREAD_unlock(pk->lock);
1762             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1763             keydata = NULL;
1764             goto end;
1765         }
1766
1767         /* Synchronize the dirty count */
1768         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1769     
1770         CRYPTO_THREAD_unlock(pk->lock);
1771         goto end;
1772     }
1773 #endif  /* FIPS_MODULE */
1774
1775     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1776
1777  end:
1778     /*
1779      * If nothing was exported, |tmp_keymgmt| might point at a freed
1780      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1781      * the caller either way in that case.
1782      */
1783     if (keydata == NULL)
1784         tmp_keymgmt = NULL;
1785
1786     if (keymgmt != NULL)
1787         *keymgmt = tmp_keymgmt;
1788
1789     EVP_KEYMGMT_free(allocated_keymgmt);
1790     return keydata;
1791 }
1792
1793 #ifndef FIPS_MODULE
1794 int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
1795 {
1796     if (!ossl_assert(dest != NULL))
1797         return 0;
1798
1799     if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) {
1800         EVP_KEYMGMT *keymgmt = src->keymgmt;
1801         void *keydata = src->keydata;
1802         int type = src->type;
1803         const char *keytype = NULL;
1804
1805         keytype = evp_first_name(EVP_KEYMGMT_provider(keymgmt),
1806                                  keymgmt->name_id);
1807
1808         /*
1809          * If the type is EVP_PKEY_NONE, then we have a problem somewhere
1810          * else in our code.  If it's not one of the well known EVP_PKEY_xxx
1811          * values, it should at least be EVP_PKEY_KEYMGMT at this point.
1812          * TODO(3.0) remove this check when we're confident that the rest
1813          * of the code treats this correctly.
1814          */
1815         if (!ossl_assert(type != EVP_PKEY_NONE)) {
1816             ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR,
1817                            "keymgmt key type = %s but legacy type = EVP_PKEY_NONE",
1818                            keytype);
1819             return 0;
1820         }
1821
1822         /* Prefer the legacy key type name for error reporting */
1823         if (type != EVP_PKEY_KEYMGMT)
1824             keytype = OBJ_nid2sn(type);
1825
1826         /* Make sure we have a clean slate to copy into */
1827         if (*dest == NULL)
1828             *dest = EVP_PKEY_new();
1829         else
1830             evp_pkey_free_it(*dest);
1831
1832         if (EVP_PKEY_set_type(*dest, type)) {
1833             /* If the key is typed but empty, we're done */
1834             if (keydata == NULL)
1835                 return 1;
1836
1837             if ((*dest)->ameth->import_from == NULL) {
1838                 ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
1839                                "key type = %s", keytype);
1840             } else {
1841                 /*
1842                  * We perform the export in the same libctx as the keymgmt
1843                  * that we are using.
1844                  */
1845                 OSSL_LIB_CTX *libctx =
1846                     ossl_provider_libctx(keymgmt->prov);
1847                 EVP_PKEY_CTX *pctx =
1848                     EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL);
1849
1850                 if (pctx == NULL)
1851                     ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1852
1853                 if (pctx != NULL
1854                     && evp_keymgmt_export(keymgmt, keydata,
1855                                           OSSL_KEYMGMT_SELECT_ALL,
1856                                           (*dest)->ameth->import_from,
1857                                           pctx)) {
1858                     /* Synchronize the dirty count */
1859                     (*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest);
1860
1861                     EVP_PKEY_CTX_free(pctx);
1862                     return 1;
1863                 }
1864                 EVP_PKEY_CTX_free(pctx);
1865             }
1866
1867             ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
1868                            "key type = %s", keytype);
1869         }
1870     }
1871
1872     return 0;
1873 }
1874
1875 int evp_pkey_downgrade(EVP_PKEY *pk)
1876 {
1877     EVP_PKEY tmp_copy;              /* Stack allocated! */
1878     int rv = 0;
1879
1880     if (!ossl_assert(pk != NULL))
1881         return 0;
1882
1883     /*
1884      * Throughout this whole function, we must ensure that we lock / unlock
1885      * the exact same lock.  Note that we do pass it around a bit.
1886      */
1887     if (!CRYPTO_THREAD_write_lock(pk->lock))
1888         return 0;
1889
1890     /* If this isn't an assigned provider side key, we're done */
1891     if (!evp_pkey_is_assigned(pk) || !evp_pkey_is_provided(pk)) {
1892         rv = 1;
1893         goto end;
1894     }
1895
1896     /*
1897      * To be able to downgrade, we steal the contents of |pk|, then reset
1898      * it, and finally try to make it a downgraded copy.  If any of that
1899      * fails, we restore the copied contents into |pk|.
1900      */
1901     tmp_copy = *pk;              /* |tmp_copy| now owns THE lock */
1902
1903     if (evp_pkey_reset_unlocked(pk)
1904         && evp_pkey_copy_downgraded(&pk, &tmp_copy)) {
1905
1906         /* Restore the common attributes, then empty |tmp_copy| */
1907         pk->references = tmp_copy.references;
1908         pk->attributes = tmp_copy.attributes;
1909         pk->save_parameters = tmp_copy.save_parameters;
1910         pk->ex_data = tmp_copy.ex_data;
1911
1912         /* Ensure that stuff we've copied won't be freed */
1913         tmp_copy.lock = NULL;
1914         tmp_copy.attributes = NULL;
1915         memset(&tmp_copy.ex_data, 0, sizeof(tmp_copy.ex_data));
1916
1917         /*
1918          * Save the provider side data in the operation cache, so they'll
1919          * find it again.  |pk| is new, so it's safe to assume slot zero
1920          * is free.
1921          * Note that evp_keymgmt_util_cache_keydata() increments keymgmt's
1922          * reference count, so we need to decrement it, or there will be a
1923          * leak.
1924          */
1925         evp_keymgmt_util_cache_keydata(pk, tmp_copy.keymgmt,
1926                                        tmp_copy.keydata);
1927         EVP_KEYMGMT_free(tmp_copy.keymgmt);
1928
1929         /*
1930          * Clear keymgmt and keydata from |tmp_copy|, or they'll get
1931          * inadvertently freed.
1932          */
1933         tmp_copy.keymgmt = NULL;
1934         tmp_copy.keydata = NULL;
1935
1936         evp_pkey_free_it(&tmp_copy);
1937         rv = 1;
1938     } else {
1939         /* Restore the original key */
1940         *pk = tmp_copy;
1941     }
1942
1943  end:
1944     if (!CRYPTO_THREAD_unlock(pk->lock))
1945         return 0;
1946     return rv;
1947 }
1948 #endif  /* FIPS_MODULE */
1949
1950 int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name,
1951                           BIGNUM **bn)
1952 {
1953     int ret = 0;
1954     OSSL_PARAM params[2];
1955     unsigned char buffer[2048];
1956     unsigned char *buf = NULL;
1957     size_t buf_sz = 0;
1958
1959     if (key_name == NULL
1960         || bn == NULL
1961         || pkey == NULL
1962         || !evp_pkey_is_provided(pkey))
1963         return 0;
1964
1965     memset(buffer, 0, sizeof(buffer));
1966     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
1967     params[1] = OSSL_PARAM_construct_end();
1968     if (!EVP_PKEY_get_params(pkey, params)) {
1969         if (!OSSL_PARAM_modified(params) || params[0].return_size == 0)
1970             return 0;
1971         buf_sz = params[0].return_size;
1972         /*
1973          * If it failed because the buffer was too small then allocate the
1974          * required buffer size and retry.
1975          */
1976         buf = OPENSSL_zalloc(buf_sz);
1977         if (buf == NULL)
1978             return 0;
1979         params[0].data = buf;
1980         params[0].data_size = buf_sz;
1981
1982         if (!EVP_PKEY_get_params(pkey, params))
1983             goto err;
1984     }
1985     /* Fail if the param was not found */
1986     if (!OSSL_PARAM_modified(params))
1987         goto err;
1988     ret = OSSL_PARAM_get_BN(params, bn);
1989 err:
1990     OPENSSL_free(buf);
1991     return ret;
1992 }
1993
1994 int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name,
1995                                     unsigned char *buf, size_t max_buf_sz,
1996                                     size_t *out_sz)
1997 {
1998     OSSL_PARAM params[2];
1999     int ret1 = 0, ret2 = 0;
2000
2001     if (key_name == NULL
2002         || pkey == NULL
2003         || !evp_pkey_is_provided(pkey))
2004         return 0;
2005
2006     params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
2007     params[1] = OSSL_PARAM_construct_end();
2008     if ((ret1 = EVP_PKEY_get_params(pkey, params)))
2009         ret2 = OSSL_PARAM_modified(params);
2010     if (ret2 && out_sz != NULL)
2011         *out_sz = params[0].return_size;
2012     return ret1 && ret2;
2013 }
2014
2015 int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name,
2016                                     char *str, size_t max_buf_sz,
2017                                     size_t *out_sz)
2018 {
2019     OSSL_PARAM params[2];
2020     int ret1 = 0, ret2 = 0;
2021
2022     if (key_name == NULL)
2023         return 0;
2024
2025     params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
2026     params[1] = OSSL_PARAM_construct_end();
2027     if ((ret1 = EVP_PKEY_get_params(pkey, params)))
2028         ret2 = OSSL_PARAM_modified(params);
2029     if (ret2 && out_sz != NULL)
2030         *out_sz = params[0].return_size;
2031     return ret1 && ret2;
2032 }
2033
2034 int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name,
2035                            int *out)
2036 {
2037     OSSL_PARAM params[2];
2038
2039     if (key_name == NULL)
2040         return 0;
2041
2042     params[0] = OSSL_PARAM_construct_int(key_name, out);
2043     params[1] = OSSL_PARAM_construct_end();
2044     return EVP_PKEY_get_params(pkey, params)
2045         && OSSL_PARAM_modified(params);
2046 }
2047
2048 int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name,
2049                               size_t *out)
2050 {
2051     OSSL_PARAM params[2];
2052
2053     if (key_name == NULL)
2054         return 0;
2055
2056     params[0] = OSSL_PARAM_construct_size_t(key_name, out);
2057     params[1] = OSSL_PARAM_construct_end();
2058     return EVP_PKEY_get_params(pkey, params)
2059         && OSSL_PARAM_modified(params);
2060 }
2061
2062 int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in)
2063 {
2064     OSSL_PARAM params[2];
2065
2066     if (key_name == NULL)
2067         return 0;
2068
2069     params[0] = OSSL_PARAM_construct_int(key_name, &in);
2070     params[1] = OSSL_PARAM_construct_end();
2071     return EVP_PKEY_set_params(pkey, params);
2072 }
2073
2074 int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in)
2075 {
2076     OSSL_PARAM params[2];
2077
2078     if (key_name == NULL)
2079         return 0;
2080
2081     params[0] = OSSL_PARAM_construct_size_t(key_name, &in);
2082     params[1] = OSSL_PARAM_construct_end();
2083     return EVP_PKEY_set_params(pkey, params);
2084 }
2085
2086 int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name,
2087                           const BIGNUM *bn)
2088 {
2089     OSSL_PARAM params[2];
2090     unsigned char buffer[2048];
2091     int bsize = 0;
2092
2093     if (key_name == NULL
2094         || bn == NULL
2095         || pkey == NULL
2096         || !evp_pkey_is_assigned(pkey))
2097         return 0;
2098
2099     bsize = BN_num_bytes(bn);
2100     if (!ossl_assert(bsize <= (int)sizeof(buffer)))
2101         return 0;
2102
2103     if (BN_bn2nativepad(bn, buffer, bsize) < 0)
2104         return 0;
2105     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, bsize);
2106     params[1] = OSSL_PARAM_construct_end();
2107     return EVP_PKEY_set_params(pkey, params);
2108 }
2109
2110 int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
2111                                    const char *str)
2112 {
2113     OSSL_PARAM params[2];
2114
2115     if (key_name == NULL)
2116         return 0;
2117
2118     params[0] = OSSL_PARAM_construct_utf8_string(key_name, (char *)str, 0);
2119     params[1] = OSSL_PARAM_construct_end();
2120     return EVP_PKEY_set_params(pkey, params);
2121 }
2122
2123 int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name,
2124                                     const unsigned char *buf, size_t bsize)
2125 {
2126     OSSL_PARAM params[2];
2127
2128     if (key_name == NULL)
2129         return 0;
2130
2131     params[0] = OSSL_PARAM_construct_octet_string(key_name,
2132                                                   (unsigned char *)buf, bsize);
2133     params[1] = OSSL_PARAM_construct_end();
2134     return EVP_PKEY_set_params(pkey, params);
2135 }
2136
2137 const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey)
2138 {
2139     return (pkey != NULL && evp_pkey_is_provided(pkey))
2140         ? EVP_KEYMGMT_settable_params(pkey->keymgmt)
2141         : NULL;
2142 }
2143
2144 int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[])
2145 {
2146     if (pkey != NULL) {
2147         if (evp_pkey_is_provided(pkey)) {
2148             pkey->dirty_cnt++;
2149             return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params);
2150         }
2151 #ifndef FIPS_MODULE
2152         /*
2153          * TODO?
2154          * We will hopefully never find the need to set individual data in
2155          * EVP_PKEYs with a legacy internal key, but we can't be entirely
2156          * sure.  This bit of code can be enabled if we find the need.  If
2157          * not, it can safely be removed when #legacy support is removed.
2158          */
2159 # if 0
2160         else if (evp_pkey_is_legacy(pkey)) {
2161             return evp_pkey_set_params_to_ctrl(pkey, params);
2162         }
2163 # endif
2164 #endif
2165     }
2166     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
2167     return 0;
2168 }
2169
2170 const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey)
2171 {
2172     return (pkey != NULL && evp_pkey_is_provided(pkey))
2173         ? EVP_KEYMGMT_gettable_params(pkey->keymgmt)
2174         : NULL;
2175 }
2176
2177 int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[])
2178 {
2179     if (pkey != NULL) {
2180         if (evp_pkey_is_provided(pkey))
2181             return evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params);
2182 #ifndef FIPS_MODULE
2183         else if (evp_pkey_is_legacy(pkey))
2184             return evp_pkey_get_params_to_ctrl(pkey, params);
2185 #endif
2186     }
2187     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
2188     return 0;
2189 }
2190
2191 #ifndef FIPS_MODULE
2192 int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey)
2193 {
2194     char name[80];
2195     size_t name_len;
2196
2197     if (pkey == NULL)
2198         return 0;
2199
2200     if (pkey->keymgmt == NULL
2201             || pkey->keydata == NULL) {
2202 #ifndef OPENSSL_NO_EC
2203         /* Might work through the legacy route */
2204         EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2205
2206         if (ec == NULL)
2207             return 0;
2208
2209         return EC_KEY_get_conv_form(ec);
2210 #else
2211         return 0;
2212 #endif
2213     }
2214
2215     if (!EVP_PKEY_get_utf8_string_param(pkey,
2216                                         OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
2217                                         name, sizeof(name), &name_len))
2218         return 0;
2219
2220     if (strcmp(name, "uncompressed") == 0)
2221         return POINT_CONVERSION_UNCOMPRESSED;
2222
2223     if (strcmp(name, "compressed") == 0)
2224         return POINT_CONVERSION_COMPRESSED;
2225
2226     if (strcmp(name, "hybrid") == 0)
2227         return POINT_CONVERSION_HYBRID;
2228
2229     return 0;
2230 }
2231
2232 int EVP_PKEY_get_field_type(const EVP_PKEY *pkey)
2233 {
2234     char fstr[80];
2235     size_t fstrlen;
2236
2237     if (pkey == NULL)
2238         return 0;
2239
2240     if (pkey->keymgmt == NULL
2241             || pkey->keydata == NULL) {
2242 #ifndef OPENSSL_NO_EC
2243         /* Might work through the legacy route */
2244         EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2245         const EC_GROUP *grp;
2246
2247         if (ec == NULL)
2248             return 0;
2249         grp = EC_KEY_get0_group(ec);
2250         if (grp == NULL)
2251             return 0;
2252
2253         return EC_GROUP_get_field_type(grp);
2254 #else
2255         return 0;
2256 #endif
2257     }
2258
2259     if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_FIELD_TYPE,
2260                                         fstr, sizeof(fstr), &fstrlen))
2261         return 0;
2262
2263     if (strcmp(fstr, SN_X9_62_prime_field) == 0)
2264         return NID_X9_62_prime_field;
2265     else if (strcmp(fstr, SN_X9_62_characteristic_two_field))
2266         return NID_X9_62_characteristic_two_field;
2267
2268     return 0;
2269 }
2270 #endif