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