EVP: add EVP_PKEY_is_a() and EVP_PKEY_can_sign()
[openssl.git] / crypto / evp / p_lib.c
1 /*
2  * Copyright 1995-2018 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 <openssl/bn.h>
20 #include <openssl/err.h>
21 #include <openssl/objects.h>
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 #include <openssl/rsa.h>
25 #include <openssl/dsa.h>
26 #include <openssl/dh.h>
27 #include <openssl/ec.h>
28 #include <openssl/cmac.h>
29 #include <openssl/engine.h>
30 #include <openssl/params.h>
31 #include <openssl/serializer.h>
32 #include <openssl/core_names.h>
33
34 #include "crypto/asn1.h"
35 #include "crypto/evp.h"
36 #include "internal/provider.h"
37 #include "evp_local.h"
38
39 #include "crypto/ec.h"
40
41 /* TODO remove this when the EVP_PKEY_is_a() #legacy support hack is removed */
42 #include "e_os.h"                /* strcasecmp on Windows */
43
44 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
45                          int len, EVP_KEYMGMT *keymgmt);
46 static void evp_pkey_free_it(EVP_PKEY *key);
47
48 #ifndef FIPS_MODE
49
50 /* The type of parameters selected in key parameter functions */
51 # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
52
53 int EVP_PKEY_bits(const EVP_PKEY *pkey)
54 {
55     if (pkey != NULL) {
56         if (pkey->ameth == NULL)
57             return pkey->cache.bits;
58         else if (pkey->ameth->pkey_bits)
59             return pkey->ameth->pkey_bits(pkey);
60     }
61     return 0;
62 }
63
64 int EVP_PKEY_security_bits(const EVP_PKEY *pkey)
65 {
66     if (pkey == NULL)
67         return 0;
68     if (pkey->ameth == NULL)
69         return pkey->cache.security_bits;
70     if (pkey->ameth->pkey_security_bits == NULL)
71         return -2;
72     return pkey->ameth->pkey_security_bits(pkey);
73 }
74
75 int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
76 {
77 # ifndef OPENSSL_NO_DSA
78     if (pkey->type == EVP_PKEY_DSA) {
79         int ret = pkey->save_parameters;
80
81         if (mode >= 0)
82             pkey->save_parameters = mode;
83         return ret;
84     }
85 # endif
86 # ifndef OPENSSL_NO_EC
87     if (pkey->type == EVP_PKEY_EC) {
88         int ret = pkey->save_parameters;
89
90         if (mode >= 0)
91             pkey->save_parameters = mode;
92         return ret;
93     }
94 # endif
95     return 0;
96 }
97
98 int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
99 {
100     /*
101      * TODO: clean up legacy stuff from this function when legacy support
102      * is gone.
103      */
104
105     /*
106      * If |to| is a legacy key and |from| isn't, we must downgrade |from|.
107      * If that fails, this function fails.
108      */
109     if (to->type != EVP_PKEY_NONE && from->keymgmt != NULL)
110         if (!evp_pkey_downgrade((EVP_PKEY *)from))
111             return 0;
112
113     /*
114      * Make sure |to| is typed.  Content is less important at this early
115      * stage.
116      *
117      * 1.  If |to| is untyped, assign |from|'s key type to it.
118      * 2.  If |to| contains a legacy key, compare its |type| to |from|'s.
119      *     (|from| was already downgraded above)
120      *
121      * If |to| is a provided key, there's nothing more to do here, functions
122      * like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called
123      * further down help us find out if they are the same or not.
124      */
125     if (to->type == EVP_PKEY_NONE && to->keymgmt == NULL) {
126         if (from->type != EVP_PKEY_NONE) {
127             if (EVP_PKEY_set_type(to, from->type) == 0)
128                 return 0;
129         } else {
130             if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0)
131                 return 0;
132         }
133     } else if (to->type != EVP_PKEY_NONE) {
134         if (to->type != from->type) {
135             EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_KEY_TYPES);
136             goto err;
137         }
138     }
139
140     if (EVP_PKEY_missing_parameters(from)) {
141         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_MISSING_PARAMETERS);
142         goto err;
143     }
144
145     if (!EVP_PKEY_missing_parameters(to)) {
146         if (EVP_PKEY_cmp_parameters(to, from) == 1)
147             return 1;
148         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_PARAMETERS);
149         return 0;
150     }
151
152     /* For purely provided keys, we just call the keymgmt utility */
153     if (to->keymgmt != NULL && from->keymgmt != NULL)
154         return evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS);
155
156     /*
157      * If |to| is provided, we know that |from| is legacy at this point.
158      * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_copy()
159      * to copy the appropriate data to |to|'s keydata.
160      */
161     if (to->keymgmt != NULL) {
162         EVP_KEYMGMT *to_keymgmt = to->keymgmt;
163         void *from_keydata =
164             evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt,
165                                         NULL);
166
167         /*
168          * If we get a NULL, it could be an internal error, or it could be
169          * that there's a key mismatch.  We're pretending the latter...
170          */
171         if (from_keydata == NULL) {
172             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
173             return 0;
174         }
175         return evp_keymgmt_copy(to->keymgmt, to->keydata, from_keydata,
176                                 SELECT_PARAMETERS);
177     }
178
179     /* Both keys are legacy */
180     if (from->ameth != NULL && from->ameth->param_copy != NULL)
181         return from->ameth->param_copy(to, from);
182  err:
183     return 0;
184 }
185
186 int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
187 {
188     if (pkey != NULL) {
189         if (pkey->keymgmt != NULL)
190             return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS);
191         else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL)
192             return pkey->ameth->param_missing(pkey);
193     }
194     return 0;
195 }
196
197 /*
198  * This function is called for any mixture of keys except pure legacy pair.
199  * TODO When legacy keys are gone, we replace a call to this functions with
200  * a call to evp_keymgmt_util_match().
201  */
202 static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b,
203                             int selection)
204 {
205     EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
206     void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL;
207
208     /* If none of them are provided, this function shouldn't have been called */
209     if (!ossl_assert(a->keymgmt != NULL || b->keymgmt != NULL))
210         return -2;
211
212     /* For purely provided keys, we just call the keymgmt utility */
213     if (a->keymgmt != NULL && b->keymgmt != NULL)
214         return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection);
215
216     /*
217      * At this point, one of them is provided, the other not.  This allows
218      * us to compare types using legacy NIDs.
219      */
220     if ((a->type != EVP_PKEY_NONE
221          && !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type)))
222         || (b->type != EVP_PKEY_NONE
223             && !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type))))
224         return -1;               /* not the same key type */
225
226     /*
227      * We've determined that they both are the same keytype, so the next
228      * step is to do a bit of cross export to ensure we have keydata for
229      * both keys in the same keymgmt.
230      */
231     keymgmt1 = a->keymgmt;
232     keydata1 = a->keydata;
233     keymgmt2 = b->keymgmt;
234     keydata2 = b->keydata;
235
236     if (keymgmt2 != NULL && keymgmt2->match != NULL) {
237         tmp_keydata =
238             evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL);
239         if (tmp_keydata != NULL) {
240             keymgmt1 = keymgmt2;
241             keydata1 = tmp_keydata;
242         }
243     }
244     if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) {
245         tmp_keydata =
246             evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL);
247         if (tmp_keydata != NULL) {
248             keymgmt2 = keymgmt1;
249             keydata2 = tmp_keydata;
250         }
251     }
252
253     /* If we still don't have matching keymgmt implementations, we give up */
254     if (keymgmt1 != keymgmt2)
255         return -2;
256
257     return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
258 }
259
260 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
261 {
262     /*
263      * TODO: clean up legacy stuff from this function when legacy support
264      * is gone.
265      */
266
267     if (a->keymgmt != NULL || b->keymgmt != NULL)
268         return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS);
269
270     /* All legacy keys */
271     if (a->type != b->type)
272         return -1;
273     if (a->ameth != NULL && a->ameth->param_cmp != NULL)
274         return a->ameth->param_cmp(a, b);
275     return -2;
276 }
277
278 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
279 {
280     /*
281      * TODO: clean up legacy stuff from this function when legacy support
282      * is gone.
283      */
284
285     if (a->keymgmt != NULL || b->keymgmt != NULL)
286         return evp_pkey_cmp_any(a, b, (SELECT_PARAMETERS
287                                        | OSSL_KEYMGMT_SELECT_PUBLIC_KEY));
288
289     /* All legacy keys */
290     if (a->type != b->type)
291         return -1;
292
293     if (a->ameth != NULL) {
294         int ret;
295         /* Compare parameters if the algorithm has them */
296         if (a->ameth->param_cmp != NULL) {
297             ret = a->ameth->param_cmp(a, b);
298             if (ret <= 0)
299                 return ret;
300         }
301
302         if (a->ameth->pub_cmp != NULL)
303             return a->ameth->pub_cmp(a, b);
304     }
305
306     return -2;
307 }
308
309 EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
310                                        const unsigned char *priv,
311                                        size_t len)
312 {
313     EVP_PKEY *ret = EVP_PKEY_new();
314
315     if (ret == NULL
316         || !pkey_set_type(ret, e, type, NULL, -1, NULL)) {
317         /* EVPerr already called */
318         goto err;
319     }
320
321     if (ret->ameth->set_priv_key == NULL) {
322         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY,
323                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
324         goto err;
325     }
326
327     if (!ret->ameth->set_priv_key(ret, priv, len)) {
328         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY, EVP_R_KEY_SETUP_FAILED);
329         goto err;
330     }
331
332     return ret;
333
334  err:
335     EVP_PKEY_free(ret);
336     return NULL;
337 }
338
339 EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
340                                       const unsigned char *pub,
341                                       size_t len)
342 {
343     EVP_PKEY *ret = EVP_PKEY_new();
344
345     if (ret == NULL
346         || !pkey_set_type(ret, e, type, NULL, -1, NULL)) {
347         /* EVPerr already called */
348         goto err;
349     }
350
351     if (ret->ameth->set_pub_key == NULL) {
352         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY,
353                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
354         goto err;
355     }
356
357     if (!ret->ameth->set_pub_key(ret, pub, len)) {
358         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY, EVP_R_KEY_SETUP_FAILED);
359         goto err;
360     }
361
362     return ret;
363
364  err:
365     EVP_PKEY_free(ret);
366     return NULL;
367 }
368
369 int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
370                                  size_t *len)
371 {
372     /* TODO(3.0) Do we need to do anything about provider side keys? */
373      if (pkey->ameth->get_priv_key == NULL) {
374         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY,
375                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
376         return 0;
377     }
378
379     if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
380         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY, EVP_R_GET_RAW_KEY_FAILED);
381         return 0;
382     }
383
384     return 1;
385 }
386
387 int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
388                                 size_t *len)
389 {
390     /* TODO(3.0) Do we need to do anything about provider side keys? */
391      if (pkey->ameth->get_pub_key == NULL) {
392         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY,
393                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
394         return 0;
395     }
396
397     if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
398         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY, EVP_R_GET_RAW_KEY_FAILED);
399         return 0;
400     }
401
402     return 1;
403 }
404
405 EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
406                                 size_t len, const EVP_CIPHER *cipher)
407 {
408 # ifndef OPENSSL_NO_CMAC
409 #  ifndef OPENSSL_NO_ENGINE
410     const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
411 #  endif
412     const char *cipher_name = EVP_CIPHER_name(cipher);
413     const OSSL_PROVIDER *prov = EVP_CIPHER_provider(cipher);
414     OPENSSL_CTX *libctx =
415         prov == NULL ? NULL : ossl_provider_library_context(prov);
416     EVP_PKEY *ret = EVP_PKEY_new();
417     EVP_MAC *cmac = EVP_MAC_fetch(libctx, OSSL_MAC_NAME_CMAC, NULL);
418     EVP_MAC_CTX *cmctx = cmac != NULL ? EVP_MAC_CTX_new(cmac) : NULL;
419     OSSL_PARAM params[4];
420     size_t paramsn = 0;
421
422     if (ret == NULL
423         || cmctx == NULL
424         || !pkey_set_type(ret, e, EVP_PKEY_CMAC, NULL, -1, NULL)) {
425         /* EVPerr already called */
426         goto err;
427     }
428
429 #  ifndef OPENSSL_NO_ENGINE
430     if (engine_id != NULL)
431         params[paramsn++] =
432             OSSL_PARAM_construct_utf8_string("engine", (char *)engine_id, 0);
433 #  endif
434
435     params[paramsn++] =
436         OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
437                                          (char *)cipher_name, 0);
438     params[paramsn++] =
439         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
440                                           (char *)priv, len);
441     params[paramsn] = OSSL_PARAM_construct_end();
442
443     if (!EVP_MAC_CTX_set_params(cmctx, params)) {
444         EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY, EVP_R_KEY_SETUP_FAILED);
445         goto err;
446     }
447
448     ret->pkey.ptr = cmctx;
449     return ret;
450
451  err:
452     EVP_PKEY_free(ret);
453     EVP_MAC_CTX_free(cmctx);
454     EVP_MAC_free(cmac);
455     return NULL;
456 # else
457     EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY,
458            EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
459     return NULL;
460 # endif
461 }
462
463 int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
464 {
465     return pkey_set_type(pkey, NULL, type, NULL, -1, NULL);
466 }
467
468 int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
469 {
470     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL);
471 }
472
473 int EVP_PKEY_set_alias_type(EVP_PKEY *pkey, int type)
474 {
475     if (pkey->type == type) {
476         return 1; /* it already is that type */
477     }
478
479     /*
480      * The application is requesting to alias this to a different pkey type,
481      * but not one that resolves to the base type.
482      */
483     if (EVP_PKEY_type(type) != EVP_PKEY_base_id(pkey)) {
484         EVPerr(EVP_F_EVP_PKEY_SET_ALIAS_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
485         return 0;
486     }
487
488     pkey->type = type;
489     return 1;
490 }
491
492 # ifndef OPENSSL_NO_ENGINE
493 int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
494 {
495     if (e != NULL) {
496         if (!ENGINE_init(e)) {
497             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, ERR_R_ENGINE_LIB);
498             return 0;
499         }
500         if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
501             ENGINE_finish(e);
502             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, EVP_R_UNSUPPORTED_ALGORITHM);
503             return 0;
504         }
505     }
506     ENGINE_finish(pkey->pmeth_engine);
507     pkey->pmeth_engine = e;
508     return 1;
509 }
510
511 ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
512 {
513     return pkey->engine;
514 }
515 # endif
516 int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
517 {
518     int alias = type;
519
520 #ifndef OPENSSL_NO_EC
521     if (EVP_PKEY_type(type) == EVP_PKEY_EC) {
522         const EC_GROUP *group = EC_KEY_get0_group(key);
523
524         if (group != NULL && EC_GROUP_get_curve_name(group) == NID_sm2)
525             alias = EVP_PKEY_SM2;
526     }
527 #endif
528
529     if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
530         return 0;
531     if (!EVP_PKEY_set_alias_type(pkey, alias))
532         return 0;
533     pkey->pkey.ptr = key;
534     return (key != NULL);
535 }
536
537 void *EVP_PKEY_get0(const EVP_PKEY *pkey)
538 {
539     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
540         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
541         return NULL;
542     }
543     return pkey->pkey.ptr;
544 }
545
546 const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
547 {
548     ASN1_OCTET_STRING *os = NULL;
549     if (pkey->type != EVP_PKEY_HMAC) {
550         EVPerr(EVP_F_EVP_PKEY_GET0_HMAC, EVP_R_EXPECTING_AN_HMAC_KEY);
551         return NULL;
552     }
553     os = EVP_PKEY_get0(pkey);
554     *len = os->length;
555     return os->data;
556 }
557
558 # ifndef OPENSSL_NO_POLY1305
559 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
560 {
561     ASN1_OCTET_STRING *os = NULL;
562     if (pkey->type != EVP_PKEY_POLY1305) {
563         EVPerr(EVP_F_EVP_PKEY_GET0_POLY1305, EVP_R_EXPECTING_A_POLY1305_KEY);
564         return NULL;
565     }
566     os = EVP_PKEY_get0(pkey);
567     *len = os->length;
568     return os->data;
569 }
570 # endif
571
572 # ifndef OPENSSL_NO_SIPHASH
573 const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
574 {
575     ASN1_OCTET_STRING *os = NULL;
576
577     if (pkey->type != EVP_PKEY_SIPHASH) {
578         EVPerr(EVP_F_EVP_PKEY_GET0_SIPHASH, EVP_R_EXPECTING_A_SIPHASH_KEY);
579         return NULL;
580     }
581     os = EVP_PKEY_get0(pkey);
582     *len = os->length;
583     return os->data;
584 }
585 # endif
586
587 # ifndef OPENSSL_NO_RSA
588 int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key)
589 {
590     int ret = EVP_PKEY_assign_RSA(pkey, key);
591     if (ret)
592         RSA_up_ref(key);
593     return ret;
594 }
595
596 RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey)
597 {
598     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
599         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
600         return NULL;
601     }
602     if (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_RSA_PSS) {
603         EVPerr(EVP_F_EVP_PKEY_GET0_RSA, EVP_R_EXPECTING_AN_RSA_KEY);
604         return NULL;
605     }
606     return pkey->pkey.rsa;
607 }
608
609 RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey)
610 {
611     RSA *ret = EVP_PKEY_get0_RSA(pkey);
612     if (ret != NULL)
613         RSA_up_ref(ret);
614     return ret;
615 }
616 # endif
617
618 # ifndef OPENSSL_NO_DSA
619 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
620 {
621     int ret = EVP_PKEY_assign_DSA(pkey, key);
622     if (ret)
623         DSA_up_ref(key);
624     return ret;
625 }
626
627 DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
628 {
629     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
630         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
631         return NULL;
632     }
633     if (pkey->type != EVP_PKEY_DSA) {
634         EVPerr(EVP_F_EVP_PKEY_GET0_DSA, EVP_R_EXPECTING_A_DSA_KEY);
635         return NULL;
636     }
637     return pkey->pkey.dsa;
638 }
639
640 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
641 {
642     DSA *ret = EVP_PKEY_get0_DSA(pkey);
643     if (ret != NULL)
644         DSA_up_ref(ret);
645     return ret;
646 }
647 # endif
648
649 # ifndef OPENSSL_NO_EC
650
651 int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key)
652 {
653     int ret = EVP_PKEY_assign_EC_KEY(pkey, key);
654     if (ret)
655         EC_KEY_up_ref(key);
656     return ret;
657 }
658
659 EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey)
660 {
661     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
662         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
663         return NULL;
664     }
665     if (EVP_PKEY_base_id(pkey) != EVP_PKEY_EC) {
666         EVPerr(EVP_F_EVP_PKEY_GET0_EC_KEY, EVP_R_EXPECTING_A_EC_KEY);
667         return NULL;
668     }
669     return pkey->pkey.ec;
670 }
671
672 EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey)
673 {
674     EC_KEY *ret = EVP_PKEY_get0_EC_KEY(pkey);
675     if (ret != NULL)
676         EC_KEY_up_ref(ret);
677     return ret;
678 }
679 # endif
680
681 # ifndef OPENSSL_NO_DH
682
683 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key)
684 {
685     int type = DH_get0_q(key) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
686     int ret = EVP_PKEY_assign(pkey, type, key);
687
688     if (ret)
689         DH_up_ref(key);
690     return ret;
691 }
692
693 DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
694 {
695     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
696         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
697         return NULL;
698     }
699     if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
700         EVPerr(EVP_F_EVP_PKEY_GET0_DH, EVP_R_EXPECTING_A_DH_KEY);
701         return NULL;
702     }
703     return pkey->pkey.dh;
704 }
705
706 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
707 {
708     DH *ret = EVP_PKEY_get0_DH(pkey);
709     if (ret != NULL)
710         DH_up_ref(ret);
711     return ret;
712 }
713 # endif
714
715 int EVP_PKEY_type(int type)
716 {
717     int ret;
718     const EVP_PKEY_ASN1_METHOD *ameth;
719     ENGINE *e;
720     ameth = EVP_PKEY_asn1_find(&e, type);
721     if (ameth)
722         ret = ameth->pkey_id;
723     else
724         ret = NID_undef;
725 # ifndef OPENSSL_NO_ENGINE
726     ENGINE_finish(e);
727 # endif
728     return ret;
729 }
730
731 int EVP_PKEY_id(const EVP_PKEY *pkey)
732 {
733     return pkey->type;
734 }
735
736 int EVP_PKEY_base_id(const EVP_PKEY *pkey)
737 {
738     return EVP_PKEY_type(pkey->type);
739 }
740
741 int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name)
742 {
743 #ifndef FIPS_MODE
744     if (pkey->keymgmt == NULL) {
745         /*
746          * These hard coded cases are pure hackery to get around the fact
747          * that names in crypto/objects/objects.txt are a mess.  There is
748          * no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's
749          * fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1,
750          * the NID of which is used for EVP_PKEY_RSA.  Strangely enough,
751          * "DSA" is accurate...  but still, better be safe and hard-code
752          * names that we know.
753          * TODO Clean this away along with all other #legacy support.
754          */
755         int type;
756
757         if (strcasecmp(name, "RSA") == 0)
758             type = EVP_PKEY_RSA;
759 #ifndef OPENSSL_NO_EC
760         else if (strcasecmp(name, "EC") == 0)
761             type = EVP_PKEY_EC;
762 #endif
763 #ifndef OPENSSL_NO_DSA
764         else if (strcasecmp(name, "DSA") == 0)
765             type = EVP_PKEY_DSA;
766 #endif
767         else
768             type = EVP_PKEY_type(OBJ_sn2nid(name));
769         return EVP_PKEY_type(pkey->type) == type;
770     }
771 #endif
772     return EVP_KEYMGMT_is_a(pkey->keymgmt, name);
773 }
774
775 int EVP_PKEY_can_sign(const EVP_PKEY *pkey)
776 {
777     if (pkey->keymgmt == NULL) {
778         switch (EVP_PKEY_base_id(pkey)) {
779         case EVP_PKEY_RSA:
780             return 1;
781 #ifndef OPENSSL_NO_DSA
782         case EVP_PKEY_DSA:
783             return 1;
784 #endif
785 #ifndef OPENSSL_NO_EC
786         case EVP_PKEY_ED25519:
787         case EVP_PKEY_ED448:
788             return 1;
789         case EVP_PKEY_EC:        /* Including SM2 */
790             return EC_KEY_can_sign(pkey->pkey.ec);
791 #endif
792         default:
793             break;
794         }
795     } else {
796         const OSSL_PROVIDER *prov = EVP_KEYMGMT_provider(pkey->keymgmt);
797         OPENSSL_CTX *libctx = ossl_provider_library_context(prov);
798         const char *supported_sig =
799             pkey->keymgmt->query_operation_name != NULL
800             ? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE)
801             : evp_first_name(prov, pkey->keymgmt->name_id);
802         EVP_SIGNATURE *signature = NULL;
803
804         signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL);
805         if (signature != NULL) {
806             EVP_SIGNATURE_free(signature);
807             return 1;
808         }
809     }
810     return 0;
811 }
812
813 static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
814 {
815     BIO_set_indent(*out, saved_indent);
816     if (pop_f_prefix) {
817         BIO *next = BIO_pop(*out);
818
819         BIO_free(*out);
820         *out = next;
821     }
822     return 1;
823 }
824
825 static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
826                             long indent)
827 {
828     *pop_f_prefix = 0;
829     *saved_indent = 0;
830     if (indent > 0) {
831         long i = BIO_get_indent(*out);
832
833         *saved_indent =  (i < 0 ? 0 : i);
834         if (BIO_set_indent(*out, indent) <= 0) {
835             if ((*out = BIO_push(BIO_new(BIO_f_prefix()), *out)) == NULL)
836                 return 0;
837             *pop_f_prefix = 1;
838         }
839         if (BIO_set_indent(*out, indent) <= 0) {
840             print_reset_indent(out, *pop_f_prefix, *saved_indent);
841             return 0;
842         }
843     }
844     return 1;
845 }
846
847 static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
848                      const char *kstr)
849 {
850     return BIO_indent(out, indent, 128)
851         && BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
852                       kstr, OBJ_nid2ln(pkey->type)) > 0;
853 }
854
855 static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
856                       const char *propquery /* For provided serialization */,
857                       int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
858                                           int indent, ASN1_PCTX *pctx),
859                       ASN1_PCTX *legacy_pctx /* For legacy print */)
860 {
861     int pop_f_prefix;
862     long saved_indent;
863     OSSL_SERIALIZER_CTX *ctx = NULL;
864     int ret = -2;                /* default to unsupported */
865
866     if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
867         return 0;
868
869     ctx = OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(pkey, propquery);
870     if (OSSL_SERIALIZER_CTX_get_serializer(ctx) != NULL)
871         ret = OSSL_SERIALIZER_to_bio(ctx, out);
872     OSSL_SERIALIZER_CTX_free(ctx);
873
874     if (ret != -2)
875         goto end;
876
877     /* legacy fallback */
878     if (legacy_print != NULL)
879         ret = legacy_print(out, pkey, 0, legacy_pctx);
880     else
881         ret = unsup_alg(out, pkey, 0, "Public Key");
882
883  end:
884     print_reset_indent(&out, pop_f_prefix, saved_indent);
885     return ret;
886 }
887
888 int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
889                           int indent, ASN1_PCTX *pctx)
890 {
891     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PUBKEY_TO_TEXT_PQ,
892                       (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
893                       pctx);
894 }
895
896 int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
897                            int indent, ASN1_PCTX *pctx)
898 {
899     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PrivateKey_TO_TEXT_PQ,
900                       (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL),
901                       pctx);
902 }
903
904 int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
905                           int indent, ASN1_PCTX *pctx)
906 {
907     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_Parameters_TO_TEXT_PQ,
908                       (pkey->ameth != NULL ? pkey->ameth->param_print : NULL),
909                       pctx);
910 }
911
912 static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op,
913                                      int arg1, void *arg2)
914 {
915     if (pkey->keymgmt == NULL)
916         return 0;
917     switch (op) {
918     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
919         {
920             char mdname[80] = "";
921             int nid;
922             int rv = EVP_PKEY_get_default_digest_name(pkey, mdname,
923                                                       sizeof(mdname));
924
925             if (rv <= 0)
926                 return rv;
927             nid = OBJ_sn2nid(mdname);
928             if (nid == NID_undef)
929                 nid = OBJ_ln2nid(mdname);
930             if (nid == NID_undef)
931                 return 0;
932             *(int *)arg2 = nid;
933             return 1;
934         }
935     default:
936         return -2;
937     }
938 }
939
940 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
941 {
942     if (pkey->ameth == NULL)
943         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
944     if (pkey->ameth->pkey_ctrl == NULL)
945         return -2;
946     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
947 }
948
949 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
950 {
951     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
952 }
953
954 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
955                                      char *mdname, size_t mdname_sz)
956 {
957     if (pkey->ameth == NULL) {
958         OSSL_PARAM params[3];
959         char mddefault[100] = "";
960         char mdmandatory[100] = "";
961
962         params[0] =
963             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
964                                              mddefault, sizeof(mddefault));
965         params[1] =
966             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
967                                              mdmandatory,
968                                              sizeof(mdmandatory));
969         params[2] = OSSL_PARAM_construct_end();
970         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
971             return 0;
972         if (mdmandatory[0] != '\0') {
973             OPENSSL_strlcpy(mdname, mdmandatory, mdname_sz);
974             return 2;
975         }
976         OPENSSL_strlcpy(mdname, mddefault, mdname_sz);
977         return 1;
978     }
979
980     {
981         int nid = NID_undef;
982         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
983         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
984
985         if (rv > 0)
986             OPENSSL_strlcpy(mdname, name, mdname_sz);
987         return rv;
988     }
989 }
990
991 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
992 {
993     int rv, default_nid;
994
995     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
996     if (rv == -2) {
997         /*
998          * If there is a mandatory default digest and this isn't it, then
999          * the answer is 'no'.
1000          */
1001         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
1002         if (rv == 2)
1003             return (nid == default_nid);
1004         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
1005         if (rv == 0)
1006             return -1;
1007     }
1008     return rv;
1009 }
1010
1011 int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey,
1012                                const unsigned char *pt, size_t ptlen)
1013 {
1014     if (ptlen > INT_MAX)
1015         return 0;
1016     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, ptlen,
1017                            (void *)pt) <= 0)
1018         return 0;
1019     return 1;
1020 }
1021
1022 size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *pkey, unsigned char **ppt)
1023 {
1024     int rv;
1025     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppt);
1026     if (rv <= 0)
1027         return 0;
1028     return rv;
1029 }
1030
1031 #endif /* FIPS_MODE */
1032
1033 /*- All methods below can also be used in FIPS_MODE */
1034
1035 EVP_PKEY *EVP_PKEY_new(void)
1036 {
1037     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
1038
1039     if (ret == NULL) {
1040         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
1041         return NULL;
1042     }
1043     ret->type = EVP_PKEY_NONE;
1044     ret->save_type = EVP_PKEY_NONE;
1045     ret->references = 1;
1046     ret->save_parameters = 1;
1047     ret->lock = CRYPTO_THREAD_lock_new();
1048     if (ret->lock == NULL) {
1049         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
1050         OPENSSL_free(ret);
1051         return NULL;
1052     }
1053     return ret;
1054 }
1055
1056 /*
1057  * Setup a public key management method.
1058  *
1059  * For legacy keys, either |type| or |str| is expected to have the type
1060  * information.  In this case, the setup consists of finding an ASN1 method
1061  * and potentially an ENGINE, and setting those fields in |pkey|.
1062  *
1063  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
1064  * case, the setup consists of setting the |keymgmt| field in |pkey|.
1065  *
1066  * If pkey is NULL just return 1 or 0 if the key management method exists.
1067  */
1068
1069 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
1070                          int len, EVP_KEYMGMT *keymgmt)
1071 {
1072 #ifndef FIPS_MODE
1073     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
1074     ENGINE **eptr = (e == NULL) ? &e :  NULL;
1075 #endif
1076
1077     /*
1078      * The setups can't set both legacy and provider side methods.
1079      * It is forbidden
1080      */
1081     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
1082         || !ossl_assert(e == NULL || keymgmt == NULL)) {
1083         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1084         return 0;
1085     }
1086
1087     if (pkey != NULL) {
1088         int free_it = 0;
1089
1090 #ifndef FIPS_MODE
1091         free_it = free_it || pkey->pkey.ptr != NULL;
1092 #endif
1093         free_it = free_it || pkey->keydata != NULL;
1094         if (free_it)
1095             evp_pkey_free_it(pkey);
1096 #ifndef FIPS_MODE
1097         /*
1098          * If key type matches and a method exists then this lookup has
1099          * succeeded once so just indicate success.
1100          */
1101         if (pkey->type != EVP_PKEY_NONE
1102             && type == pkey->save_type
1103             && pkey->ameth != NULL)
1104             return 1;
1105 # ifndef OPENSSL_NO_ENGINE
1106         /* If we have ENGINEs release them */
1107         ENGINE_finish(pkey->engine);
1108         pkey->engine = NULL;
1109         ENGINE_finish(pkey->pmeth_engine);
1110         pkey->pmeth_engine = NULL;
1111 # endif
1112 #endif
1113     }
1114 #ifndef FIPS_MODE
1115     if (str != NULL)
1116         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1117     else if (type != EVP_PKEY_NONE)
1118         ameth = EVP_PKEY_asn1_find(eptr, type);
1119 # ifndef OPENSSL_NO_ENGINE
1120     if (pkey == NULL && eptr != NULL)
1121         ENGINE_finish(e);
1122 # endif
1123 #endif
1124
1125
1126     {
1127         int check = 1;
1128
1129 #ifndef FIPS_MODE
1130         check = check && ameth == NULL;
1131 #endif
1132         check = check && keymgmt == NULL;
1133         if (check) {
1134             EVPerr(EVP_F_PKEY_SET_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
1135             return 0;
1136         }
1137     }
1138     if (pkey != NULL) {
1139         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1140             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1141             return 0;
1142         }
1143
1144         pkey->keymgmt = keymgmt;
1145
1146         pkey->save_type = type;
1147         pkey->type = type;
1148
1149 #ifndef FIPS_MODE
1150         /*
1151          * If the internal "origin" key is provider side, don't save |ameth|.
1152          * The main reason is that |ameth| is one factor to detect that the
1153          * internal "origin" key is a legacy one.
1154          */
1155         if (keymgmt == NULL)
1156             pkey->ameth = ameth;
1157         pkey->engine = e;
1158
1159         /*
1160          * The EVP_PKEY_ASN1_METHOD |pkey_id| serves different purposes,
1161          * depending on if we're setting this key to contain a legacy or
1162          * a provider side "origin" key.  For a legacy key, we assign it
1163          * to the |type| field, but for a provider side key, we assign it
1164          * to the |save_type| field, because |type| is supposed to be set
1165          * to EVP_PKEY_NONE in that case.
1166          */
1167         if (keymgmt != NULL)
1168             pkey->save_type = ameth->pkey_id;
1169         else if (pkey->ameth != NULL)
1170             pkey->type = ameth->pkey_id;
1171 #endif
1172     }
1173     return 1;
1174 }
1175
1176 #ifndef FIPS_MODE
1177 static void find_ameth(const char *name, void *data)
1178 {
1179     const char **str = data;
1180
1181     /*
1182      * The error messages from pkey_set_type() are uninteresting here,
1183      * and misleading.
1184      */
1185     ERR_set_mark();
1186
1187     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1188                       NULL)) {
1189         if (str[0] == NULL)
1190             str[0] = name;
1191         else if (str[1] == NULL)
1192             str[1] = name;
1193     }
1194
1195     ERR_pop_to_mark();
1196 }
1197 #endif
1198
1199 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1200 {
1201 #ifndef FIPS_MODE
1202 # define EVP_PKEY_TYPE_STR str[0]
1203 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1204     /*
1205      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1206      * Ideally, only one should be found.  If two (or more) are found, the
1207      * match is ambiguous.  This should never happen, but...
1208      */
1209     const char *str[2] = { NULL, NULL };
1210
1211     EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str);
1212     if (str[1] != NULL) {
1213         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1214         return 0;
1215     }
1216 #else
1217 # define EVP_PKEY_TYPE_STR NULL
1218 # define EVP_PKEY_TYPE_STRLEN -1
1219 #endif
1220     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1221                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1222                          keymgmt);
1223
1224 #undef EVP_PKEY_TYPE_STR
1225 #undef EVP_PKEY_TYPE_STRLEN
1226 }
1227
1228 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1229 {
1230     int i;
1231
1232     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
1233         return 0;
1234
1235     REF_PRINT_COUNT("EVP_PKEY", pkey);
1236     REF_ASSERT_ISNT(i < 2);
1237     return ((i > 1) ? 1 : 0);
1238 }
1239
1240 #ifndef FIPS_MODE
1241 void evp_pkey_free_legacy(EVP_PKEY *x)
1242 {
1243     if (x->ameth != NULL) {
1244         if (x->ameth->pkey_free != NULL)
1245             x->ameth->pkey_free(x);
1246         x->pkey.ptr = NULL;
1247     }
1248 # ifndef OPENSSL_NO_ENGINE
1249     ENGINE_finish(x->engine);
1250     x->engine = NULL;
1251     ENGINE_finish(x->pmeth_engine);
1252     x->pmeth_engine = NULL;
1253 # endif
1254     x->type = EVP_PKEY_NONE;
1255 }
1256 #endif  /* FIPS_MODE */
1257
1258 static void evp_pkey_free_it(EVP_PKEY *x)
1259 {
1260     /* internal function; x is never NULL */
1261
1262     evp_keymgmt_util_clear_operation_cache(x);
1263 #ifndef FIPS_MODE
1264     evp_pkey_free_legacy(x);
1265 #endif
1266
1267     if (x->keymgmt != NULL) {
1268         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1269         EVP_KEYMGMT_free(x->keymgmt);
1270         x->keymgmt = NULL;
1271         x->keydata = NULL;
1272     }
1273 }
1274
1275 void EVP_PKEY_free(EVP_PKEY *x)
1276 {
1277     int i;
1278
1279     if (x == NULL)
1280         return;
1281
1282     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
1283     REF_PRINT_COUNT("EVP_PKEY", x);
1284     if (i > 0)
1285         return;
1286     REF_ASSERT_ISNT(i < 0);
1287     evp_pkey_free_it(x);
1288     CRYPTO_THREAD_lock_free(x->lock);
1289 #ifndef FIPS_MODE
1290     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1291 #endif
1292     OPENSSL_free(x);
1293 }
1294
1295 int EVP_PKEY_size(const EVP_PKEY *pkey)
1296 {
1297     int size = 0;
1298
1299     if (pkey != NULL) {
1300         size = pkey->cache.size;
1301 #ifndef FIPS_MODE
1302         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1303             size = pkey->ameth->pkey_size(pkey);
1304 #endif
1305     }
1306     return size;
1307 }
1308
1309 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
1310                                   EVP_KEYMGMT **keymgmt,
1311                                   const char *propquery)
1312 {
1313     EVP_KEYMGMT *allocated_keymgmt = NULL;
1314     EVP_KEYMGMT *tmp_keymgmt = NULL;
1315     void *keydata = NULL;
1316     int check;
1317
1318     if (pk == NULL)
1319         return NULL;
1320
1321     /* No key data => nothing to export */
1322     check = 1;
1323 #ifndef FIPS_MODE
1324     check = check && pk->pkey.ptr == NULL;
1325 #endif
1326     check = check && pk->keydata == NULL;
1327     if (check)
1328         return NULL;
1329
1330 #ifndef FIPS_MODE
1331     if (pk->pkey.ptr != NULL) {
1332         /*
1333          * If the legacy key doesn't have an dirty counter or export function,
1334          * give up
1335          */
1336         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1337             return NULL;
1338     }
1339 #endif
1340
1341     if (keymgmt != NULL) {
1342         tmp_keymgmt = *keymgmt;
1343         *keymgmt = NULL;
1344     }
1345
1346     /*
1347      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1348      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1349      */
1350     if (tmp_keymgmt == NULL) {
1351         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1352
1353         tmp_keymgmt = ctx->keymgmt;
1354         ctx->keymgmt = NULL;
1355         EVP_PKEY_CTX_free(ctx);
1356     }
1357
1358     /* If there's still no keymgmt to be had, give up */
1359     if (tmp_keymgmt == NULL)
1360         goto end;
1361
1362 #ifndef FIPS_MODE
1363     if (pk->pkey.ptr != NULL) {
1364         size_t i = 0;
1365
1366         /*
1367          * If the legacy "origin" hasn't changed since last time, we try
1368          * to find our keymgmt in the operation cache.  If it has changed,
1369          * |i| remains zero, and we will clear the cache further down.
1370          */
1371         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1372             i = evp_keymgmt_util_find_operation_cache_index(pk, tmp_keymgmt);
1373
1374             /*
1375              * If |tmp_keymgmt| is present in the operation cache, it means
1376              * that export doesn't need to be redone.  In that case, we take
1377              * token copies of the cached pointers, to have token success
1378              * values to return.
1379              */
1380             if (i < OSSL_NELEM(pk->operation_cache)
1381                 && pk->operation_cache[i].keymgmt != NULL) {
1382                 keydata = pk->operation_cache[i].keydata;
1383                 goto end;
1384             }
1385         }
1386
1387         /*
1388          * TODO(3.0) Right now, we assume we have ample space.  We will have
1389          * to think about a cache aging scheme, though, if |i| indexes outside
1390          * the array.
1391          */
1392         if (!ossl_assert(i < OSSL_NELEM(pk->operation_cache)))
1393             goto end;
1394
1395         /* Make sure that the keymgmt key type matches the legacy NID */
1396         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1397             goto end;
1398
1399         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1400             goto end;
1401
1402         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt)) {
1403             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1404             keydata = NULL;
1405             goto end;
1406         }
1407
1408         /*
1409          * If the dirty counter changed since last time, then clear the
1410          * operation cache.  In that case, we know that |i| is zero.  Just
1411          * in case this is a re-export, we increment then decrement the
1412          * keymgmt reference counter.
1413          */
1414         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1415             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1416             keydata = NULL;
1417             goto end;
1418         }
1419         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy)
1420             evp_keymgmt_util_clear_operation_cache(pk);
1421         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1422
1423         /* Add the new export to the operation cache */
1424         if (!evp_keymgmt_util_cache_keydata(pk, i, tmp_keymgmt, keydata)) {
1425             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1426             keydata = NULL;
1427             goto end;
1428         }
1429
1430         /* Synchronize the dirty count */
1431         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1432         goto end;
1433     }
1434 #endif  /* FIPS_MODE */
1435
1436     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1437
1438  end:
1439     /*
1440      * If nothing was exported, |tmp_keymgmt| might point at a freed
1441      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1442      * the caller either way in that case.
1443      */
1444     if (keydata == NULL)
1445         tmp_keymgmt = NULL;
1446
1447     if (keymgmt != NULL)
1448         *keymgmt = tmp_keymgmt;
1449
1450     EVP_KEYMGMT_free(allocated_keymgmt);
1451     return keydata;
1452 }
1453
1454 #ifndef FIPS_MODE
1455 int evp_pkey_downgrade(EVP_PKEY *pk)
1456 {
1457     EVP_KEYMGMT *keymgmt = pk->keymgmt;
1458     void *keydata = pk->keydata;
1459     int type = pk->save_type;
1460     const char *keytype = NULL;
1461
1462     /* If this isn't a provider side key, we're done */
1463     if (keymgmt == NULL)
1464         return 1;
1465
1466     /* Get the key type name for error reporting */
1467     if (type != EVP_PKEY_NONE)
1468         keytype = OBJ_nid2sn(type);
1469     else
1470         keytype =
1471             evp_first_name(EVP_KEYMGMT_provider(keymgmt), keymgmt->name_id);
1472
1473     /*
1474      * |save_type| was set when any of the EVP_PKEY_set_type functions
1475      * was called.  It was set to EVP_PKEY_NONE if the key type wasn't
1476      * recognised to be any of the legacy key types, and the downgrade
1477      * isn't possible.
1478      */
1479     if (type == EVP_PKEY_NONE) {
1480         ERR_raise_data(ERR_LIB_EVP, EVP_R_UNKNOWN_KEY_TYPE,
1481                        "key type = %s, can't downgrade", keytype);
1482         return 0;
1483     }
1484
1485     /*
1486      * To be able to downgrade, we steal the provider side "origin" keymgmt
1487      * and keydata.  We've already grabbed the pointers, so all we need to
1488      * do is clear those pointers in |pk| and then call evp_pkey_free_it().
1489      * That way, we can restore |pk| if we need to.
1490      */
1491     pk->keymgmt = NULL;
1492     pk->keydata = NULL;
1493     evp_pkey_free_it(pk);
1494     if (EVP_PKEY_set_type(pk, type)) {
1495         /* If the key is typed but empty, we're done */
1496         if (keydata == NULL)
1497             return 1;
1498
1499         if (pk->ameth->import_from == NULL) {
1500             ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
1501                            "key type = %s", keytype);
1502         } else if (evp_keymgmt_export(keymgmt, keydata,
1503                                       OSSL_KEYMGMT_SELECT_ALL,
1504                                       pk->ameth->import_from, pk)) {
1505             /*
1506              * Save the provider side data in the operation cache, so they'll
1507              * find it again.  evp_pkey_free_it() cleared the cache, so it's
1508              * safe to assume slot zero is free.
1509              * Note that evp_keymgmt_util_cache_keydata() increments keymgmt's
1510              * reference count.
1511              */
1512             evp_keymgmt_util_cache_keydata(pk, 0, keymgmt, keydata);
1513
1514             /* Synchronize the dirty count */
1515             pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1516             return 1;
1517         }
1518
1519         ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
1520                        "key type = %s", keytype);
1521     }
1522
1523     /*
1524      * Something went wrong.  This could for example happen if the keymgmt
1525      * turns out to be an HSM implementation that refuses to let go of some
1526      * of the key data, typically the private bits.  In this case, we restore
1527      * the provider side internal "origin" and leave it at that.
1528      */
1529     if (!ossl_assert(EVP_PKEY_set_type_by_keymgmt(pk, keymgmt))) {
1530         /* This should not be impossible */
1531         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1532         return 0;
1533     }
1534     pk->keydata = keydata;
1535     evp_keymgmt_util_cache_keyinfo(pk);
1536     return 0;     /* No downgrade, but at least the key is restored */
1537 }
1538 #endif  /* FIPS_MODE */
1539
1540 const OSSL_PARAM *EVP_PKEY_gettable_params(EVP_PKEY *pkey)
1541 {
1542     if (pkey == NULL
1543         || pkey->keymgmt == NULL
1544         || pkey->keydata == NULL)
1545         return 0;
1546     return evp_keymgmt_gettable_params(pkey->keymgmt);
1547 }
1548
1549 /*
1550  * For the following methods param->return_size is set to a value
1551  * larger than can be returned by the call to evp_keymgmt_get_params().
1552  * If it is still this value then the parameter was ignored - and in this
1553  * case it returns an error..
1554  */
1555
1556 int EVP_PKEY_get_bn_param(EVP_PKEY *pkey, const char *key_name, BIGNUM **bn)
1557 {
1558     int ret = 0;
1559     OSSL_PARAM params[2];
1560     unsigned char buffer[2048];
1561     /*
1562      * Use -1 as the terminator here instead of sizeof(buffer) + 1 since
1563      * -1 is less likely to be a valid value.
1564      */
1565     const size_t not_set = (size_t)-1;
1566     unsigned char *buf = NULL;
1567     size_t buf_sz = 0;
1568
1569     if (pkey == NULL
1570         || pkey->keymgmt == NULL
1571         || pkey->keydata == NULL
1572         || key_name == NULL
1573         || bn == NULL)
1574         return 0;
1575
1576     memset(buffer, 0, sizeof(buffer));
1577     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
1578     /* If the return_size is still not_set then we know it was not found */
1579     params[0].return_size = not_set;
1580     params[1] = OSSL_PARAM_construct_end();
1581     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)) {
1582         if (params[0].return_size == not_set
1583             || params[0].return_size == 0)
1584             return 0;
1585         buf_sz = params[0].return_size;
1586         /*
1587          * If it failed because the buffer was too small then allocate the
1588          * required buffer size and retry.
1589          */
1590         buf = OPENSSL_zalloc(buf_sz);
1591         if (buf == NULL)
1592             return 0;
1593         params[0].data = buf;
1594         params[0].data_size = buf_sz;
1595
1596         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1597             goto err;
1598     }
1599     /* Fail if the param was not found */
1600     if (params[0].return_size == not_set)
1601         goto err;
1602     ret = OSSL_PARAM_get_BN(params, bn);
1603 err:
1604     OPENSSL_free(buf);
1605     return ret;
1606 }
1607
1608 int EVP_PKEY_get_octet_string_param(EVP_PKEY *pkey, const char *key_name,
1609                                     unsigned char *buf, size_t max_buf_sz,
1610                                     size_t *out_sz)
1611 {
1612     OSSL_PARAM params[2];
1613     const size_t not_set = max_buf_sz + 1;
1614
1615     if (pkey == NULL
1616         || pkey->keymgmt == NULL
1617         || pkey->keydata == NULL
1618         || key_name == NULL)
1619         return 0;
1620
1621     params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
1622     params[0].return_size = not_set;
1623     params[1] = OSSL_PARAM_construct_end();
1624     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1625         return 0;
1626     if (params[0].return_size == not_set)
1627         return 0;
1628     if (out_sz != NULL)
1629         *out_sz = params[0].return_size;
1630     return 1;
1631 }
1632
1633 int EVP_PKEY_get_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
1634                                     char *str, size_t max_buf_sz,
1635                                     size_t *out_sz)
1636 {
1637     OSSL_PARAM params[2];
1638     const size_t not_set = max_buf_sz + 1;
1639
1640     if (pkey == NULL
1641         || pkey->keymgmt == NULL
1642         || pkey->keydata == NULL
1643         || key_name == NULL)
1644         return 0;
1645
1646     params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
1647     params[0].return_size = not_set;
1648     params[1] = OSSL_PARAM_construct_end();
1649     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1650         return 0;
1651     if (params[0].return_size == not_set)
1652         return 0;
1653     if (out_sz != NULL)
1654         *out_sz = params[0].return_size;
1655     return 1;
1656 }
1657
1658 int EVP_PKEY_get_int_param(EVP_PKEY *pkey, const char *key_name, int *out)
1659 {
1660     OSSL_PARAM params[2];
1661     const size_t not_set = sizeof(int) + 1;
1662
1663     if (pkey == NULL
1664         || pkey->keymgmt == NULL
1665         || pkey->keydata == NULL
1666         || key_name == NULL)
1667         return 0;
1668
1669     params[0] = OSSL_PARAM_construct_int(key_name, out);
1670     params[0].return_size = not_set;
1671     params[1] = OSSL_PARAM_construct_end();
1672     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1673         return 0;
1674     if (params[0].return_size == not_set)
1675         return 0;
1676     return 1;
1677 }
1678
1679 int EVP_PKEY_get_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t *out)
1680 {
1681     OSSL_PARAM params[2];
1682     const size_t not_set = sizeof(size_t) + 1;
1683
1684     if (pkey == NULL
1685         || pkey->keymgmt == NULL
1686         || pkey->keydata == NULL
1687         || key_name == NULL)
1688         return 0;
1689
1690     params[0] = OSSL_PARAM_construct_size_t(key_name, out);
1691     params[0].return_size = not_set;
1692     params[1] = OSSL_PARAM_construct_end();
1693     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1694         return 0;
1695     if (params[0].return_size == not_set)
1696         return 0;
1697     return 1;
1698 }