621d99d1713ba105162f6d140819d574b325e80a
[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 void evp_pkey_free_it(EVP_PKEY *key);
39
40 #ifndef FIPS_MODE
41
42 int EVP_PKEY_bits(const EVP_PKEY *pkey)
43 {
44     if (pkey != NULL) {
45         if (pkey->ameth == NULL)
46             return pkey->cache.bits;
47         else if (pkey->ameth->pkey_bits)
48             return pkey->ameth->pkey_bits(pkey);
49     }
50     return 0;
51 }
52
53 int EVP_PKEY_security_bits(const EVP_PKEY *pkey)
54 {
55     if (pkey == NULL)
56         return 0;
57     if (pkey->ameth == NULL)
58         return pkey->cache.security_bits;
59     if (pkey->ameth->pkey_security_bits == NULL)
60         return -2;
61     return pkey->ameth->pkey_security_bits(pkey);
62 }
63
64 int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
65 {
66 # ifndef OPENSSL_NO_DSA
67     if (pkey->type == EVP_PKEY_DSA) {
68         int ret = pkey->save_parameters;
69
70         if (mode >= 0)
71             pkey->save_parameters = mode;
72         return ret;
73     }
74 # endif
75 # ifndef OPENSSL_NO_EC
76     if (pkey->type == EVP_PKEY_EC) {
77         int ret = pkey->save_parameters;
78
79         if (mode >= 0)
80             pkey->save_parameters = mode;
81         return ret;
82     }
83 # endif
84     return 0;
85 }
86
87 int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
88 {
89     if (to->type == EVP_PKEY_NONE) {
90         if (EVP_PKEY_set_type(to, from->type) == 0)
91             return 0;
92     } else if (to->type != from->type) {
93         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_KEY_TYPES);
94         goto err;
95     }
96
97     if (EVP_PKEY_missing_parameters(from)) {
98         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_MISSING_PARAMETERS);
99         goto err;
100     }
101
102     if (!EVP_PKEY_missing_parameters(to)) {
103         if (EVP_PKEY_cmp_parameters(to, from) == 1)
104             return 1;
105         EVPerr(EVP_F_EVP_PKEY_COPY_PARAMETERS, EVP_R_DIFFERENT_PARAMETERS);
106         return 0;
107     }
108
109     if (from->ameth && from->ameth->param_copy)
110         return from->ameth->param_copy(to, from);
111  err:
112     return 0;
113 }
114
115 int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
116 {
117     if (pkey != NULL && pkey->ameth && pkey->ameth->param_missing)
118         return pkey->ameth->param_missing(pkey);
119     return 0;
120 }
121
122 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
123 {
124     if (a->type != b->type)
125         return -1;
126     if (a->ameth && a->ameth->param_cmp)
127         return a->ameth->param_cmp(a, b);
128     return -2;
129 }
130
131 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
132 {
133     if (a->type != b->type)
134         return -1;
135
136     if (a->ameth) {
137         int ret;
138         /* Compare parameters if the algorithm has them */
139         if (a->ameth->param_cmp) {
140             ret = a->ameth->param_cmp(a, b);
141             if (ret <= 0)
142                 return ret;
143         }
144
145         if (a->ameth->pub_cmp)
146             return a->ameth->pub_cmp(a, b);
147     }
148
149     return -2;
150 }
151
152
153 /*
154  * Setup a public key ASN1 method and ENGINE from a NID or a string. If pkey
155  * is NULL just return 1 or 0 if the algorithm exists.
156  */
157
158 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
159                          int len)
160 {
161     const EVP_PKEY_ASN1_METHOD *ameth;
162     ENGINE **eptr = (e == NULL) ? &e :  NULL;
163
164     if (pkey) {
165         if (pkey->pkey.ptr)
166             evp_pkey_free_it(pkey);
167         /*
168          * If key type matches and a method exists then this lookup has
169          * succeeded once so just indicate success.
170          */
171         if ((type == pkey->save_type) && pkey->ameth)
172             return 1;
173 # ifndef OPENSSL_NO_ENGINE
174         /* If we have ENGINEs release them */
175         ENGINE_finish(pkey->engine);
176         pkey->engine = NULL;
177         ENGINE_finish(pkey->pmeth_engine);
178         pkey->pmeth_engine = NULL;
179 # endif
180     }
181     if (str)
182         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
183     else
184         ameth = EVP_PKEY_asn1_find(eptr, type);
185 # ifndef OPENSSL_NO_ENGINE
186     if (pkey == NULL && eptr != NULL)
187         ENGINE_finish(e);
188 # endif
189     if (ameth == NULL) {
190         EVPerr(EVP_F_PKEY_SET_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
191         return 0;
192     }
193     if (pkey) {
194         pkey->ameth = ameth;
195         pkey->engine = e;
196
197         pkey->type = pkey->ameth->pkey_id;
198         pkey->save_type = type;
199     }
200     return 1;
201 }
202
203 EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
204                                        const unsigned char *priv,
205                                        size_t len)
206 {
207     EVP_PKEY *ret = EVP_PKEY_new();
208
209     if (ret == NULL
210             || !pkey_set_type(ret, e, type, NULL, -1)) {
211         /* EVPerr already called */
212         goto err;
213     }
214
215     if (ret->ameth->set_priv_key == NULL) {
216         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY,
217                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
218         goto err;
219     }
220
221     if (!ret->ameth->set_priv_key(ret, priv, len)) {
222         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY, EVP_R_KEY_SETUP_FAILED);
223         goto err;
224     }
225
226     return ret;
227
228  err:
229     EVP_PKEY_free(ret);
230     return NULL;
231 }
232
233 EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
234                                       const unsigned char *pub,
235                                       size_t len)
236 {
237     EVP_PKEY *ret = EVP_PKEY_new();
238
239     if (ret == NULL
240             || !pkey_set_type(ret, e, type, NULL, -1)) {
241         /* EVPerr already called */
242         goto err;
243     }
244
245     if (ret->ameth->set_pub_key == NULL) {
246         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY,
247                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
248         goto err;
249     }
250
251     if (!ret->ameth->set_pub_key(ret, pub, len)) {
252         EVPerr(EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY, EVP_R_KEY_SETUP_FAILED);
253         goto err;
254     }
255
256     return ret;
257
258  err:
259     EVP_PKEY_free(ret);
260     return NULL;
261 }
262
263 int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
264                                  size_t *len)
265 {
266      if (pkey->ameth->get_priv_key == NULL) {
267         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY,
268                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
269         return 0;
270     }
271
272     if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
273         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY, EVP_R_GET_RAW_KEY_FAILED);
274         return 0;
275     }
276
277     return 1;
278 }
279
280 int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
281                                 size_t *len)
282 {
283      if (pkey->ameth->get_pub_key == NULL) {
284         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY,
285                EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
286         return 0;
287     }
288
289     if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
290         EVPerr(EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY, EVP_R_GET_RAW_KEY_FAILED);
291         return 0;
292     }
293
294     return 1;
295 }
296
297 EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
298                                 size_t len, const EVP_CIPHER *cipher)
299 {
300 # ifndef OPENSSL_NO_CMAC
301 #  ifndef OPENSSL_NO_ENGINE
302     const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
303 #  endif
304     const char *cipher_name = EVP_CIPHER_name(cipher);
305     const OSSL_PROVIDER *prov = EVP_CIPHER_provider(cipher);
306     OPENSSL_CTX *libctx =
307         prov == NULL ? NULL : ossl_provider_library_context(prov);
308     EVP_PKEY *ret = EVP_PKEY_new();
309     EVP_MAC *cmac = EVP_MAC_fetch(libctx, OSSL_MAC_NAME_CMAC, NULL);
310     EVP_MAC_CTX *cmctx = cmac != NULL ? EVP_MAC_CTX_new(cmac) : NULL;
311     OSSL_PARAM params[4];
312     size_t paramsn = 0;
313
314     if (ret == NULL
315             || cmctx == NULL
316             || !pkey_set_type(ret, e, EVP_PKEY_CMAC, NULL, -1)) {
317         /* EVPerr already called */
318         goto err;
319     }
320
321 #  ifndef OPENSSL_NO_ENGINE
322     if (engine_id != NULL)
323         params[paramsn++] =
324             OSSL_PARAM_construct_utf8_string("engine", (char *)engine_id, 0);
325 #  endif
326
327     params[paramsn++] =
328         OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
329                                          (char *)cipher_name, 0);
330     params[paramsn++] =
331         OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
332                                           (char *)priv, len);
333     params[paramsn] = OSSL_PARAM_construct_end();
334
335     if (!EVP_MAC_CTX_set_params(cmctx, params)) {
336         EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY, EVP_R_KEY_SETUP_FAILED);
337         goto err;
338     }
339
340     ret->pkey.ptr = cmctx;
341     return ret;
342
343  err:
344     EVP_PKEY_free(ret);
345     EVP_MAC_CTX_free(cmctx);
346     EVP_MAC_free(cmac);
347     return NULL;
348 # else
349     EVPerr(EVP_F_EVP_PKEY_NEW_CMAC_KEY,
350            EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
351     return NULL;
352 # endif
353 }
354
355 int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
356 {
357     return pkey_set_type(pkey, NULL, type, NULL, -1);
358 }
359
360 int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
361 {
362     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len);
363 }
364
365 int EVP_PKEY_set_alias_type(EVP_PKEY *pkey, int type)
366 {
367     if (pkey->type == type) {
368         return 1; /* it already is that type */
369     }
370
371     /*
372      * The application is requesting to alias this to a different pkey type,
373      * but not one that resolves to the base type.
374      */
375     if (EVP_PKEY_type(type) != EVP_PKEY_base_id(pkey)) {
376         EVPerr(EVP_F_EVP_PKEY_SET_ALIAS_TYPE, EVP_R_UNSUPPORTED_ALGORITHM);
377         return 0;
378     }
379
380     pkey->type = type;
381     return 1;
382 }
383
384 # ifndef OPENSSL_NO_ENGINE
385 int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
386 {
387     if (e != NULL) {
388         if (!ENGINE_init(e)) {
389             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, ERR_R_ENGINE_LIB);
390             return 0;
391         }
392         if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
393             ENGINE_finish(e);
394             EVPerr(EVP_F_EVP_PKEY_SET1_ENGINE, EVP_R_UNSUPPORTED_ALGORITHM);
395             return 0;
396         }
397     }
398     ENGINE_finish(pkey->pmeth_engine);
399     pkey->pmeth_engine = e;
400     return 1;
401 }
402
403 ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
404 {
405     return pkey->engine;
406 }
407 # endif
408 int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
409 {
410     int alias = type;
411
412 #ifndef OPENSSL_NO_EC
413     if (EVP_PKEY_type(type) == EVP_PKEY_EC) {
414         const EC_GROUP *group = EC_KEY_get0_group(key);
415
416         if (group != NULL && EC_GROUP_get_curve_name(group) == NID_sm2)
417             alias = EVP_PKEY_SM2;
418     }
419 #endif
420
421     if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
422         return 0;
423     if (!EVP_PKEY_set_alias_type(pkey, alias))
424         return 0;
425     pkey->pkey.ptr = key;
426     return (key != NULL);
427 }
428
429 void *EVP_PKEY_get0(const EVP_PKEY *pkey)
430 {
431     return pkey->pkey.ptr;
432 }
433
434 const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
435 {
436     ASN1_OCTET_STRING *os = NULL;
437     if (pkey->type != EVP_PKEY_HMAC) {
438         EVPerr(EVP_F_EVP_PKEY_GET0_HMAC, EVP_R_EXPECTING_AN_HMAC_KEY);
439         return NULL;
440     }
441     os = EVP_PKEY_get0(pkey);
442     *len = os->length;
443     return os->data;
444 }
445
446 # ifndef OPENSSL_NO_POLY1305
447 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
448 {
449     ASN1_OCTET_STRING *os = NULL;
450     if (pkey->type != EVP_PKEY_POLY1305) {
451         EVPerr(EVP_F_EVP_PKEY_GET0_POLY1305, EVP_R_EXPECTING_A_POLY1305_KEY);
452         return NULL;
453     }
454     os = EVP_PKEY_get0(pkey);
455     *len = os->length;
456     return os->data;
457 }
458 # endif
459
460 # ifndef OPENSSL_NO_SIPHASH
461 const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
462 {
463     ASN1_OCTET_STRING *os = NULL;
464
465     if (pkey->type != EVP_PKEY_SIPHASH) {
466         EVPerr(EVP_F_EVP_PKEY_GET0_SIPHASH, EVP_R_EXPECTING_A_SIPHASH_KEY);
467         return NULL;
468     }
469     os = EVP_PKEY_get0(pkey);
470     *len = os->length;
471     return os->data;
472 }
473 # endif
474
475 # ifndef OPENSSL_NO_RSA
476 int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key)
477 {
478     int ret = EVP_PKEY_assign_RSA(pkey, key);
479     if (ret)
480         RSA_up_ref(key);
481     return ret;
482 }
483
484 RSA *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey)
485 {
486     if (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_RSA_PSS) {
487         EVPerr(EVP_F_EVP_PKEY_GET0_RSA, EVP_R_EXPECTING_AN_RSA_KEY);
488         return NULL;
489     }
490     return pkey->pkey.rsa;
491 }
492
493 RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey)
494 {
495     RSA *ret = EVP_PKEY_get0_RSA(pkey);
496     if (ret != NULL)
497         RSA_up_ref(ret);
498     return ret;
499 }
500 # endif
501
502 # ifndef OPENSSL_NO_DSA
503 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
504 {
505     int ret = EVP_PKEY_assign_DSA(pkey, key);
506     if (ret)
507         DSA_up_ref(key);
508     return ret;
509 }
510
511 DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
512 {
513     if (pkey->type != EVP_PKEY_DSA) {
514         EVPerr(EVP_F_EVP_PKEY_GET0_DSA, EVP_R_EXPECTING_A_DSA_KEY);
515         return NULL;
516     }
517     return pkey->pkey.dsa;
518 }
519
520 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
521 {
522     DSA *ret = EVP_PKEY_get0_DSA(pkey);
523     if (ret != NULL)
524         DSA_up_ref(ret);
525     return ret;
526 }
527 # endif
528
529 # ifndef OPENSSL_NO_EC
530
531 int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key)
532 {
533     int ret = EVP_PKEY_assign_EC_KEY(pkey, key);
534     if (ret)
535         EC_KEY_up_ref(key);
536     return ret;
537 }
538
539 EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey)
540 {
541     if (EVP_PKEY_base_id(pkey) != EVP_PKEY_EC) {
542         EVPerr(EVP_F_EVP_PKEY_GET0_EC_KEY, EVP_R_EXPECTING_A_EC_KEY);
543         return NULL;
544     }
545     return pkey->pkey.ec;
546 }
547
548 EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey)
549 {
550     EC_KEY *ret = EVP_PKEY_get0_EC_KEY(pkey);
551     if (ret != NULL)
552         EC_KEY_up_ref(ret);
553     return ret;
554 }
555 # endif
556
557 # ifndef OPENSSL_NO_DH
558
559 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *key)
560 {
561     int type = DH_get0_q(key) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
562     int ret = EVP_PKEY_assign(pkey, type, key);
563
564     if (ret)
565         DH_up_ref(key);
566     return ret;
567 }
568
569 DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
570 {
571     if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
572         EVPerr(EVP_F_EVP_PKEY_GET0_DH, EVP_R_EXPECTING_A_DH_KEY);
573         return NULL;
574     }
575     return pkey->pkey.dh;
576 }
577
578 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
579 {
580     DH *ret = EVP_PKEY_get0_DH(pkey);
581     if (ret != NULL)
582         DH_up_ref(ret);
583     return ret;
584 }
585 # endif
586
587 int EVP_PKEY_type(int type)
588 {
589     int ret;
590     const EVP_PKEY_ASN1_METHOD *ameth;
591     ENGINE *e;
592     ameth = EVP_PKEY_asn1_find(&e, type);
593     if (ameth)
594         ret = ameth->pkey_id;
595     else
596         ret = NID_undef;
597 # ifndef OPENSSL_NO_ENGINE
598     ENGINE_finish(e);
599 # endif
600     return ret;
601 }
602
603 int EVP_PKEY_id(const EVP_PKEY *pkey)
604 {
605     return pkey->type;
606 }
607
608 int EVP_PKEY_base_id(const EVP_PKEY *pkey)
609 {
610     return EVP_PKEY_type(pkey->type);
611 }
612
613
614 static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
615 {
616     BIO_set_indent(*out, saved_indent);
617     if (pop_f_prefix) {
618         BIO *next = BIO_pop(*out);
619
620         BIO_free(*out);
621         *out = next;
622     }
623     return 1;
624 }
625
626 static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
627                             long indent)
628 {
629     *pop_f_prefix = 0;
630     *saved_indent = 0;
631     if (indent > 0) {
632         long i = BIO_get_indent(*out);
633
634         *saved_indent =  (i < 0 ? 0 : i);
635         if (BIO_set_indent(*out, indent) <= 0) {
636             if ((*out = BIO_push(BIO_new(BIO_f_prefix()), *out)) == NULL)
637                 return 0;
638             *pop_f_prefix = 1;
639         }
640         if (BIO_set_indent(*out, indent) <= 0) {
641             print_reset_indent(out, *pop_f_prefix, *saved_indent);
642             return 0;
643         }
644     }
645     return 1;
646 }
647
648 static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
649                      const char *kstr)
650 {
651     return BIO_indent(out, indent, 128)
652         && BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
653                       kstr, OBJ_nid2ln(pkey->type)) > 0;
654 }
655
656 static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
657                       const char *propquery /* For provided serialization */,
658                       int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
659                                           int indent, ASN1_PCTX *pctx),
660                       ASN1_PCTX *legacy_pctx /* For legacy print */)
661 {
662     int pop_f_prefix;
663     long saved_indent;
664     OSSL_SERIALIZER_CTX *ctx = NULL;
665     int ret = -2;                /* default to unsupported */
666
667     if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
668         return 0;
669
670     ctx = OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(pkey, propquery);
671     if (OSSL_SERIALIZER_CTX_get_serializer(ctx) != NULL)
672         ret = OSSL_SERIALIZER_to_bio(ctx, out);
673     OSSL_SERIALIZER_CTX_free(ctx);
674
675     if (ret != -2)
676         goto end;
677
678     /* legacy fallback */
679     if (legacy_print != NULL)
680         ret = legacy_print(out, pkey, 0, legacy_pctx);
681     else
682         ret = unsup_alg(out, pkey, 0, "Public Key");
683
684  end:
685     print_reset_indent(&out, pop_f_prefix, saved_indent);
686     return ret;
687 }
688
689 int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
690                           int indent, ASN1_PCTX *pctx)
691 {
692     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PUBKEY_TO_TEXT_PQ,
693                       (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
694                       pctx);
695 }
696
697 int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
698                            int indent, ASN1_PCTX *pctx)
699 {
700     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_PrivateKey_TO_TEXT_PQ,
701                       (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL),
702                       pctx);
703 }
704
705 int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
706                           int indent, ASN1_PCTX *pctx)
707 {
708     return print_pkey(pkey, out, indent, OSSL_SERIALIZER_Parameters_TO_TEXT_PQ,
709                       (pkey->ameth != NULL ? pkey->ameth->param_print : NULL),
710                       pctx);
711 }
712
713 static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op,
714                                      int arg1, void *arg2)
715 {
716     if (pkey->keymgmt == NULL)
717         return 0;
718     switch (op) {
719     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
720         {
721             char mdname[80] = "";
722             int nid;
723             int rv = EVP_PKEY_get_default_digest_name(pkey, mdname,
724                                                       sizeof(mdname));
725
726             if (rv <= 0)
727                 return rv;
728             nid = OBJ_sn2nid(mdname);
729             if (nid == NID_undef)
730                 nid = OBJ_ln2nid(mdname);
731             if (nid == NID_undef)
732                 return 0;
733             *(int *)arg2 = nid;
734             return 1;
735         }
736     default:
737         return -2;
738     }
739 }
740
741 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
742 {
743     if (pkey->ameth == NULL)
744         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
745     if (pkey->ameth->pkey_ctrl == NULL)
746         return -2;
747     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
748 }
749
750 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
751 {
752     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
753 }
754
755 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
756                                      char *mdname, size_t mdname_sz)
757 {
758     if (pkey->ameth == NULL) {
759         OSSL_PARAM params[3];
760         char mddefault[100] = "";
761         char mdmandatory[100] = "";
762
763         params[0] =
764             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST,
765                                              mddefault, sizeof(mddefault));
766         params[1] =
767             OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_MANDATORY_DIGEST,
768                                              mdmandatory,
769                                              sizeof(mdmandatory));
770         params[2] = OSSL_PARAM_construct_end();
771         if (!evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params))
772             return 0;
773         if (mdmandatory[0] != '\0') {
774             OPENSSL_strlcpy(mdname, mdmandatory, mdname_sz);
775             return 2;
776         }
777         OPENSSL_strlcpy(mdname, mddefault, mdname_sz);
778         return 1;
779     }
780
781     {
782         int nid = NID_undef;
783         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
784         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
785
786         if (rv > 0)
787             OPENSSL_strlcpy(mdname, name, mdname_sz);
788         return rv;
789     }
790 }
791
792 int EVP_PKEY_supports_digest_nid(EVP_PKEY *pkey, int nid)
793 {
794     int rv, default_nid;
795
796     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SUPPORTS_MD_NID, nid, NULL);
797     if (rv == -2) {
798         /*
799          * If there is a mandatory default digest and this isn't it, then
800          * the answer is 'no'.
801          */
802         rv = EVP_PKEY_get_default_digest_nid(pkey, &default_nid);
803         if (rv == 2)
804             return (nid == default_nid);
805         /* zero is an error from EVP_PKEY_get_default_digest_nid() */
806         if (rv == 0)
807             return -1;
808     }
809     return rv;
810 }
811
812 int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey,
813                                const unsigned char *pt, size_t ptlen)
814 {
815     if (ptlen > INT_MAX)
816         return 0;
817     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, ptlen,
818                            (void *)pt) <= 0)
819         return 0;
820     return 1;
821 }
822
823 size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *pkey, unsigned char **ppt)
824 {
825     int rv;
826     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppt);
827     if (rv <= 0)
828         return 0;
829     return rv;
830 }
831
832 #endif /* FIPS_MODE */
833
834 /*- All methods below can also be used in FIPS_MODE */
835
836 EVP_PKEY *EVP_PKEY_new(void)
837 {
838     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
839
840     if (ret == NULL) {
841         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
842         return NULL;
843     }
844     ret->type = EVP_PKEY_NONE;
845     ret->save_type = EVP_PKEY_NONE;
846     ret->references = 1;
847     ret->save_parameters = 1;
848     ret->lock = CRYPTO_THREAD_lock_new();
849     if (ret->lock == NULL) {
850         EVPerr(EVP_F_EVP_PKEY_NEW, ERR_R_MALLOC_FAILURE);
851         OPENSSL_free(ret);
852         return NULL;
853     }
854     return ret;
855 }
856
857 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
858 {
859     int i;
860
861     if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0)
862         return 0;
863
864     REF_PRINT_COUNT("EVP_PKEY", pkey);
865     REF_ASSERT_ISNT(i < 2);
866     return ((i > 1) ? 1 : 0);
867 }
868
869 #ifndef FIPS_MODE
870 static void evp_pkey_free_legacy(EVP_PKEY *x)
871 {
872     if (x->ameth != NULL) {
873         if (x->ameth->pkey_free)
874             x->ameth->pkey_free(x);
875         x->pkey.ptr = NULL;
876         x->ameth = NULL;
877     }
878 # ifndef OPENSSL_NO_ENGINE
879     ENGINE_finish(x->engine);
880     x->engine = NULL;
881     ENGINE_finish(x->pmeth_engine);
882     x->pmeth_engine = NULL;
883 # endif
884     x->type = x->save_type = EVP_PKEY_NONE;
885 }
886 #endif  /* FIPS_MODE */
887
888 static void evp_pkey_free_it(EVP_PKEY *x)
889 {
890     /* internal function; x is never NULL */
891
892     evp_keymgmt_util_clear_operation_cache(x);
893 #ifndef FIPS_MODE
894     evp_pkey_free_legacy(x);
895 #endif
896
897     if (x->keymgmt != NULL) {
898         evp_keymgmt_freedata(x->keymgmt, x->keydata);
899         EVP_KEYMGMT_free(x->keymgmt);
900         x->keymgmt = NULL;
901         x->keydata = NULL;
902     }
903 }
904
905 void EVP_PKEY_free(EVP_PKEY *x)
906 {
907     int i;
908
909     if (x == NULL)
910         return;
911
912     CRYPTO_DOWN_REF(&x->references, &i, x->lock);
913     REF_PRINT_COUNT("EVP_PKEY", x);
914     if (i > 0)
915         return;
916     REF_ASSERT_ISNT(i < 0);
917     evp_pkey_free_it(x);
918     CRYPTO_THREAD_lock_free(x->lock);
919 #ifndef FIPS_MODE
920     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
921 #endif
922     OPENSSL_free(x);
923 }
924
925 int EVP_PKEY_size(const EVP_PKEY *pkey)
926 {
927     if (pkey != NULL) {
928         if (pkey->ameth == NULL)
929             return pkey->cache.size;
930         else if (pkey->ameth->pkey_size != NULL)
931             return pkey->ameth->pkey_size(pkey);
932     }
933     return 0;
934 }
935
936 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
937                                   EVP_KEYMGMT **keymgmt,
938                                   const char *propquery)
939 {
940     EVP_KEYMGMT *allocated_keymgmt = NULL;
941     EVP_KEYMGMT *tmp_keymgmt = NULL;
942     void *keydata = NULL;
943
944     if (pk == NULL)
945         return NULL;
946
947 #ifndef FIPS_MODE
948     if (pk->pkey.ptr != NULL) {
949         /*
950          * If the legacy key doesn't have an dirty counter or export function,
951          * give up
952          */
953         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
954             return NULL;
955     }
956 #endif
957
958     if (keymgmt != NULL) {
959         tmp_keymgmt = *keymgmt;
960         *keymgmt = NULL;
961     }
962
963     /* If no keymgmt was given or found, get a default keymgmt */
964     if (tmp_keymgmt == NULL) {
965         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
966
967         if (ctx != NULL && ctx->keytype != NULL)
968             tmp_keymgmt = allocated_keymgmt =
969                 EVP_KEYMGMT_fetch(ctx->libctx, ctx->keytype, propquery);
970         EVP_PKEY_CTX_free(ctx);
971     }
972
973     /* If there's still no keymgmt to be had, give up */
974     if (tmp_keymgmt == NULL)
975         goto end;
976
977 #ifndef FIPS_MODE
978     if (pk->pkey.ptr != NULL) {
979         size_t i = 0;
980
981         /*
982          * If the legacy "origin" hasn't changed since last time, we try
983          * to find our keymgmt in the operation cache.  If it has changed,
984          * |i| remains zero, and we will clear the cache further down.
985          */
986         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
987             i = evp_keymgmt_util_find_operation_cache_index(pk, tmp_keymgmt);
988
989             /*
990              * If |tmp_keymgmt| is present in the operation cache, it means
991              * that export doesn't need to be redone.  In that case, we take
992              * token copies of the cached pointers, to have token success
993              * values to return.
994              */
995             if (i < OSSL_NELEM(pk->operation_cache)
996                 && pk->operation_cache[i].keymgmt != NULL) {
997                 keydata = pk->operation_cache[i].keydata;
998                 goto end;
999             }
1000         }
1001
1002         /*
1003          * TODO(3.0) Right now, we assume we have ample space.  We will have
1004          * to think about a cache aging scheme, though, if |i| indexes outside
1005          * the array.
1006          */
1007         if (!ossl_assert(i < OSSL_NELEM(pk->operation_cache)))
1008             goto end;
1009
1010         /* Make sure that the keymgmt key type matches the legacy NID */
1011         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1012             goto end;
1013
1014         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1015             goto end;
1016
1017         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt)) {
1018             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1019             keydata = NULL;
1020             goto end;
1021         }
1022
1023         /*
1024          * If the dirty counter changed since last time, then clear the
1025          * operation cache.  In that case, we know that |i| is zero.  Just
1026          * in case this is a re-export, we increment then decrement the
1027          * keymgmt reference counter.
1028          */
1029         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1030             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1031             keydata = NULL;
1032             goto end;
1033         }
1034         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy)
1035             evp_keymgmt_util_clear_operation_cache(pk);
1036         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1037
1038         /* Add the new export to the operation cache */
1039         if (!evp_keymgmt_util_cache_keydata(pk, i, tmp_keymgmt, keydata)) {
1040             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1041             keydata = NULL;
1042             goto end;
1043         }
1044
1045         /* Synchronize the dirty count */
1046         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1047         goto end;
1048     }
1049 #endif  /* FIPS_MODE */
1050
1051     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt);
1052
1053  end:
1054     /*
1055      * If nothing was exported, |tmp_keymgmt| might point at a freed
1056      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1057      * the caller either way in that case.
1058      */
1059     if (keydata == NULL)
1060         tmp_keymgmt = NULL;
1061
1062     if (keymgmt != NULL)
1063         *keymgmt = tmp_keymgmt;
1064
1065     EVP_KEYMGMT_free(allocated_keymgmt);
1066     return keydata;
1067 }
1068
1069 #ifndef FIPS_MODE
1070 /*
1071  * This differs from exporting in that it releases the legacy key and assigns
1072  * the export keymgmt and keydata to the "origin" provider side key instead
1073  * of the operation cache.
1074  */
1075 void *evp_pkey_upgrade_to_provider(EVP_PKEY *pk, OPENSSL_CTX *libctx,
1076                                    EVP_KEYMGMT **keymgmt,
1077                                    const char *propquery)
1078 {
1079     EVP_KEYMGMT *allocated_keymgmt = NULL;
1080     EVP_KEYMGMT *tmp_keymgmt = NULL;
1081     void *keydata = NULL;
1082
1083     if (pk == NULL)
1084         return NULL;
1085
1086     /*
1087      * If this key is already "upgraded", this function shouldn't have been
1088      * called.
1089      */
1090     if (!ossl_assert(pk->keymgmt == NULL))
1091         return NULL;
1092
1093     if (keymgmt != NULL) {
1094         tmp_keymgmt = *keymgmt;
1095         *keymgmt = NULL;
1096     }
1097
1098     /* If the key isn't a legacy one, bail out, but with proper values */
1099     if (pk->pkey.ptr == NULL) {
1100         tmp_keymgmt = pk->keymgmt;
1101         keydata = pk->keydata;
1102     } else {
1103         /* If the legacy key doesn't have an export function, give up */
1104         if (pk->ameth->export_to == NULL)
1105             return NULL;
1106
1107         /* If no keymgmt was given, get a default keymgmt */
1108         if (tmp_keymgmt == NULL) {
1109             EVP_PKEY_CTX *ctx =
1110                 EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1111
1112             if (ctx != NULL && ctx->keytype != NULL)
1113                 tmp_keymgmt = allocated_keymgmt =
1114                     EVP_KEYMGMT_fetch(ctx->libctx, ctx->keytype, propquery);
1115             EVP_PKEY_CTX_free(ctx);
1116         }
1117
1118         /* If we still don't have a keymgmt, give up */
1119         if (tmp_keymgmt == NULL)
1120             goto end;
1121
1122         /* Make sure that the keymgmt key type matches the legacy NID */
1123         if (!ossl_assert(EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type))))
1124             goto end;
1125
1126         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1127             goto end;
1128
1129         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt)
1130             || !EVP_KEYMGMT_up_ref(tmp_keymgmt)) {
1131             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1132             keydata = NULL;
1133             goto end;
1134         }
1135
1136         /*
1137          * Clear the operation cache, all the legacy data, as well as the
1138          * dirty counters
1139          */
1140         evp_pkey_free_legacy(pk);
1141         pk->dirty_cnt_copy = 0;
1142
1143         evp_keymgmt_util_clear_operation_cache(pk);
1144         pk->keymgmt = tmp_keymgmt;
1145         pk->keydata = keydata;
1146         evp_keymgmt_util_cache_keyinfo(pk);
1147     }
1148
1149  end:
1150     /*
1151      * If nothing was upgraded, |tmp_keymgmt| might point at a freed
1152      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
1153      * the caller either way in that case.
1154      */
1155     if (keydata == NULL)
1156         tmp_keymgmt = NULL;
1157
1158     if (keymgmt != NULL)
1159         *keymgmt = tmp_keymgmt;
1160
1161     EVP_KEYMGMT_free(allocated_keymgmt);
1162     return keydata;
1163 }
1164 #endif  /* FIPS_MODE */