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