9f04c72330414340be419a7ab24bc50019207d20
[openssl.git] / crypto / evp / p_lib.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * DSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include "internal/refcount.h"
19 #include <openssl/bn.h>
20 #include <openssl/err.h>
21 #include <openssl/objects.h>
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 #include <openssl/rsa.h>
25 #include <openssl/dsa.h>
26 #include <openssl/dh.h>
27 #include <openssl/ec.h>
28 #include <openssl/cmac.h>
29 #include <openssl/engine.h>
30 #include <openssl/params.h>
31 #include <openssl/serializer.h>
32 #include <openssl/core_names.h>
33
34 #include "crypto/asn1.h"
35 #include "crypto/evp.h"
36 #include "internal/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 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
631 {
632     int ret = EVP_PKEY_assign_DSA(pkey, key);
633     if (ret)
634         DSA_up_ref(key);
635     return ret;
636 }
637
638 DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
639 {
640     if (!evp_pkey_downgrade((EVP_PKEY *)pkey)) {
641         ERR_raise(ERR_LIB_EVP, EVP_R_INACCESSIBLE_KEY);
642         return NULL;
643     }
644     if (pkey->type != EVP_PKEY_DSA) {
645         EVPerr(EVP_F_EVP_PKEY_GET0_DSA, EVP_R_EXPECTING_A_DSA_KEY);
646         return NULL;
647     }
648     return pkey->pkey.dsa;
649 }
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
659
660 # ifndef OPENSSL_NO_EC
661
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         OSSL_PARAM params[3];
1012         char mddefault[100] = "";
1013         char mdmandatory[100] = "";
1014
1015         params[0] =
1016             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
1017                                              mddefault, sizeof(mddefault));
1018         params[1] =
1019             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
1020                                              mdmandatory,
1021                                              sizeof(mdmandatory));
1022         params[2] = OSSL_PARAM_construct_end();
1023         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1024             return 0;
1025         if (mdmandatory[0] != '\0') {
1026             OPENSSL_strlcpy(mdname, mdmandatory, mdname_sz);
1027             return 2;
1028         }
1029         OPENSSL_strlcpy(mdname, mddefault, mdname_sz);
1030         return 1;
1031     }
1032
1033     {
1034         int nid = NID_undef;
1035         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
1036         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
1037
1038         if (rv > 0)
1039             OPENSSL_strlcpy(mdname, name, mdname_sz);
1040         return rv;
1041     }
1042 }
1043
1044 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
1045 {
1046     int rv, default_nid;
1047
1048     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
1049     if (rv == -2) {
1050         /*
1051          * If there is a mandatory default digest and this isn't it, then
1052          * the answer is 'no'.
1053          */
1054         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
1055         if (rv == 2)
1056             return (nid == default_nid);
1057         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
1058         if (rv == 0)
1059             return -1;
1060     }
1061     return rv;
1062 }
1063
1064 int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey,
1065                                const unsigned char *pt, size_t ptlen)
1066 {
1067     if (ptlen > INT_MAX)
1068         return 0;
1069     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, ptlen,
1070                            (void *)pt) <= 0)
1071         return 0;
1072     return 1;
1073 }
1074
1075 size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *pkey, unsigned char **ppt)
1076 {
1077     int rv;
1078     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppt);
1079     if (rv <= 0)
1080         return 0;
1081     return rv;
1082 }
1083
1084 #endif /* FIPS_MODE */
1085
1086 /*- All methods below can also be used in FIPS_MODE */
1087
1088 EVP_PKEY *EVP_PKEY_new(void)
1089 {
1090     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
1091
1092     if (ret == NULL) {
1093         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
1094         return NULL;
1095     }
1096     ret->type = EVP_PKEY_NONE;
1097     ret->save_type = EVP_PKEY_NONE;
1098     ret->references = 1;
1099     ret->save_parameters = 1;
1100     ret->lock = CRYPTO_THREAD_lock_new();
1101     if (ret->lock == NULL) {
1102         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
1103         goto err;
1104     }
1105 #ifndef FIPS_MODE
1106     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) {
1107         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
1108         goto err;
1109     }
1110 #endif
1111     return ret;
1112
1113  err:
1114     CRYPTO_THREAD_lock_free(ret->lock);
1115     OPENSSL_free(ret);
1116     return NULL;
1117 }
1118
1119 /*
1120  * Setup a public key management method.
1121  *
1122  * For legacy keys, either |type| or |str| is expected to have the type
1123  * information.  In this case, the setup consists of finding an ASN1 method
1124  * and potentially an ENGINE, and setting those fields in |pkey|.
1125  *
1126  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
1127  * case, the setup consists of setting the |keymgmt| field in |pkey|.
1128  *
1129  * If pkey is NULL just return 1 or 0 if the key management method exists.
1130  */
1131
1132 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
1133                          int len, EVP_KEYMGMT *keymgmt)
1134 {
1135 #ifndef FIPS_MODE
1136     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
1137     ENGINE **eptr = (e == NULL) ? &e :  NULL;
1138 #endif
1139
1140     /*
1141      * The setups can't set both legacy and provider side methods.
1142      * It is forbidden
1143      */
1144     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
1145         || !ossl_assert(e == NULL || keymgmt == NULL)) {
1146         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1147         return 0;
1148     }
1149
1150     if (pkey != NULL) {
1151         int free_it = 0;
1152
1153 #ifndef FIPS_MODE
1154         free_it = free_it || pkey->pkey.ptr != NULL;
1155 #endif
1156         free_it = free_it || pkey->keydata != NULL;
1157         if (free_it)
1158             evp_pkey_free_it(pkey);
1159 #ifndef FIPS_MODE
1160         /*
1161          * If key type matches and a method exists then this lookup has
1162          * succeeded once so just indicate success.
1163          */
1164         if (pkey->type != EVP_PKEY_NONE
1165             && type == pkey->save_type
1166             && pkey->ameth != NULL)
1167             return 1;
1168 # ifndef OPENSSL_NO_ENGINE
1169         /* If we have ENGINEs release them */
1170         ENGINE_finish(pkey->engine);
1171         pkey->engine = NULL;
1172         ENGINE_finish(pkey->pmeth_engine);
1173         pkey->pmeth_engine = NULL;
1174 # endif
1175 #endif
1176     }
1177 #ifndef FIPS_MODE
1178     if (str != NULL)
1179         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1180     else if (type != EVP_PKEY_NONE)
1181         ameth = EVP_PKEY_asn1_find(eptr, type);
1182 # ifndef OPENSSL_NO_ENGINE
1183     if (pkey == NULL && eptr != NULL)
1184         ENGINE_finish(e);
1185 # endif
1186 #endif
1187
1188
1189     {
1190         int check = 1;
1191
1192 #ifndef FIPS_MODE
1193         check = check && ameth == NULL;
1194 #endif
1195         check = check && keymgmt == NULL;
1196         if (check) {
1197             EVPerr(EVP_F_PKEY_SET_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
1198             return 0;
1199         }
1200     }
1201     if (pkey != NULL) {
1202         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1203             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1204             return 0;
1205         }
1206
1207         pkey->keymgmt = keymgmt;
1208
1209         pkey->save_type = type;
1210         pkey->type = type;
1211
1212 #ifndef FIPS_MODE
1213         /*
1214          * If the internal "origin" key is provider side, don't save |ameth|.
1215          * The main reason is that |ameth| is one factor to detect that the
1216          * internal "origin" key is a legacy one.
1217          */
1218         if (keymgmt == NULL)
1219             pkey->ameth = ameth;
1220         pkey->engine = e;
1221
1222         /*
1223          * The EVP_PKEY_ASN1_METHOD |pkey_id| serves different purposes,
1224          * depending on if we're setting this key to contain a legacy or
1225          * a provider side "origin" key.  For a legacy key, we assign it
1226          * to the |type| field, but for a provider side key, we assign it
1227          * to the |save_type| field, because |type| is supposed to be set
1228          * to EVP_PKEY_NONE in that case.
1229          */
1230         if (keymgmt != NULL)
1231             pkey->save_type = ameth->pkey_id;
1232         else if (pkey->ameth != NULL)
1233             pkey->type = ameth->pkey_id;
1234 #endif
1235     }
1236     return 1;
1237 }
1238
1239 #ifndef FIPS_MODE
1240 static void find_ameth(const char *name, void *data)
1241 {
1242     const char **str = data;
1243
1244     /*
1245      * The error messages from pkey_set_type() are uninteresting here,
1246      * and misleading.
1247      */
1248     ERR_set_mark();
1249
1250     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1251                       NULL)) {
1252         if (str[0] == NULL)
1253             str[0] = name;
1254         else if (str[1] == NULL)
1255             str[1] = name;
1256     }
1257
1258     ERR_pop_to_mark();
1259 }
1260 #endif
1261
1262 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1263 {
1264 #ifndef FIPS_MODE
1265 # define EVP_PKEY_TYPE_STR str[0]
1266 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1267     /*
1268      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1269      * Ideally, only one should be found.  If two (or more) are found, the
1270      * match is ambiguous.  This should never happen, but...
1271      */
1272     const char *str[2] = { NULL, NULL };
1273
1274     EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str);
1275     if (str[1] != NULL) {
1276         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1277         return 0;
1278     }
1279 #else
1280 # define EVP_PKEY_TYPE_STR NULL
1281 # define EVP_PKEY_TYPE_STRLEN -1
1282 #endif
1283     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1284                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1285                          keymgmt);
1286
1287 #undef EVP_PKEY_TYPE_STR
1288 #undef EVP_PKEY_TYPE_STRLEN
1289 }
1290
1291 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1292 {
1293     int i;
1294
1295     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
1296         return 0;
1297
1298     REF_PRINT_COUNT("EVP_PKEY", pkey);
1299     REF_ASSERT_ISNT(i < 2);
1300     return ((i > 1) ? 1 : 0);
1301 }
1302
1303 #ifndef FIPS_MODE
1304 void evp_pkey_free_legacy(EVP_PKEY *x)
1305 {
1306     if (x->ameth != NULL) {
1307         if (x->ameth->pkey_free != NULL)
1308             x->ameth->pkey_free(x);
1309         x->pkey.ptr = NULL;
1310     }
1311 # ifndef OPENSSL_NO_ENGINE
1312     ENGINE_finish(x->engine);
1313     x->engine = NULL;
1314     ENGINE_finish(x->pmeth_engine);
1315     x->pmeth_engine = NULL;
1316 # endif
1317     x->type = EVP_PKEY_NONE;
1318 }
1319 #endif  /* FIPS_MODE */
1320
1321 static void evp_pkey_free_it(EVP_PKEY *x)
1322 {
1323     /* internal function; x is never NULL */
1324
1325     evp_keymgmt_util_clear_operation_cache(x);
1326 #ifndef FIPS_MODE
1327     evp_pkey_free_legacy(x);
1328 #endif
1329
1330     if (x->keymgmt != NULL) {
1331         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1332         EVP_KEYMGMT_free(x->keymgmt);
1333         x->keymgmt = NULL;
1334         x->keydata = NULL;
1335     }
1336 }
1337
1338 void EVP_PKEY_free(EVP_PKEY *x)
1339 {
1340     int i;
1341
1342     if (x == NULL)
1343         return;
1344
1345     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
1346     REF_PRINT_COUNT("EVP_PKEY", x);
1347     if (i > 0)
1348         return;
1349     REF_ASSERT_ISNT(i < 0);
1350     evp_pkey_free_it(x);
1351 #ifndef FIPS_MODE
1352     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data);
1353 #endif
1354     CRYPTO_THREAD_lock_free(x->lock);
1355 #ifndef FIPS_MODE
1356     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1357 #endif
1358     OPENSSL_free(x);
1359 }
1360
1361 int EVP_PKEY_size(const EVP_PKEY *pkey)
1362 {
1363     int size = 0;
1364
1365     if (pkey != NULL) {
1366         size = pkey->cache.size;
1367 #ifndef FIPS_MODE
1368         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1369             size = pkey->ameth->pkey_size(pkey);
1370 #endif
1371     }
1372     return size;
1373 }
1374
1375 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
1376                                   EVP_KEYMGMT **keymgmt,
1377                                   const char *propquery)
1378 {
1379     EVP_KEYMGMT *allocated_keymgmt = NULL;
1380     EVP_KEYMGMT *tmp_keymgmt = NULL;
1381     void *keydata = NULL;
1382     int check;
1383
1384     if (pk == NULL)
1385         return NULL;
1386
1387     /* No key data => nothing to export */
1388     check = 1;
1389 #ifndef FIPS_MODE
1390     check = check && pk->pkey.ptr == NULL;
1391 #endif
1392     check = check && pk->keydata == NULL;
1393     if (check)
1394         return NULL;
1395
1396 #ifndef FIPS_MODE
1397     if (pk->pkey.ptr != NULL) {
1398         /*
1399          * If the legacy key doesn't have an dirty counter or export function,
1400          * give up
1401          */
1402         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1403             return NULL;
1404     }
1405 #endif
1406
1407     if (keymgmt != NULL) {
1408         tmp_keymgmt = *keymgmt;
1409         *keymgmt = NULL;
1410     }
1411
1412     /*
1413      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1414      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1415      */
1416     if (tmp_keymgmt == NULL) {
1417         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1418
1419         tmp_keymgmt = ctx->keymgmt;
1420         ctx->keymgmt = NULL;
1421         EVP_PKEY_CTX_free(ctx);
1422     }
1423
1424     /* If there's still no keymgmt to be had, give up */
1425     if (tmp_keymgmt == NULL)
1426         goto end;
1427
1428 #ifndef FIPS_MODE
1429     if (pk->pkey.ptr != NULL) {
1430         size_t i = 0;
1431
1432         /*
1433          * If the legacy "origin" hasn't changed since last time, we try
1434          * to find our keymgmt in the operation cache.  If it has changed,
1435          * |i| remains zero, and we will clear the cache further down.
1436          */
1437         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1438             i = evp_keymgmt_util_find_operation_cache_index(pk, tmp_keymgmt);
1439
1440             /*
1441              * If |tmp_keymgmt| is present in the operation cache, it means
1442              * that export doesn't need to be redone.  In that case, we take
1443              * token copies of the cached pointers, to have token success
1444              * values to return.
1445              */
1446             if (i < OSSL_NELEM(pk->operation_cache)
1447                 && pk->operation_cache[i].keymgmt != NULL) {
1448                 keydata = pk->operation_cache[i].keydata;
1449                 goto end;
1450             }
1451         }
1452
1453         /*
1454          * TODO(3.0) Right now, we assume we have ample space.  We will have
1455          * to think about a cache aging scheme, though, if |i| indexes outside
1456          * the array.
1457          */
1458         if (!ossl_assert(i < OSSL_NELEM(pk->operation_cache)))
1459             goto end;
1460
1461         /* Make sure that the keymgmt key type matches the legacy NID */
1462         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1463             goto end;
1464
1465         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1466             goto end;
1467
1468         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt, libctx, propquery)) {
1469             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1470             keydata = NULL;
1471             goto end;
1472         }
1473
1474         /*
1475          * If the dirty counter changed since last time, then clear the
1476          * operation cache.  In that case, we know that |i| is zero.  Just
1477          * in case this is a re-export, we increment then decrement the
1478          * keymgmt reference counter.
1479          */
1480         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1481             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1482             keydata = NULL;
1483             goto end;
1484         }
1485         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy)
1486             evp_keymgmt_util_clear_operation_cache(pk);
1487         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1488
1489         /* Add the new export to the operation cache */
1490         if (!evp_keymgmt_util_cache_keydata(pk, i, tmp_keymgmt, keydata)) {
1491             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1492             keydata = NULL;
1493             goto end;
1494         }
1495
1496         /* Synchronize the dirty count */
1497         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1498         goto end;
1499     }
1500 #endif  /* FIPS_MODE */
1501
1502     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1503
1504  end:
1505     /*
1506      * If nothing was exported, |tmp_keymgmt| might point at a freed
1507      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1508      * the caller either way in that case.
1509      */
1510     if (keydata == NULL)
1511         tmp_keymgmt = NULL;
1512
1513     if (keymgmt != NULL)
1514         *keymgmt = tmp_keymgmt;
1515
1516     EVP_KEYMGMT_free(allocated_keymgmt);
1517     return keydata;
1518 }
1519
1520 #ifndef FIPS_MODE
1521 int evp_pkey_downgrade(EVP_PKEY *pk)
1522 {
1523     EVP_KEYMGMT *keymgmt = pk->keymgmt;
1524     void *keydata = pk->keydata;
1525     int type = pk->save_type;
1526     const char *keytype = NULL;
1527
1528     /* If this isn't a provider side key, we're done */
1529     if (keymgmt == NULL)
1530         return 1;
1531
1532     /* Get the key type name for error reporting */
1533     if (type != EVP_PKEY_NONE)
1534         keytype = OBJ_nid2sn(type);
1535     else
1536         keytype =
1537             evp_first_name(EVP_KEYMGMT_provider(keymgmt), keymgmt->name_id);
1538
1539     /*
1540      * |save_type| was set when any of the EVP_PKEY_set_type functions
1541      * was called.  It was set to EVP_PKEY_NONE if the key type wasn't
1542      * recognised to be any of the legacy key types, and the downgrade
1543      * isn't possible.
1544      */
1545     if (type == EVP_PKEY_NONE) {
1546         ERR_raise_data(ERR_LIB_EVP, EVP_R_UNKNOWN_KEY_TYPE,
1547                        "key type = %s, can't downgrade", keytype);
1548         return 0;
1549     }
1550
1551     /*
1552      * To be able to downgrade, we steal the provider side "origin" keymgmt
1553      * and keydata.  We've already grabbed the pointers, so all we need to
1554      * do is clear those pointers in |pk| and then call evp_pkey_free_it().
1555      * That way, we can restore |pk| if we need to.
1556      */
1557     pk->keymgmt = NULL;
1558     pk->keydata = NULL;
1559     evp_pkey_free_it(pk);
1560     if (EVP_PKEY_set_type(pk, type)) {
1561         /* If the key is typed but empty, we're done */
1562         if (keydata == NULL) {
1563             /* We're dropping the EVP_KEYMGMT */
1564             EVP_KEYMGMT_free(keymgmt);
1565             return 1;
1566         }
1567
1568         if (pk->ameth->import_from == NULL) {
1569             ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
1570                            "key type = %s", keytype);
1571         } else if (evp_keymgmt_export(keymgmt, keydata,
1572                                       OSSL_KEYMGMT_SELECT_ALL,
1573                                       pk->ameth->import_from, pk)) {
1574             /*
1575              * Save the provider side data in the operation cache, so they'll
1576              * find it again.  evp_pkey_free_it() cleared the cache, so it's
1577              * safe to assume slot zero is free.
1578              * Note that evp_keymgmt_util_cache_keydata() increments keymgmt's
1579              * reference count.
1580              */
1581             evp_keymgmt_util_cache_keydata(pk, 0, keymgmt, keydata);
1582
1583             /* Synchronize the dirty count */
1584             pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1585
1586             /* evp_keymgmt_export() increased the refcount... */
1587             EVP_KEYMGMT_free(keymgmt);
1588             return 1;
1589         }
1590
1591         ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
1592                        "key type = %s", keytype);
1593     }
1594
1595     /*
1596      * Something went wrong.  This could for example happen if the keymgmt
1597      * turns out to be an HSM implementation that refuses to let go of some
1598      * of the key data, typically the private bits.  In this case, we restore
1599      * the provider side internal "origin" and leave it at that.
1600      */
1601     if (!ossl_assert(EVP_PKEY_set_type_by_keymgmt(pk, keymgmt))) {
1602         /* This should not be impossible */
1603         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1604         return 0;
1605     }
1606     /* EVP_PKEY_set_type_by_keymgmt() increased the refcount... */
1607     EVP_KEYMGMT_free(keymgmt);
1608     pk->keydata = keydata;
1609     evp_keymgmt_util_cache_keyinfo(pk);
1610     return 0;     /* No downgrade, but at least the key is restored */
1611 }
1612 #endif  /* FIPS_MODE */
1613
1614 const OSSL_PARAM *EVP_PKEY_gettable_params(EVP_PKEY *pkey)
1615 {
1616     if (pkey == NULL
1617         || pkey->keymgmt == NULL
1618         || pkey->keydata == NULL)
1619         return 0;
1620     return evp_keymgmt_gettable_params(pkey->keymgmt);
1621 }
1622
1623 /*
1624  * For the following methods param->return_size is set to a value
1625  * larger than can be returned by the call to evp_keymgmt_get_params().
1626  * If it is still this value then the parameter was ignored - and in this
1627  * case it returns an error..
1628  */
1629
1630 int EVP_PKEY_get_bn_param(EVP_PKEY *pkey, const char *key_name, BIGNUM **bn)
1631 {
1632     int ret = 0;
1633     OSSL_PARAM params[2];
1634     unsigned char buffer[2048];
1635     /*
1636      * Use -1 as the terminator here instead of sizeof(buffer) + 1 since
1637      * -1 is less likely to be a valid value.
1638      */
1639     const size_t not_set = (size_t)-1;
1640     unsigned char *buf = NULL;
1641     size_t buf_sz = 0;
1642
1643     if (pkey == NULL
1644         || pkey->keymgmt == NULL
1645         || pkey->keydata == NULL
1646         || key_name == NULL
1647         || bn == NULL)
1648         return 0;
1649
1650     memset(buffer, 0, sizeof(buffer));
1651     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
1652     /* If the return_size is still not_set then we know it was not found */
1653     params[0].return_size = not_set;
1654     params[1] = OSSL_PARAM_construct_end();
1655     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params)) {
1656         if (params[0].return_size == not_set
1657             || params[0].return_size == 0)
1658             return 0;
1659         buf_sz = params[0].return_size;
1660         /*
1661          * If it failed because the buffer was too small then allocate the
1662          * required buffer size and retry.
1663          */
1664         buf = OPENSSL_zalloc(buf_sz);
1665         if (buf == NULL)
1666             return 0;
1667         params[0].data = buf;
1668         params[0].data_size = buf_sz;
1669
1670         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1671             goto err;
1672     }
1673     /* Fail if the param was not found */
1674     if (params[0].return_size == not_set)
1675         goto err;
1676     ret = OSSL_PARAM_get_BN(params, bn);
1677 err:
1678     OPENSSL_free(buf);
1679     return ret;
1680 }
1681
1682 int EVP_PKEY_get_octet_string_param(EVP_PKEY *pkey, const char *key_name,
1683                                     unsigned char *buf, size_t max_buf_sz,
1684                                     size_t *out_sz)
1685 {
1686     OSSL_PARAM params[2];
1687     const size_t not_set = max_buf_sz + 1;
1688
1689     if (pkey == NULL
1690         || pkey->keymgmt == NULL
1691         || pkey->keydata == NULL
1692         || key_name == NULL)
1693         return 0;
1694
1695     params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
1696     params[0].return_size = not_set;
1697     params[1] = OSSL_PARAM_construct_end();
1698     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1699         return 0;
1700     if (params[0].return_size == not_set)
1701         return 0;
1702     if (out_sz != NULL)
1703         *out_sz = params[0].return_size;
1704     return 1;
1705 }
1706
1707 int EVP_PKEY_get_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
1708                                     char *str, size_t max_buf_sz,
1709                                     size_t *out_sz)
1710 {
1711     OSSL_PARAM params[2];
1712     const size_t not_set = max_buf_sz + 1;
1713
1714     if (pkey == NULL
1715         || pkey->keymgmt == NULL
1716         || pkey->keydata == NULL
1717         || key_name == NULL)
1718         return 0;
1719
1720     params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
1721     params[0].return_size = not_set;
1722     params[1] = OSSL_PARAM_construct_end();
1723     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1724         return 0;
1725     if (params[0].return_size == not_set)
1726         return 0;
1727     if (out_sz != NULL)
1728         *out_sz = params[0].return_size;
1729     return 1;
1730 }
1731
1732 int EVP_PKEY_get_int_param(EVP_PKEY *pkey, const char *key_name, int *out)
1733 {
1734     OSSL_PARAM params[2];
1735     const size_t not_set = sizeof(int) + 1;
1736
1737     if (pkey == NULL
1738         || pkey->keymgmt == NULL
1739         || pkey->keydata == NULL
1740         || key_name == NULL)
1741         return 0;
1742
1743     params[0] = OSSL_PARAM_construct_int(key_name, out);
1744     params[0].return_size = not_set;
1745     params[1] = OSSL_PARAM_construct_end();
1746     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1747         return 0;
1748     if (params[0].return_size == not_set)
1749         return 0;
1750     return 1;
1751 }
1752
1753 int EVP_PKEY_get_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t *out)
1754 {
1755     OSSL_PARAM params[2];
1756     const size_t not_set = sizeof(size_t) + 1;
1757
1758     if (pkey == NULL
1759         || pkey->keymgmt == NULL
1760         || pkey->keydata == NULL
1761         || key_name == NULL)
1762         return 0;
1763
1764     params[0] = OSSL_PARAM_construct_size_t(key_name, out);
1765     params[0].return_size = not_set;
1766     params[1] = OSSL_PARAM_construct_end();
1767     if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
1768         return 0;
1769     if (params[0].return_size == not_set)
1770         return 0;
1771     return 1;
1772 }