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