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