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