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