xref: /openssl/crypto/evp/p_lib.c (revision b6461792)
1 /*
2  * Copyright 1995-2024 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 <assert.h>
17 #include <stdio.h>
18 #include "internal/cryptlib.h"
19 #include "internal/refcount.h"
20 #include "internal/namemap.h"
21 #include <openssl/bn.h>
22 #include <openssl/err.h>
23 #include <openssl/objects.h>
24 #include <openssl/evp.h>
25 #include <openssl/rsa.h>
26 #include <openssl/dsa.h>
27 #include <openssl/dh.h>
28 #include <openssl/ec.h>
29 #include <openssl/cmac.h>
30 #ifndef FIPS_MODULE
31 # include <openssl/engine.h>
32 #endif
33 #include <openssl/params.h>
34 #include <openssl/param_build.h>
35 #include <openssl/encoder.h>
36 #include <openssl/core_names.h>
37 
38 #include "internal/numbers.h"   /* includes SIZE_MAX */
39 #include "internal/ffc.h"
40 #include "crypto/evp.h"
41 #include "crypto/dh.h"
42 #include "crypto/dsa.h"
43 #include "crypto/ec.h"
44 #include "crypto/ecx.h"
45 #include "crypto/rsa.h"
46 #ifndef FIPS_MODULE
47 # include "crypto/asn1.h"
48 # include "crypto/x509.h"
49 #endif
50 #include "internal/provider.h"
51 #include "evp_local.h"
52 
53 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
54                          int len, EVP_KEYMGMT *keymgmt);
55 static void evp_pkey_free_it(EVP_PKEY *key);
56 
57 #ifndef FIPS_MODULE
58 
59 /* The type of parameters selected in key parameter functions */
60 # define SELECT_PARAMETERS OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
61 
EVP_PKEY_get_bits(const EVP_PKEY * pkey)62 int EVP_PKEY_get_bits(const EVP_PKEY *pkey)
63 {
64     int size = 0;
65 
66     if (pkey != NULL) {
67         size = pkey->cache.bits;
68         if (pkey->ameth != NULL && pkey->ameth->pkey_bits != NULL)
69             size = pkey->ameth->pkey_bits(pkey);
70     }
71     if (size <= 0) {
72         ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_BITS);
73         return 0;
74     }
75     return size;
76 }
77 
EVP_PKEY_get_security_bits(const EVP_PKEY * pkey)78 int EVP_PKEY_get_security_bits(const EVP_PKEY *pkey)
79 {
80     int size = 0;
81 
82     if (pkey != NULL) {
83         size = pkey->cache.security_bits;
84         if (pkey->ameth != NULL && pkey->ameth->pkey_security_bits != NULL)
85             size = pkey->ameth->pkey_security_bits(pkey);
86     }
87     if (size <= 0) {
88         ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_SECURITY_BITS);
89         return 0;
90     }
91     return size;
92 }
93 
EVP_PKEY_save_parameters(EVP_PKEY * pkey,int mode)94 int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode)
95 {
96 # ifndef OPENSSL_NO_DSA
97     if (pkey->type == EVP_PKEY_DSA) {
98         int ret = pkey->save_parameters;
99 
100         if (mode >= 0)
101             pkey->save_parameters = mode;
102         return ret;
103     }
104 # endif
105 # ifndef OPENSSL_NO_EC
106     if (pkey->type == EVP_PKEY_EC) {
107         int ret = pkey->save_parameters;
108 
109         if (mode >= 0)
110             pkey->save_parameters = mode;
111         return ret;
112     }
113 # endif
114     return 0;
115 }
116 
EVP_PKEY_set_ex_data(EVP_PKEY * key,int idx,void * arg)117 int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg)
118 {
119     return CRYPTO_set_ex_data(&key->ex_data, idx, arg);
120 }
121 
EVP_PKEY_get_ex_data(const EVP_PKEY * key,int idx)122 void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx)
123 {
124     return CRYPTO_get_ex_data(&key->ex_data, idx);
125 }
126 
EVP_PKEY_copy_parameters(EVP_PKEY * to,const EVP_PKEY * from)127 int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
128 {
129     /*
130      * Clean up legacy stuff from this function when legacy support is gone.
131      */
132 
133     EVP_PKEY *downgraded_from = NULL;
134     int ok = 0;
135 
136     /*
137      * If |to| is a legacy key and |from| isn't, we must make a downgraded
138      * copy of |from|.  If that fails, this function fails.
139      */
140     if (evp_pkey_is_legacy(to) && evp_pkey_is_provided(from)) {
141         if (!evp_pkey_copy_downgraded(&downgraded_from, from))
142             goto end;
143         from = downgraded_from;
144     }
145 
146     /*
147      * Make sure |to| is typed.  Content is less important at this early
148      * stage.
149      *
150      * 1.  If |to| is untyped, assign |from|'s key type to it.
151      * 2.  If |to| contains a legacy key, compare its |type| to |from|'s.
152      *     (|from| was already downgraded above)
153      *
154      * If |to| is a provided key, there's nothing more to do here, functions
155      * like evp_keymgmt_util_copy() and evp_pkey_export_to_provider() called
156      * further down help us find out if they are the same or not.
157      */
158     if (evp_pkey_is_blank(to)) {
159         if (evp_pkey_is_legacy(from)) {
160             if (EVP_PKEY_set_type(to, from->type) == 0)
161                 goto end;
162         } else {
163             if (EVP_PKEY_set_type_by_keymgmt(to, from->keymgmt) == 0)
164                 goto end;
165         }
166     } else if (evp_pkey_is_legacy(to)) {
167         if (to->type != from->type) {
168             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
169             goto end;
170         }
171     }
172 
173     if (EVP_PKEY_missing_parameters(from)) {
174         ERR_raise(ERR_LIB_EVP, EVP_R_MISSING_PARAMETERS);
175         goto end;
176     }
177 
178     if (!EVP_PKEY_missing_parameters(to)) {
179         if (EVP_PKEY_parameters_eq(to, from) == 1)
180             ok = 1;
181         else
182             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_PARAMETERS);
183         goto end;
184     }
185 
186     /* For purely provided keys, we just call the keymgmt utility */
187     if (to->keymgmt != NULL && from->keymgmt != NULL) {
188         ok = evp_keymgmt_util_copy(to, (EVP_PKEY *)from, SELECT_PARAMETERS);
189         goto end;
190     }
191 
192     /*
193      * If |to| is provided, we know that |from| is legacy at this point.
194      * Try exporting |from| to |to|'s keymgmt, then use evp_keymgmt_dup()
195      * to copy the appropriate data to |to|'s keydata.
196      * We cannot override existing data so do it only if there is no keydata
197      * in |to| yet.
198      */
199     if (to->keymgmt != NULL && to->keydata == NULL) {
200         EVP_KEYMGMT *to_keymgmt = to->keymgmt;
201         void *from_keydata =
202             evp_pkey_export_to_provider((EVP_PKEY *)from, NULL, &to_keymgmt,
203                                         NULL);
204 
205         /*
206          * If we get a NULL, it could be an internal error, or it could be
207          * that there's a key mismatch.  We're pretending the latter...
208          */
209         if (from_keydata == NULL)
210             ERR_raise(ERR_LIB_EVP, EVP_R_DIFFERENT_KEY_TYPES);
211         else
212             ok = (to->keydata = evp_keymgmt_dup(to->keymgmt,
213                                                 from_keydata,
214                                                 SELECT_PARAMETERS)) != NULL;
215         goto end;
216     }
217 
218     /* Both keys are legacy */
219     if (from->ameth != NULL && from->ameth->param_copy != NULL)
220         ok = from->ameth->param_copy(to, from);
221  end:
222     EVP_PKEY_free(downgraded_from);
223     return ok;
224 }
225 
EVP_PKEY_missing_parameters(const EVP_PKEY * pkey)226 int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey)
227 {
228     if (pkey != NULL) {
229         if (pkey->keymgmt != NULL)
230             return !evp_keymgmt_util_has((EVP_PKEY *)pkey, SELECT_PARAMETERS);
231         else if (pkey->ameth != NULL && pkey->ameth->param_missing != NULL)
232             return pkey->ameth->param_missing(pkey);
233     }
234     return 0;
235 }
236 
237 /*
238  * This function is called for any mixture of keys except pure legacy pair.
239  * When legacy keys are gone, we replace a call to this functions with
240  * a call to evp_keymgmt_util_match().
241  */
evp_pkey_cmp_any(const EVP_PKEY * a,const EVP_PKEY * b,int selection)242 static int evp_pkey_cmp_any(const EVP_PKEY *a, const EVP_PKEY *b,
243                             int selection)
244 {
245     EVP_KEYMGMT *keymgmt1 = NULL, *keymgmt2 = NULL;
246     void *keydata1 = NULL, *keydata2 = NULL, *tmp_keydata = NULL;
247 
248     /* If none of them are provided, this function shouldn't have been called */
249     if (!ossl_assert(evp_pkey_is_provided(a) || evp_pkey_is_provided(b)))
250         return -2;
251 
252     /* For purely provided keys, we just call the keymgmt utility */
253     if (evp_pkey_is_provided(a) && evp_pkey_is_provided(b))
254         return evp_keymgmt_util_match((EVP_PKEY *)a, (EVP_PKEY *)b, selection);
255 
256     /*
257      * At this point, one of them is provided, the other not.  This allows
258      * us to compare types using legacy NIDs.
259      */
260     if (evp_pkey_is_legacy(a)
261         && !EVP_KEYMGMT_is_a(b->keymgmt, OBJ_nid2sn(a->type)))
262         return -1;               /* not the same key type */
263     if (evp_pkey_is_legacy(b)
264         && !EVP_KEYMGMT_is_a(a->keymgmt, OBJ_nid2sn(b->type)))
265         return -1;               /* not the same key type */
266 
267     /*
268      * We've determined that they both are the same keytype, so the next
269      * step is to do a bit of cross export to ensure we have keydata for
270      * both keys in the same keymgmt.
271      */
272     keymgmt1 = a->keymgmt;
273     keydata1 = a->keydata;
274     keymgmt2 = b->keymgmt;
275     keydata2 = b->keydata;
276 
277     if (keymgmt2 != NULL && keymgmt2->match != NULL) {
278         tmp_keydata =
279             evp_pkey_export_to_provider((EVP_PKEY *)a, NULL, &keymgmt2, NULL);
280         if (tmp_keydata != NULL) {
281             keymgmt1 = keymgmt2;
282             keydata1 = tmp_keydata;
283         }
284     }
285     if (tmp_keydata == NULL && keymgmt1 != NULL && keymgmt1->match != NULL) {
286         tmp_keydata =
287             evp_pkey_export_to_provider((EVP_PKEY *)b, NULL, &keymgmt1, NULL);
288         if (tmp_keydata != NULL) {
289             keymgmt2 = keymgmt1;
290             keydata2 = tmp_keydata;
291         }
292     }
293 
294     /* If we still don't have matching keymgmt implementations, we give up */
295     if (keymgmt1 != keymgmt2)
296         return -2;
297 
298     /* If the keymgmt implementations are NULL, the export failed */
299     if (keymgmt1 == NULL)
300         return -2;
301 
302     return evp_keymgmt_match(keymgmt1, keydata1, keydata2, selection);
303 }
304 
305 # ifndef OPENSSL_NO_DEPRECATED_3_0
EVP_PKEY_cmp_parameters(const EVP_PKEY * a,const EVP_PKEY * b)306 int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
307 {
308     return EVP_PKEY_parameters_eq(a, b);
309 }
310 #endif
311 
EVP_PKEY_parameters_eq(const EVP_PKEY * a,const EVP_PKEY * b)312 int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b)
313 {
314     /*
315      * This will just call evp_keymgmt_util_match when legacy support
316      * is gone.
317      */
318 
319     if (a->keymgmt != NULL || b->keymgmt != NULL)
320         return evp_pkey_cmp_any(a, b, SELECT_PARAMETERS);
321 
322     /* All legacy keys */
323     if (a->type != b->type)
324         return -1;
325     if (a->ameth != NULL && a->ameth->param_cmp != NULL)
326         return a->ameth->param_cmp(a, b);
327     return -2;
328 }
329 
330 # ifndef OPENSSL_NO_DEPRECATED_3_0
EVP_PKEY_cmp(const EVP_PKEY * a,const EVP_PKEY * b)331 int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
332 {
333     return EVP_PKEY_eq(a, b);
334 }
335 #endif
336 
EVP_PKEY_eq(const EVP_PKEY * a,const EVP_PKEY * b)337 int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b)
338 {
339     /*
340      * This will just call evp_keymgmt_util_match when legacy support
341      * is gone.
342      */
343 
344     /* Trivial shortcuts */
345     if (a == b)
346         return 1;
347     if (a == NULL || b == NULL)
348         return 0;
349 
350     if (a->keymgmt != NULL || b->keymgmt != NULL) {
351         int selection = SELECT_PARAMETERS;
352 
353         if (evp_keymgmt_util_has((EVP_PKEY *)a, OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
354             && evp_keymgmt_util_has((EVP_PKEY *)b, OSSL_KEYMGMT_SELECT_PUBLIC_KEY))
355             selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
356         else
357             selection |= OSSL_KEYMGMT_SELECT_KEYPAIR;
358         return evp_pkey_cmp_any(a, b, selection);
359     }
360 
361     /* All legacy keys */
362     if (a->type != b->type)
363         return -1;
364 
365     if (a->ameth != NULL) {
366         int ret;
367         /* Compare parameters if the algorithm has them */
368         if (a->ameth->param_cmp != NULL) {
369             ret = a->ameth->param_cmp(a, b);
370             if (ret <= 0)
371                 return ret;
372         }
373 
374         if (a->ameth->pub_cmp != NULL)
375             return a->ameth->pub_cmp(a, b);
376     }
377 
378     return -2;
379 }
380 
381 
new_raw_key_int(OSSL_LIB_CTX * libctx,const char * strtype,const char * propq,int nidtype,ENGINE * e,const unsigned char * key,size_t len,int key_is_priv)382 static EVP_PKEY *new_raw_key_int(OSSL_LIB_CTX *libctx,
383                                  const char *strtype,
384                                  const char *propq,
385                                  int nidtype,
386                                  ENGINE *e,
387                                  const unsigned char *key,
388                                  size_t len,
389                                  int key_is_priv)
390 {
391     EVP_PKEY *pkey = NULL;
392     EVP_PKEY_CTX *ctx = NULL;
393     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
394     int result = 0;
395 
396 # ifndef OPENSSL_NO_ENGINE
397     /* Check if there is an Engine for this type */
398     if (e == NULL) {
399         ENGINE *tmpe = NULL;
400 
401         if (strtype != NULL)
402             ameth = EVP_PKEY_asn1_find_str(&tmpe, strtype, -1);
403         else if (nidtype != EVP_PKEY_NONE)
404             ameth = EVP_PKEY_asn1_find(&tmpe, nidtype);
405 
406         /* If tmpe is NULL then no engine is claiming to support this type */
407         if (tmpe == NULL)
408             ameth = NULL;
409 
410         ENGINE_finish(tmpe);
411     }
412 # endif
413 
414     if (e == NULL && ameth == NULL) {
415         /*
416          * No engine is claiming to support this type, so lets see if we have
417          * a provider.
418          */
419         ctx = EVP_PKEY_CTX_new_from_name(libctx,
420                                          strtype != NULL ? strtype
421                                                          : OBJ_nid2sn(nidtype),
422                                          propq);
423         if (ctx == NULL)
424             goto err;
425         /* May fail if no provider available */
426         ERR_set_mark();
427         if (EVP_PKEY_fromdata_init(ctx) == 1) {
428             OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
429 
430             ERR_clear_last_mark();
431             params[0] = OSSL_PARAM_construct_octet_string(
432                             key_is_priv ? OSSL_PKEY_PARAM_PRIV_KEY
433                                         : OSSL_PKEY_PARAM_PUB_KEY,
434                             (void *)key, len);
435 
436             if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) != 1) {
437                 ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
438                 goto err;
439             }
440 
441             EVP_PKEY_CTX_free(ctx);
442 
443             return pkey;
444         }
445         ERR_pop_to_mark();
446         /* else not supported so fallback to legacy */
447     }
448 
449     /* Legacy code path */
450 
451     pkey = EVP_PKEY_new();
452     if (pkey == NULL) {
453         ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
454         goto err;
455     }
456 
457     if (!pkey_set_type(pkey, e, nidtype, strtype, -1, NULL)) {
458         /* ERR_raise(ERR_LIB_EVP, ...) already called */
459         goto err;
460     }
461 
462     if (!ossl_assert(pkey->ameth != NULL))
463         goto err;
464 
465     if (key_is_priv) {
466         if (pkey->ameth->set_priv_key == NULL) {
467             ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
468             goto err;
469         }
470 
471         if (!pkey->ameth->set_priv_key(pkey, key, len)) {
472             ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
473             goto err;
474         }
475     } else {
476         if (pkey->ameth->set_pub_key == NULL) {
477             ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
478             goto err;
479         }
480 
481         if (!pkey->ameth->set_pub_key(pkey, key, len)) {
482             ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
483             goto err;
484         }
485     }
486 
487     result = 1;
488  err:
489     if (!result) {
490         EVP_PKEY_free(pkey);
491         pkey = NULL;
492     }
493     EVP_PKEY_CTX_free(ctx);
494     return pkey;
495 }
496 
EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX * libctx,const char * keytype,const char * propq,const unsigned char * priv,size_t len)497 EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx,
498                                           const char *keytype,
499                                           const char *propq,
500                                           const unsigned char *priv, size_t len)
501 {
502     return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, priv,
503                            len, 1);
504 }
505 
EVP_PKEY_new_raw_private_key(int type,ENGINE * e,const unsigned char * priv,size_t len)506 EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
507                                        const unsigned char *priv,
508                                        size_t len)
509 {
510     return new_raw_key_int(NULL, NULL, NULL, type, e, priv, len, 1);
511 }
512 
EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX * libctx,const char * keytype,const char * propq,const unsigned char * pub,size_t len)513 EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx,
514                                          const char *keytype, const char *propq,
515                                          const unsigned char *pub, size_t len)
516 {
517     return new_raw_key_int(libctx, keytype, propq, EVP_PKEY_NONE, NULL, pub,
518                            len, 0);
519 }
520 
EVP_PKEY_new_raw_public_key(int type,ENGINE * e,const unsigned char * pub,size_t len)521 EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
522                                       const unsigned char *pub,
523                                       size_t len)
524 {
525     return new_raw_key_int(NULL, NULL, NULL, type, e, pub, len, 0);
526 }
527 
528 struct raw_key_details_st
529 {
530     unsigned char **key;
531     size_t *len;
532     int selection;
533 };
534 
535 static OSSL_CALLBACK get_raw_key_details;
get_raw_key_details(const OSSL_PARAM params[],void * arg)536 static int get_raw_key_details(const OSSL_PARAM params[], void *arg)
537 {
538     const OSSL_PARAM *p = NULL;
539     struct raw_key_details_st *raw_key = arg;
540 
541     if (raw_key->selection == OSSL_KEYMGMT_SELECT_PRIVATE_KEY) {
542         if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY))
543                 != NULL)
544             return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
545                                                raw_key->key == NULL ? 0 : *raw_key->len,
546                                                raw_key->len);
547     } else if (raw_key->selection == OSSL_KEYMGMT_SELECT_PUBLIC_KEY) {
548         if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY))
549                 != NULL)
550             return OSSL_PARAM_get_octet_string(p, (void **)raw_key->key,
551                                                raw_key->key == NULL ? 0 : *raw_key->len,
552                                                raw_key->len);
553     }
554 
555     return 0;
556 }
557 
EVP_PKEY_get_raw_private_key(const EVP_PKEY * pkey,unsigned char * priv,size_t * len)558 int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
559                                  size_t *len)
560 {
561     if (pkey->keymgmt != NULL) {
562         struct raw_key_details_st raw_key;
563 
564         raw_key.key = priv == NULL ? NULL : &priv;
565         raw_key.len = len;
566         raw_key.selection = OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
567 
568         return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
569                                        get_raw_key_details, &raw_key);
570     }
571 
572     if (pkey->ameth == NULL) {
573         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
574         return 0;
575     }
576 
577     if (pkey->ameth->get_priv_key == NULL) {
578         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
579         return 0;
580     }
581 
582     if (!pkey->ameth->get_priv_key(pkey, priv, len)) {
583         ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
584         return 0;
585     }
586 
587     return 1;
588 }
589 
EVP_PKEY_get_raw_public_key(const EVP_PKEY * pkey,unsigned char * pub,size_t * len)590 int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
591                                 size_t *len)
592 {
593     if (pkey->keymgmt != NULL) {
594         struct raw_key_details_st raw_key;
595 
596         raw_key.key = pub == NULL ? NULL : &pub;
597         raw_key.len = len;
598         raw_key.selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
599 
600         return evp_keymgmt_util_export(pkey, OSSL_KEYMGMT_SELECT_PUBLIC_KEY,
601                                        get_raw_key_details, &raw_key);
602     }
603 
604     if (pkey->ameth == NULL) {
605         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
606         return 0;
607     }
608 
609      if (pkey->ameth->get_pub_key == NULL) {
610         ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
611         return 0;
612     }
613 
614     if (!pkey->ameth->get_pub_key(pkey, pub, len)) {
615         ERR_raise(ERR_LIB_EVP, EVP_R_GET_RAW_KEY_FAILED);
616         return 0;
617     }
618 
619     return 1;
620 }
621 
new_cmac_key_int(const unsigned char * priv,size_t len,const char * cipher_name,const EVP_CIPHER * cipher,OSSL_LIB_CTX * libctx,const char * propq,ENGINE * e)622 static EVP_PKEY *new_cmac_key_int(const unsigned char *priv, size_t len,
623                                   const char *cipher_name,
624                                   const EVP_CIPHER *cipher,
625                                   OSSL_LIB_CTX *libctx,
626                                   const char *propq, ENGINE *e)
627 {
628 # ifndef OPENSSL_NO_CMAC
629 #  ifndef OPENSSL_NO_ENGINE
630     const char *engine_id = e != NULL ? ENGINE_get_id(e) : NULL;
631 #  endif
632     OSSL_PARAM params[5], *p = params;
633     EVP_PKEY *pkey = NULL;
634     EVP_PKEY_CTX *ctx;
635 
636     if (cipher != NULL)
637         cipher_name = EVP_CIPHER_get0_name(cipher);
638 
639     if (cipher_name == NULL) {
640         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
641         return NULL;
642     }
643 
644     ctx = EVP_PKEY_CTX_new_from_name(libctx, "CMAC", propq);
645     if (ctx == NULL)
646         goto err;
647 
648     if (EVP_PKEY_fromdata_init(ctx) <= 0) {
649         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
650         goto err;
651     }
652 
653     *p++ = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PRIV_KEY,
654                                             (void *)priv, len);
655     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_CIPHER,
656                                             (char *)cipher_name, 0);
657     if (propq != NULL)
658         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_PROPERTIES,
659                                                 (char *)propq, 0);
660 #  ifndef OPENSSL_NO_ENGINE
661     if (engine_id != NULL)
662         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_ENGINE,
663                                                 (char *)engine_id, 0);
664 #  endif
665     *p = OSSL_PARAM_construct_end();
666 
667     if (EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEYPAIR, params) <= 0) {
668         ERR_raise(ERR_LIB_EVP, EVP_R_KEY_SETUP_FAILED);
669         goto err;
670     }
671 
672  err:
673     EVP_PKEY_CTX_free(ctx);
674 
675     return pkey;
676 # else
677     ERR_raise(ERR_LIB_EVP, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
678     return NULL;
679 # endif
680 }
681 
EVP_PKEY_new_CMAC_key(ENGINE * e,const unsigned char * priv,size_t len,const EVP_CIPHER * cipher)682 EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
683                                 size_t len, const EVP_CIPHER *cipher)
684 {
685     return new_cmac_key_int(priv, len, NULL, cipher, NULL, NULL, e);
686 }
687 
EVP_PKEY_set_type(EVP_PKEY * pkey,int type)688 int EVP_PKEY_set_type(EVP_PKEY *pkey, int type)
689 {
690     return pkey_set_type(pkey, NULL, type, NULL, -1, NULL);
691 }
692 
EVP_PKEY_set_type_str(EVP_PKEY * pkey,const char * str,int len)693 int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len)
694 {
695     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE, str, len, NULL);
696 }
697 
698 # ifndef OPENSSL_NO_ENGINE
EVP_PKEY_set1_engine(EVP_PKEY * pkey,ENGINE * e)699 int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e)
700 {
701     if (e != NULL) {
702         if (!ENGINE_init(e)) {
703             ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
704             return 0;
705         }
706         if (ENGINE_get_pkey_meth(e, pkey->type) == NULL) {
707             ENGINE_finish(e);
708             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
709             return 0;
710         }
711     }
712     ENGINE_finish(pkey->pmeth_engine);
713     pkey->pmeth_engine = e;
714     return 1;
715 }
716 
EVP_PKEY_get0_engine(const EVP_PKEY * pkey)717 ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey)
718 {
719     return pkey->engine;
720 }
721 # endif
722 
723 # ifndef OPENSSL_NO_DEPRECATED_3_0
detect_foreign_key(EVP_PKEY * pkey)724 static void detect_foreign_key(EVP_PKEY *pkey)
725 {
726     switch (pkey->type) {
727     case EVP_PKEY_RSA:
728     case EVP_PKEY_RSA_PSS:
729         pkey->foreign = pkey->pkey.rsa != NULL
730                         && ossl_rsa_is_foreign(pkey->pkey.rsa);
731         break;
732 #  ifndef OPENSSL_NO_EC
733     case EVP_PKEY_SM2:
734         break;
735     case EVP_PKEY_EC:
736         pkey->foreign = pkey->pkey.ec != NULL
737                         && ossl_ec_key_is_foreign(pkey->pkey.ec);
738         break;
739 #  endif
740 #  ifndef OPENSSL_NO_DSA
741     case EVP_PKEY_DSA:
742         pkey->foreign = pkey->pkey.dsa != NULL
743                         && ossl_dsa_is_foreign(pkey->pkey.dsa);
744         break;
745 #endif
746 #  ifndef OPENSSL_NO_DH
747     case EVP_PKEY_DH:
748         pkey->foreign = pkey->pkey.dh != NULL
749                         && ossl_dh_is_foreign(pkey->pkey.dh);
750         break;
751 #endif
752     default:
753         pkey->foreign = 0;
754         break;
755     }
756 }
757 
EVP_PKEY_assign(EVP_PKEY * pkey,int type,void * key)758 int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key)
759 {
760 #  ifndef OPENSSL_NO_EC
761     int pktype;
762 
763     pktype = EVP_PKEY_type(type);
764     if ((key != NULL) && (pktype == EVP_PKEY_EC || pktype == EVP_PKEY_SM2)) {
765         const EC_GROUP *group = EC_KEY_get0_group(key);
766 
767         if (group != NULL) {
768             int curve = EC_GROUP_get_curve_name(group);
769 
770             /*
771              * Regardless of what is requested the SM2 curve must be SM2 type,
772              * and non SM2 curves are EC type.
773              */
774             if (curve == NID_sm2 && pktype == EVP_PKEY_EC)
775                 type = EVP_PKEY_SM2;
776             else if(curve != NID_sm2 && pktype == EVP_PKEY_SM2)
777                 type = EVP_PKEY_EC;
778         }
779     }
780 #  endif
781 
782     if (pkey == NULL || !EVP_PKEY_set_type(pkey, type))
783         return 0;
784 
785     pkey->pkey.ptr = key;
786     detect_foreign_key(pkey);
787 
788     return (key != NULL);
789 }
790 # endif
791 
EVP_PKEY_get0(const EVP_PKEY * pkey)792 void *EVP_PKEY_get0(const EVP_PKEY *pkey)
793 {
794     if (pkey == NULL)
795         return NULL;
796 
797     if (!evp_pkey_is_provided(pkey))
798         return pkey->pkey.ptr;
799 
800     return NULL;
801 }
802 
EVP_PKEY_get0_hmac(const EVP_PKEY * pkey,size_t * len)803 const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len)
804 {
805     const ASN1_OCTET_STRING *os = NULL;
806     if (pkey->type != EVP_PKEY_HMAC) {
807         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_AN_HMAC_KEY);
808         return NULL;
809     }
810     os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
811     if (os != NULL) {
812         *len = os->length;
813         return os->data;
814     }
815     return NULL;
816 }
817 
818 # ifndef OPENSSL_NO_POLY1305
EVP_PKEY_get0_poly1305(const EVP_PKEY * pkey,size_t * len)819 const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len)
820 {
821     const ASN1_OCTET_STRING *os = NULL;
822     if (pkey->type != EVP_PKEY_POLY1305) {
823         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_POLY1305_KEY);
824         return NULL;
825     }
826     os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
827     if (os != NULL) {
828         *len = os->length;
829         return os->data;
830     }
831     return NULL;
832 }
833 # endif
834 
835 # ifndef OPENSSL_NO_SIPHASH
EVP_PKEY_get0_siphash(const EVP_PKEY * pkey,size_t * len)836 const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len)
837 {
838     const ASN1_OCTET_STRING *os = NULL;
839 
840     if (pkey->type != EVP_PKEY_SIPHASH) {
841         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_SIPHASH_KEY);
842         return NULL;
843     }
844     os = evp_pkey_get_legacy((EVP_PKEY *)pkey);
845     if (os != NULL) {
846         *len = os->length;
847         return os->data;
848     }
849     return NULL;
850 }
851 # endif
852 
853 # ifndef OPENSSL_NO_DSA
evp_pkey_get0_DSA_int(const EVP_PKEY * pkey)854 static DSA *evp_pkey_get0_DSA_int(const EVP_PKEY *pkey)
855 {
856     if (pkey->type != EVP_PKEY_DSA) {
857         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DSA_KEY);
858         return NULL;
859     }
860     return evp_pkey_get_legacy((EVP_PKEY *)pkey);
861 }
862 
EVP_PKEY_get0_DSA(const EVP_PKEY * pkey)863 const DSA *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey)
864 {
865     return evp_pkey_get0_DSA_int(pkey);
866 }
867 
EVP_PKEY_set1_DSA(EVP_PKEY * pkey,DSA * key)868 int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
869 {
870     int ret = EVP_PKEY_assign_DSA(pkey, key);
871     if (ret)
872         DSA_up_ref(key);
873     return ret;
874 }
EVP_PKEY_get1_DSA(EVP_PKEY * pkey)875 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
876 {
877     DSA *ret = evp_pkey_get0_DSA_int(pkey);
878 
879     if (ret != NULL)
880         DSA_up_ref(ret);
881     return ret;
882 }
883 # endif /*  OPENSSL_NO_DSA */
884 
885 # ifndef OPENSSL_NO_ECX
evp_pkey_get0_ECX_KEY(const EVP_PKEY * pkey,int type)886 static const ECX_KEY *evp_pkey_get0_ECX_KEY(const EVP_PKEY *pkey, int type)
887 {
888     if (EVP_PKEY_get_base_id(pkey) != type) {
889         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_ECX_KEY);
890         return NULL;
891     }
892     return evp_pkey_get_legacy((EVP_PKEY *)pkey);
893 }
894 
evp_pkey_get1_ECX_KEY(EVP_PKEY * pkey,int type)895 static ECX_KEY *evp_pkey_get1_ECX_KEY(EVP_PKEY *pkey, int type)
896 {
897     ECX_KEY *ret = (ECX_KEY *)evp_pkey_get0_ECX_KEY(pkey, type);
898 
899     if (ret != NULL && !ossl_ecx_key_up_ref(ret))
900         ret = NULL;
901     return ret;
902 }
903 
904 #  define IMPLEMENT_ECX_VARIANT(NAME)                                   \
905     ECX_KEY *ossl_evp_pkey_get1_##NAME(EVP_PKEY *pkey)                  \
906     {                                                                   \
907         return evp_pkey_get1_ECX_KEY(pkey, EVP_PKEY_##NAME);            \
908     }
909 IMPLEMENT_ECX_VARIANT(X25519)
IMPLEMENT_ECX_VARIANT(X448)910 IMPLEMENT_ECX_VARIANT(X448)
911 IMPLEMENT_ECX_VARIANT(ED25519)
912 IMPLEMENT_ECX_VARIANT(ED448)
913 
914 # endif /* OPENSSL_NO_ECX */
915 
916 # if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0)
917 
918 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, DH *dhkey)
919 {
920     int ret, type;
921 
922     /*
923      * ossl_dh_is_named_safe_prime_group() returns 1 for named safe prime groups
924      * related to ffdhe and modp (which cache q = (p - 1) / 2),
925      * and returns 0 for all other dh parameter generation types including
926      * RFC5114 named groups.
927      *
928      * The EVP_PKEY_DH type is used for dh parameter generation types:
929      *  - named safe prime groups related to ffdhe and modp
930      *  - safe prime generator
931      *
932      * The type EVP_PKEY_DHX is used for dh parameter generation types
933      *  - fips186-4 and fips186-2
934      *  - rfc5114 named groups.
935      *
936      * The EVP_PKEY_DH type is used to save PKCS#3 data than can be stored
937      * without a q value.
938      * The EVP_PKEY_DHX type is used to save X9.42 data that requires the
939      * q value to be stored.
940      */
941     if (ossl_dh_is_named_safe_prime_group(dhkey))
942         type = EVP_PKEY_DH;
943     else
944         type = DH_get0_q(dhkey) == NULL ? EVP_PKEY_DH : EVP_PKEY_DHX;
945 
946     ret = EVP_PKEY_assign(pkey, type, dhkey);
947 
948     if (ret)
949         DH_up_ref(dhkey);
950     return ret;
951 }
952 
evp_pkey_get0_DH_int(const EVP_PKEY * pkey)953 DH *evp_pkey_get0_DH_int(const EVP_PKEY *pkey)
954 {
955     if (pkey->type != EVP_PKEY_DH && pkey->type != EVP_PKEY_DHX) {
956         ERR_raise(ERR_LIB_EVP, EVP_R_EXPECTING_A_DH_KEY);
957         return NULL;
958     }
959     return evp_pkey_get_legacy((EVP_PKEY *)pkey);
960 }
961 
EVP_PKEY_get0_DH(const EVP_PKEY * pkey)962 const DH *EVP_PKEY_get0_DH(const EVP_PKEY *pkey)
963 {
964     return evp_pkey_get0_DH_int(pkey);
965 }
966 
EVP_PKEY_get1_DH(EVP_PKEY * pkey)967 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey)
968 {
969     DH *ret = evp_pkey_get0_DH_int(pkey);
970 
971     if (ret != NULL)
972         DH_up_ref(ret);
973     return ret;
974 }
975 # endif
976 
EVP_PKEY_type(int type)977 int EVP_PKEY_type(int type)
978 {
979     int ret;
980     const EVP_PKEY_ASN1_METHOD *ameth;
981     ENGINE *e;
982     ameth = EVP_PKEY_asn1_find(&e, type);
983     if (ameth)
984         ret = ameth->pkey_id;
985     else
986         ret = NID_undef;
987 # ifndef OPENSSL_NO_ENGINE
988     ENGINE_finish(e);
989 # endif
990     return ret;
991 }
992 
EVP_PKEY_get_id(const EVP_PKEY * pkey)993 int EVP_PKEY_get_id(const EVP_PKEY *pkey)
994 {
995     return pkey->type;
996 }
997 
EVP_PKEY_get_base_id(const EVP_PKEY * pkey)998 int EVP_PKEY_get_base_id(const EVP_PKEY *pkey)
999 {
1000     return EVP_PKEY_type(pkey->type);
1001 }
1002 
1003 /*
1004  * These hard coded cases are pure hackery to get around the fact
1005  * that names in crypto/objects/objects.txt are a mess.  There is
1006  * no "EC", and "RSA" leads to the NID for 2.5.8.1.1, an OID that's
1007  * fallen out in favor of { pkcs-1 1 }, i.e. 1.2.840.113549.1.1.1,
1008  * the NID of which is used for EVP_PKEY_RSA.  Strangely enough,
1009  * "DSA" is accurate...  but still, better be safe and hard-code
1010  * names that we know.
1011  * On a similar topic, EVP_PKEY_type(EVP_PKEY_SM2) will result in
1012  * EVP_PKEY_EC, because of aliasing.
1013  * This should be cleaned away along with all other #legacy support.
1014  */
1015 static const OSSL_ITEM standard_name2type[] = {
1016     { EVP_PKEY_RSA,     "RSA" },
1017     { EVP_PKEY_RSA_PSS, "RSA-PSS" },
1018     { EVP_PKEY_EC,      "EC" },
1019     { EVP_PKEY_ED25519, "ED25519" },
1020     { EVP_PKEY_ED448,   "ED448" },
1021     { EVP_PKEY_X25519,  "X25519" },
1022     { EVP_PKEY_X448,    "X448" },
1023     { EVP_PKEY_SM2,     "SM2" },
1024     { EVP_PKEY_DH,      "DH" },
1025     { EVP_PKEY_DHX,     "X9.42 DH" },
1026     { EVP_PKEY_DHX,     "DHX" },
1027     { EVP_PKEY_DSA,     "DSA" },
1028 };
1029 
evp_pkey_name2type(const char * name)1030 int evp_pkey_name2type(const char *name)
1031 {
1032     int type;
1033     size_t i;
1034 
1035     for (i = 0; i < OSSL_NELEM(standard_name2type); i++) {
1036         if (OPENSSL_strcasecmp(name, standard_name2type[i].ptr) == 0)
1037             return (int)standard_name2type[i].id;
1038     }
1039 
1040     if ((type = EVP_PKEY_type(OBJ_sn2nid(name))) != NID_undef)
1041         return type;
1042     return EVP_PKEY_type(OBJ_ln2nid(name));
1043 }
1044 
evp_pkey_type2name(int type)1045 const char *evp_pkey_type2name(int type)
1046 {
1047     size_t i;
1048 
1049     for (i = 0; i < OSSL_NELEM(standard_name2type); i++) {
1050         if (type == (int)standard_name2type[i].id)
1051             return standard_name2type[i].ptr;
1052     }
1053 
1054     return OBJ_nid2sn(type);
1055 }
1056 
EVP_PKEY_is_a(const EVP_PKEY * pkey,const char * name)1057 int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name)
1058 {
1059     if (pkey == NULL)
1060         return 0;
1061     if (pkey->keymgmt == NULL)
1062         return pkey->type == evp_pkey_name2type(name);
1063     return EVP_KEYMGMT_is_a(pkey->keymgmt, name);
1064 }
1065 
EVP_PKEY_type_names_do_all(const EVP_PKEY * pkey,void (* fn)(const char * name,void * data),void * data)1066 int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey,
1067                                void (*fn)(const char *name, void *data),
1068                                void *data)
1069 {
1070     if (!evp_pkey_is_typed(pkey))
1071         return 0;
1072 
1073     if (!evp_pkey_is_provided(pkey)) {
1074         const char *name = OBJ_nid2sn(EVP_PKEY_get_id(pkey));
1075 
1076         fn(name, data);
1077         return 1;
1078     }
1079     return EVP_KEYMGMT_names_do_all(pkey->keymgmt, fn, data);
1080 }
1081 
EVP_PKEY_can_sign(const EVP_PKEY * pkey)1082 int EVP_PKEY_can_sign(const EVP_PKEY *pkey)
1083 {
1084     if (pkey->keymgmt == NULL) {
1085         switch (EVP_PKEY_get_base_id(pkey)) {
1086         case EVP_PKEY_RSA:
1087         case EVP_PKEY_RSA_PSS:
1088             return 1;
1089 # ifndef OPENSSL_NO_DSA
1090         case EVP_PKEY_DSA:
1091             return 1;
1092 # endif
1093 # ifndef OPENSSL_NO_EC
1094         case EVP_PKEY_ED25519:
1095         case EVP_PKEY_ED448:
1096             return 1;
1097         case EVP_PKEY_EC:        /* Including SM2 */
1098             return EC_KEY_can_sign(pkey->pkey.ec);
1099 # endif
1100         default:
1101             break;
1102         }
1103     } else {
1104         const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt);
1105         OSSL_LIB_CTX *libctx = ossl_provider_libctx(prov);
1106         const char *supported_sig =
1107             pkey->keymgmt->query_operation_name != NULL
1108             ? pkey->keymgmt->query_operation_name(OSSL_OP_SIGNATURE)
1109             : EVP_KEYMGMT_get0_name(pkey->keymgmt);
1110         EVP_SIGNATURE *signature = NULL;
1111 
1112         signature = EVP_SIGNATURE_fetch(libctx, supported_sig, NULL);
1113         if (signature != NULL) {
1114             EVP_SIGNATURE_free(signature);
1115             return 1;
1116         }
1117     }
1118     return 0;
1119 }
1120 
print_reset_indent(BIO ** out,int pop_f_prefix,long saved_indent)1121 static int print_reset_indent(BIO **out, int pop_f_prefix, long saved_indent)
1122 {
1123     BIO_set_indent(*out, saved_indent);
1124     if (pop_f_prefix) {
1125         BIO *next = BIO_pop(*out);
1126 
1127         BIO_free(*out);
1128         *out = next;
1129     }
1130     return 1;
1131 }
1132 
print_set_indent(BIO ** out,int * pop_f_prefix,long * saved_indent,long indent)1133 static int print_set_indent(BIO **out, int *pop_f_prefix, long *saved_indent,
1134                             long indent)
1135 {
1136     *pop_f_prefix = 0;
1137     *saved_indent = 0;
1138     if (indent > 0) {
1139         long i = BIO_get_indent(*out);
1140 
1141         *saved_indent =  (i < 0 ? 0 : i);
1142         if (BIO_set_indent(*out, indent) <= 0) {
1143             BIO *prefbio = BIO_new(BIO_f_prefix());
1144 
1145             if (prefbio == NULL)
1146                 return 0;
1147             *out = BIO_push(prefbio, *out);
1148             *pop_f_prefix = 1;
1149         }
1150         if (BIO_set_indent(*out, indent) <= 0) {
1151             print_reset_indent(out, *pop_f_prefix, *saved_indent);
1152             return 0;
1153         }
1154     }
1155     return 1;
1156 }
1157 
unsup_alg(BIO * out,const EVP_PKEY * pkey,int indent,const char * kstr)1158 static int unsup_alg(BIO *out, const EVP_PKEY *pkey, int indent,
1159                      const char *kstr)
1160 {
1161     return BIO_indent(out, indent, 128)
1162         && BIO_printf(out, "%s algorithm \"%s\" unsupported\n",
1163                       kstr, OBJ_nid2ln(pkey->type)) > 0;
1164 }
1165 
print_pkey(const EVP_PKEY * pkey,BIO * out,int indent,int selection,const char * propquery,int (* legacy_print)(BIO * out,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx),ASN1_PCTX * legacy_pctx)1166 static int print_pkey(const EVP_PKEY *pkey, BIO *out, int indent,
1167                       int selection /* For provided encoding */,
1168                       const char *propquery /* For provided encoding */,
1169                       int (*legacy_print)(BIO *out, const EVP_PKEY *pkey,
1170                                           int indent, ASN1_PCTX *pctx),
1171                       ASN1_PCTX *legacy_pctx /* For legacy print */)
1172 {
1173     int pop_f_prefix;
1174     long saved_indent;
1175     OSSL_ENCODER_CTX *ctx = NULL;
1176     int ret = -2;                /* default to unsupported */
1177 
1178     if (!print_set_indent(&out, &pop_f_prefix, &saved_indent, indent))
1179         return 0;
1180 
1181     ctx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "TEXT", NULL,
1182                                         propquery);
1183     if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0)
1184         ret = OSSL_ENCODER_to_bio(ctx, out);
1185     OSSL_ENCODER_CTX_free(ctx);
1186 
1187     if (ret != -2)
1188         goto end;
1189 
1190     /* legacy fallback */
1191     if (legacy_print != NULL)
1192         ret = legacy_print(out, pkey, 0, legacy_pctx);
1193     else
1194         ret = unsup_alg(out, pkey, 0, "Public Key");
1195 
1196  end:
1197     print_reset_indent(&out, pop_f_prefix, saved_indent);
1198     return ret;
1199 }
1200 
EVP_PKEY_print_public(BIO * out,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1201 int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
1202                           int indent, ASN1_PCTX *pctx)
1203 {
1204     return print_pkey(pkey, out, indent, EVP_PKEY_PUBLIC_KEY, NULL,
1205                       (pkey->ameth != NULL ? pkey->ameth->pub_print : NULL),
1206                       pctx);
1207 }
1208 
EVP_PKEY_print_private(BIO * out,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1209 int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
1210                            int indent, ASN1_PCTX *pctx)
1211 {
1212     return print_pkey(pkey, out, indent, EVP_PKEY_PRIVATE_KEY, NULL,
1213                       (pkey->ameth != NULL ? pkey->ameth->priv_print : NULL),
1214                       pctx);
1215 }
1216 
EVP_PKEY_print_params(BIO * out,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1217 int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
1218                           int indent, ASN1_PCTX *pctx)
1219 {
1220     return print_pkey(pkey, out, indent, EVP_PKEY_KEY_PARAMETERS, NULL,
1221                       (pkey->ameth != NULL ? pkey->ameth->param_print : NULL),
1222                       pctx);
1223 }
1224 
1225 # ifndef OPENSSL_NO_STDIO
EVP_PKEY_print_public_fp(FILE * fp,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1226 int EVP_PKEY_print_public_fp(FILE *fp, const EVP_PKEY *pkey,
1227                              int indent, ASN1_PCTX *pctx)
1228 {
1229     int ret;
1230     BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
1231 
1232     if (b == NULL)
1233         return 0;
1234     ret = EVP_PKEY_print_public(b, pkey, indent, pctx);
1235     BIO_free(b);
1236     return ret;
1237 }
1238 
EVP_PKEY_print_private_fp(FILE * fp,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1239 int EVP_PKEY_print_private_fp(FILE *fp, const EVP_PKEY *pkey,
1240                               int indent, ASN1_PCTX *pctx)
1241 {
1242     int ret;
1243     BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
1244 
1245     if (b == NULL)
1246         return 0;
1247     ret = EVP_PKEY_print_private(b, pkey, indent, pctx);
1248     BIO_free(b);
1249     return ret;
1250 }
1251 
EVP_PKEY_print_params_fp(FILE * fp,const EVP_PKEY * pkey,int indent,ASN1_PCTX * pctx)1252 int EVP_PKEY_print_params_fp(FILE *fp, const EVP_PKEY *pkey,
1253                              int indent, ASN1_PCTX *pctx)
1254 {
1255     int ret;
1256     BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
1257 
1258     if (b == NULL)
1259         return 0;
1260     ret = EVP_PKEY_print_params(b, pkey, indent, pctx);
1261     BIO_free(b);
1262     return ret;
1263 }
1264 # endif
1265 
mdname2nid(const char * mdname,void * data)1266 static void mdname2nid(const char *mdname, void *data)
1267 {
1268     int *nid = (int *)data;
1269 
1270     if (*nid != NID_undef)
1271         return;
1272 
1273     *nid = OBJ_sn2nid(mdname);
1274     if (*nid == NID_undef)
1275         *nid = OBJ_ln2nid(mdname);
1276 }
1277 
legacy_asn1_ctrl_to_param(EVP_PKEY * pkey,int op,int arg1,void * arg2)1278 static int legacy_asn1_ctrl_to_param(EVP_PKEY *pkey, int op,
1279                                      int arg1, void *arg2)
1280 {
1281     if (pkey->keymgmt == NULL)
1282         return 0;
1283     switch (op) {
1284     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
1285         {
1286             char mdname[80] = "";
1287             int rv = EVP_PKEY_get_default_digest_name(pkey, mdname,
1288                                                       sizeof(mdname));
1289 
1290             if (rv > 0) {
1291                 int mdnum;
1292                 OSSL_LIB_CTX *libctx = ossl_provider_libctx(pkey->keymgmt->prov);
1293                 /* Make sure the MD is in the namemap if available */
1294                 EVP_MD *md;
1295                 OSSL_NAMEMAP *namemap;
1296                 int nid = NID_undef;
1297 
1298                 (void)ERR_set_mark();
1299                 md = EVP_MD_fetch(libctx, mdname, NULL);
1300                 (void)ERR_pop_to_mark();
1301                 namemap = ossl_namemap_stored(libctx);
1302 
1303                 /*
1304                  * The only reason to fetch the MD was to make sure it is in the
1305                  * namemap. We can immediately free it.
1306                  */
1307                 EVP_MD_free(md);
1308                 mdnum = ossl_namemap_name2num(namemap, mdname);
1309                 if (mdnum == 0)
1310                     return 0;
1311 
1312                 /*
1313                  * We have the namemap number - now we need to find the
1314                  * associated nid
1315                  */
1316                 if (!ossl_namemap_doall_names(namemap, mdnum, mdname2nid, &nid))
1317                     return 0;
1318                 *(int *)arg2 = nid;
1319             }
1320             return rv;
1321         }
1322     default:
1323         return -2;
1324     }
1325 }
1326 
evp_pkey_asn1_ctrl(EVP_PKEY * pkey,int op,int arg1,void * arg2)1327 static int evp_pkey_asn1_ctrl(EVP_PKEY *pkey, int op, int arg1, void *arg2)
1328 {
1329     if (pkey->ameth == NULL)
1330         return legacy_asn1_ctrl_to_param(pkey, op, arg1, arg2);
1331     if (pkey->ameth->pkey_ctrl == NULL)
1332         return -2;
1333     return pkey->ameth->pkey_ctrl(pkey, op, arg1, arg2);
1334 }
1335 
EVP_PKEY_get_default_digest_nid(EVP_PKEY * pkey,int * pnid)1336 int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid)
1337 {
1338     if (pkey == NULL)
1339         return 0;
1340     return evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_DEFAULT_MD_NID, 0, pnid);
1341 }
1342 
EVP_PKEY_get_default_digest_name(EVP_PKEY * pkey,char * mdname,size_t mdname_sz)1343 int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
1344                                      char *mdname, size_t mdname_sz)
1345 {
1346     if (pkey->ameth == NULL)
1347         return evp_keymgmt_util_get_deflt_digest_name(pkey->keymgmt,
1348                                                       pkey->keydata,
1349                                                       mdname, mdname_sz);
1350 
1351     {
1352         int nid = NID_undef;
1353         int rv = EVP_PKEY_get_default_digest_nid(pkey, &nid);
1354         const char *name = rv > 0 ? OBJ_nid2sn(nid) : NULL;
1355 
1356         if (rv > 0)
1357             OPENSSL_strlcpy(mdname, name, mdname_sz);
1358         return rv;
1359     }
1360 }
1361 
EVP_PKEY_get_group_name(const EVP_PKEY * pkey,char * gname,size_t gname_sz,size_t * gname_len)1362 int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *gname, size_t gname_sz,
1363                             size_t *gname_len)
1364 {
1365     return EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME,
1366                                           gname, gname_sz, gname_len);
1367 }
1368 
EVP_PKEY_digestsign_supports_digest(EVP_PKEY * pkey,OSSL_LIB_CTX * libctx,const char * name,const char * propq)1369 int EVP_PKEY_digestsign_supports_digest(EVP_PKEY *pkey, OSSL_LIB_CTX *libctx,
1370                                         const char *name, const char *propq)
1371 {
1372     int rv;
1373     EVP_MD_CTX *ctx = NULL;
1374 
1375     if ((ctx = EVP_MD_CTX_new()) == NULL)
1376         return -1;
1377 
1378     ERR_set_mark();
1379     rv = EVP_DigestSignInit_ex(ctx, NULL, name, libctx,
1380                                propq, pkey, NULL);
1381     ERR_pop_to_mark();
1382 
1383     EVP_MD_CTX_free(ctx);
1384     return rv;
1385 }
1386 
EVP_PKEY_set1_encoded_public_key(EVP_PKEY * pkey,const unsigned char * pub,size_t publen)1387 int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey, const unsigned char *pub,
1388                                      size_t publen)
1389 {
1390     if (pkey == NULL)
1391         return 0;
1392     if (evp_pkey_is_provided(pkey))
1393         return
1394             EVP_PKEY_set_octet_string_param(pkey,
1395                                             OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1396                                             (unsigned char *)pub, publen);
1397 
1398     if (publen > INT_MAX)
1399         return 0;
1400     /* Historically this function was EVP_PKEY_set1_tls_encodedpoint */
1401     if (evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_SET1_TLS_ENCPT, publen,
1402                            (void *)pub) <= 0)
1403         return 0;
1404     return 1;
1405 }
1406 
EVP_PKEY_get1_encoded_public_key(EVP_PKEY * pkey,unsigned char ** ppub)1407 size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub)
1408 {
1409     int rv;
1410 
1411     if (pkey == NULL)
1412         return 0;
1413     if (evp_pkey_is_provided(pkey)) {
1414         size_t return_size = OSSL_PARAM_UNMODIFIED;
1415         unsigned char *buf;
1416 
1417         /*
1418          * We know that this is going to fail, but it will give us a size
1419          * to allocate.
1420          */
1421         EVP_PKEY_get_octet_string_param(pkey,
1422                                         OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1423                                         NULL, 0, &return_size);
1424         if (return_size == OSSL_PARAM_UNMODIFIED)
1425             return 0;
1426 
1427         *ppub = NULL;
1428         buf = OPENSSL_malloc(return_size);
1429         if (buf == NULL)
1430             return 0;
1431 
1432         if (!EVP_PKEY_get_octet_string_param(pkey,
1433                                              OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY,
1434                                              buf, return_size, NULL)) {
1435             OPENSSL_free(buf);
1436             return 0;
1437         }
1438         *ppub = buf;
1439         return return_size;
1440     }
1441 
1442 
1443     rv = evp_pkey_asn1_ctrl(pkey, ASN1_PKEY_CTRL_GET1_TLS_ENCPT, 0, ppub);
1444     if (rv <= 0)
1445         return 0;
1446     return rv;
1447 }
1448 
1449 #endif /* FIPS_MODULE */
1450 
1451 /*- All methods below can also be used in FIPS_MODULE */
1452 
EVP_PKEY_new(void)1453 EVP_PKEY *EVP_PKEY_new(void)
1454 {
1455     EVP_PKEY *ret = OPENSSL_zalloc(sizeof(*ret));
1456 
1457     if (ret == NULL)
1458         return NULL;
1459 
1460     ret->type = EVP_PKEY_NONE;
1461     ret->save_type = EVP_PKEY_NONE;
1462 
1463     if (!CRYPTO_NEW_REF(&ret->references, 1))
1464         goto err;
1465 
1466     ret->lock = CRYPTO_THREAD_lock_new();
1467     if (ret->lock == NULL) {
1468         ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB);
1469         goto err;
1470     }
1471 
1472 #ifndef FIPS_MODULE
1473     ret->save_parameters = 1;
1474     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, ret, &ret->ex_data)) {
1475         ERR_raise(ERR_LIB_EVP, ERR_R_CRYPTO_LIB);
1476         goto err;
1477     }
1478 #endif
1479     return ret;
1480 
1481  err:
1482     CRYPTO_FREE_REF(&ret->references);
1483     CRYPTO_THREAD_lock_free(ret->lock);
1484     OPENSSL_free(ret);
1485     return NULL;
1486 }
1487 
1488 /*
1489  * Setup a public key management method.
1490  *
1491  * For legacy keys, either |type| or |str| is expected to have the type
1492  * information.  In this case, the setup consists of finding an ASN1 method
1493  * and potentially an ENGINE, and setting those fields in |pkey|.
1494  *
1495  * For provider side keys, |keymgmt| is expected to be non-NULL.  In this
1496  * case, the setup consists of setting the |keymgmt| field in |pkey|.
1497  *
1498  * If pkey is NULL just return 1 or 0 if the key management method exists.
1499  */
1500 
pkey_set_type(EVP_PKEY * pkey,ENGINE * e,int type,const char * str,int len,EVP_KEYMGMT * keymgmt)1501 static int pkey_set_type(EVP_PKEY *pkey, ENGINE *e, int type, const char *str,
1502                          int len, EVP_KEYMGMT *keymgmt)
1503 {
1504 #ifndef FIPS_MODULE
1505     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
1506     ENGINE **eptr = (e == NULL) ? &e :  NULL;
1507 #endif
1508 
1509     /*
1510      * The setups can't set both legacy and provider side methods.
1511      * It is forbidden
1512      */
1513     if (!ossl_assert(type == EVP_PKEY_NONE || keymgmt == NULL)
1514         || !ossl_assert(e == NULL || keymgmt == NULL)) {
1515         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1516         return 0;
1517     }
1518 
1519     if (pkey != NULL) {
1520         int free_it = 0;
1521 
1522 #ifndef FIPS_MODULE
1523         free_it = free_it || pkey->pkey.ptr != NULL;
1524 #endif
1525         free_it = free_it || pkey->keydata != NULL;
1526         if (free_it)
1527             evp_pkey_free_it(pkey);
1528 #ifndef FIPS_MODULE
1529         /*
1530          * If key type matches and a method exists then this lookup has
1531          * succeeded once so just indicate success.
1532          */
1533         if (pkey->type != EVP_PKEY_NONE
1534             && type == pkey->save_type
1535             && pkey->ameth != NULL)
1536             return 1;
1537 # ifndef OPENSSL_NO_ENGINE
1538         /* If we have ENGINEs release them */
1539         ENGINE_finish(pkey->engine);
1540         pkey->engine = NULL;
1541         ENGINE_finish(pkey->pmeth_engine);
1542         pkey->pmeth_engine = NULL;
1543 # endif
1544 #endif
1545     }
1546 #ifndef FIPS_MODULE
1547     if (str != NULL)
1548         ameth = EVP_PKEY_asn1_find_str(eptr, str, len);
1549     else if (type != EVP_PKEY_NONE)
1550         ameth = EVP_PKEY_asn1_find(eptr, type);
1551 # ifndef OPENSSL_NO_ENGINE
1552     if (pkey == NULL && eptr != NULL)
1553         ENGINE_finish(e);
1554 # endif
1555 #endif
1556 
1557 
1558     {
1559         int check = 1;
1560 
1561 #ifndef FIPS_MODULE
1562         check = check && ameth == NULL;
1563 #endif
1564         check = check && keymgmt == NULL;
1565         if (check) {
1566             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_ALGORITHM);
1567             return 0;
1568         }
1569     }
1570     if (pkey != NULL) {
1571         if (keymgmt != NULL && !EVP_KEYMGMT_up_ref(keymgmt)) {
1572             ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1573             return 0;
1574         }
1575 
1576         pkey->keymgmt = keymgmt;
1577 
1578         pkey->save_type = type;
1579         pkey->type = type;
1580 
1581 #ifndef FIPS_MODULE
1582         /*
1583          * If the internal "origin" key is provider side, don't save |ameth|.
1584          * The main reason is that |ameth| is one factor to detect that the
1585          * internal "origin" key is a legacy one.
1586          */
1587         if (keymgmt == NULL)
1588             pkey->ameth = ameth;
1589 
1590         /*
1591          * The EVP_PKEY_ASN1_METHOD |pkey_id| retains its legacy key purpose
1592          * for any key type that has a legacy implementation, regardless of
1593          * if the internal key is a legacy or a provider side one.  When
1594          * there is no legacy implementation for the key, the type becomes
1595          * EVP_PKEY_KEYMGMT, which indicates that one should be cautious
1596          * with functions that expect legacy internal keys.
1597          */
1598         if (ameth != NULL) {
1599             if (type == EVP_PKEY_NONE)
1600                 pkey->type = ameth->pkey_id;
1601         } else {
1602             pkey->type = EVP_PKEY_KEYMGMT;
1603         }
1604 # ifndef OPENSSL_NO_ENGINE
1605         if (eptr == NULL && e != NULL && !ENGINE_init(e)) {
1606             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
1607             return 0;
1608         }
1609 # endif
1610         pkey->engine = e;
1611 #endif
1612     }
1613     return 1;
1614 }
1615 
1616 #ifndef FIPS_MODULE
find_ameth(const char * name,void * data)1617 static void find_ameth(const char *name, void *data)
1618 {
1619     const char **str = data;
1620 
1621     /*
1622      * The error messages from pkey_set_type() are uninteresting here,
1623      * and misleading.
1624      */
1625     ERR_set_mark();
1626 
1627     if (pkey_set_type(NULL, NULL, EVP_PKEY_NONE, name, strlen(name),
1628                       NULL)) {
1629         if (str[0] == NULL)
1630             str[0] = name;
1631         else if (str[1] == NULL)
1632             str[1] = name;
1633     }
1634 
1635     ERR_pop_to_mark();
1636 }
1637 #endif
1638 
EVP_PKEY_set_type_by_keymgmt(EVP_PKEY * pkey,EVP_KEYMGMT * keymgmt)1639 int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt)
1640 {
1641 #ifndef FIPS_MODULE
1642 # define EVP_PKEY_TYPE_STR str[0]
1643 # define EVP_PKEY_TYPE_STRLEN (str[0] == NULL ? -1 : (int)strlen(str[0]))
1644     /*
1645      * Find at most two strings that have an associated EVP_PKEY_ASN1_METHOD
1646      * Ideally, only one should be found.  If two (or more) are found, the
1647      * match is ambiguous.  This should never happen, but...
1648      */
1649     const char *str[2] = { NULL, NULL };
1650 
1651     if (!EVP_KEYMGMT_names_do_all(keymgmt, find_ameth, &str)
1652             || str[1] != NULL) {
1653         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1654         return 0;
1655     }
1656 #else
1657 # define EVP_PKEY_TYPE_STR NULL
1658 # define EVP_PKEY_TYPE_STRLEN -1
1659 #endif
1660     return pkey_set_type(pkey, NULL, EVP_PKEY_NONE,
1661                          EVP_PKEY_TYPE_STR, EVP_PKEY_TYPE_STRLEN,
1662                          keymgmt);
1663 
1664 #undef EVP_PKEY_TYPE_STR
1665 #undef EVP_PKEY_TYPE_STRLEN
1666 }
1667 
EVP_PKEY_up_ref(EVP_PKEY * pkey)1668 int EVP_PKEY_up_ref(EVP_PKEY *pkey)
1669 {
1670     int i;
1671 
1672     if (CRYPTO_UP_REF(&pkey->references, &i) <= 0)
1673         return 0;
1674 
1675     REF_PRINT_COUNT("EVP_PKEY", pkey);
1676     REF_ASSERT_ISNT(i < 2);
1677     return ((i > 1) ? 1 : 0);
1678 }
1679 
1680 #ifndef FIPS_MODULE
EVP_PKEY_dup(EVP_PKEY * pkey)1681 EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey)
1682 {
1683     EVP_PKEY *dup_pk;
1684 
1685     if (pkey == NULL) {
1686         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
1687         return NULL;
1688     }
1689 
1690     if ((dup_pk = EVP_PKEY_new()) == NULL)
1691         return NULL;
1692 
1693     if (evp_pkey_is_blank(pkey))
1694         goto done;
1695 
1696     if (evp_pkey_is_provided(pkey)) {
1697         if (!evp_keymgmt_util_copy(dup_pk, pkey,
1698                                    OSSL_KEYMGMT_SELECT_ALL))
1699             goto err;
1700         goto done;
1701     }
1702 
1703     if (evp_pkey_is_legacy(pkey)) {
1704         const EVP_PKEY_ASN1_METHOD *ameth = pkey->ameth;
1705 
1706         if (ameth == NULL || ameth->copy == NULL) {
1707             if (pkey->pkey.ptr == NULL /* empty key, just set type */
1708                 && EVP_PKEY_set_type(dup_pk, pkey->type) != 0)
1709                 goto done;
1710             ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEY_TYPE);
1711             goto err;
1712         }
1713         if (!ameth->copy(dup_pk, pkey))
1714             goto err;
1715         goto done;
1716     }
1717 
1718     goto err;
1719 done:
1720     /* copy auxiliary data */
1721     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EVP_PKEY,
1722                             &dup_pk->ex_data, &pkey->ex_data))
1723         goto err;
1724 
1725     if (pkey->attributes != NULL) {
1726         if ((dup_pk->attributes = ossl_x509at_dup(pkey->attributes)) == NULL)
1727             goto err;
1728     }
1729     return dup_pk;
1730 err:
1731     EVP_PKEY_free(dup_pk);
1732     return NULL;
1733 }
1734 
evp_pkey_free_legacy(EVP_PKEY * x)1735 void evp_pkey_free_legacy(EVP_PKEY *x)
1736 {
1737     const EVP_PKEY_ASN1_METHOD *ameth = x->ameth;
1738     ENGINE *tmpe = NULL;
1739 
1740     if (ameth == NULL && x->legacy_cache_pkey.ptr != NULL)
1741         ameth = EVP_PKEY_asn1_find(&tmpe, x->type);
1742 
1743     if (ameth != NULL) {
1744         if (x->legacy_cache_pkey.ptr != NULL) {
1745             /*
1746              * We should never have both a legacy origin key, and a key in the
1747              * legacy cache.
1748              */
1749             assert(x->pkey.ptr == NULL);
1750             /*
1751              * For the purposes of freeing we make the legacy cache look like
1752              * a legacy origin key.
1753              */
1754             x->pkey = x->legacy_cache_pkey;
1755             x->legacy_cache_pkey.ptr = NULL;
1756         }
1757         if (ameth->pkey_free != NULL)
1758             ameth->pkey_free(x);
1759         x->pkey.ptr = NULL;
1760     }
1761 # ifndef OPENSSL_NO_ENGINE
1762     ENGINE_finish(tmpe);
1763     ENGINE_finish(x->engine);
1764     x->engine = NULL;
1765     ENGINE_finish(x->pmeth_engine);
1766     x->pmeth_engine = NULL;
1767 # endif
1768 }
1769 #endif  /* FIPS_MODULE */
1770 
evp_pkey_free_it(EVP_PKEY * x)1771 static void evp_pkey_free_it(EVP_PKEY *x)
1772 {
1773     /* internal function; x is never NULL */
1774     evp_keymgmt_util_clear_operation_cache(x);
1775 #ifndef FIPS_MODULE
1776     evp_pkey_free_legacy(x);
1777 #endif
1778 
1779     if (x->keymgmt != NULL) {
1780         evp_keymgmt_freedata(x->keymgmt, x->keydata);
1781         EVP_KEYMGMT_free(x->keymgmt);
1782         x->keymgmt = NULL;
1783         x->keydata = NULL;
1784     }
1785     x->type = EVP_PKEY_NONE;
1786 }
1787 
EVP_PKEY_free(EVP_PKEY * x)1788 void EVP_PKEY_free(EVP_PKEY *x)
1789 {
1790     int i;
1791 
1792     if (x == NULL)
1793         return;
1794 
1795     CRYPTO_DOWN_REF(&x->references, &i);
1796     REF_PRINT_COUNT("EVP_PKEY", x);
1797     if (i > 0)
1798         return;
1799     REF_ASSERT_ISNT(i < 0);
1800     evp_pkey_free_it(x);
1801 #ifndef FIPS_MODULE
1802     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EVP_PKEY, x, &x->ex_data);
1803 #endif
1804     CRYPTO_THREAD_lock_free(x->lock);
1805     CRYPTO_FREE_REF(&x->references);
1806 #ifndef FIPS_MODULE
1807     sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1808 #endif
1809     OPENSSL_free(x);
1810 }
1811 
EVP_PKEY_get_size(const EVP_PKEY * pkey)1812 int EVP_PKEY_get_size(const EVP_PKEY *pkey)
1813 {
1814     int size = 0;
1815 
1816     if (pkey != NULL) {
1817         size = pkey->cache.size;
1818 #ifndef FIPS_MODULE
1819         if (pkey->ameth != NULL && pkey->ameth->pkey_size != NULL)
1820             size = pkey->ameth->pkey_size(pkey);
1821 #endif
1822     }
1823     if (size <= 0) {
1824         ERR_raise(ERR_LIB_EVP, EVP_R_UNKNOWN_MAX_SIZE);
1825         return 0;
1826     }
1827     return size;
1828 }
1829 
EVP_PKEY_get0_description(const EVP_PKEY * pkey)1830 const char *EVP_PKEY_get0_description(const EVP_PKEY *pkey)
1831 {
1832     if (!evp_pkey_is_assigned(pkey))
1833         return NULL;
1834 
1835     if (evp_pkey_is_provided(pkey) && pkey->keymgmt->description != NULL)
1836         return pkey->keymgmt->description;
1837 #ifndef FIPS_MODULE
1838     if (pkey->ameth != NULL)
1839         return pkey->ameth->info;
1840 #endif
1841     return NULL;
1842 }
1843 
evp_pkey_export_to_provider(EVP_PKEY * pk,OSSL_LIB_CTX * libctx,EVP_KEYMGMT ** keymgmt,const char * propquery)1844 void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
1845                                   EVP_KEYMGMT **keymgmt,
1846                                   const char *propquery)
1847 {
1848     EVP_KEYMGMT *allocated_keymgmt = NULL;
1849     EVP_KEYMGMT *tmp_keymgmt = NULL;
1850     int selection = OSSL_KEYMGMT_SELECT_ALL;
1851     void *keydata = NULL;
1852     int check;
1853 
1854     if (pk == NULL)
1855         return NULL;
1856 
1857     /* No key data => nothing to export */
1858     check = 1;
1859 #ifndef FIPS_MODULE
1860     check = check && pk->pkey.ptr == NULL;
1861 #endif
1862     check = check && pk->keydata == NULL;
1863     if (check)
1864         return NULL;
1865 
1866 #ifndef FIPS_MODULE
1867     if (pk->pkey.ptr != NULL) {
1868         /*
1869          * If the legacy key doesn't have an dirty counter or export function,
1870          * give up
1871          */
1872         if (pk->ameth->dirty_cnt == NULL || pk->ameth->export_to == NULL)
1873             return NULL;
1874     }
1875 #endif
1876 
1877     if (keymgmt != NULL) {
1878         tmp_keymgmt = *keymgmt;
1879         *keymgmt = NULL;
1880     }
1881 
1882     /*
1883      * If no keymgmt was given or found, get a default keymgmt.  We do so by
1884      * letting EVP_PKEY_CTX_new_from_pkey() do it for us, then we steal it.
1885      */
1886     if (tmp_keymgmt == NULL) {
1887         EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propquery);
1888 
1889         if (ctx == NULL)
1890             goto end;
1891         allocated_keymgmt = tmp_keymgmt = ctx->keymgmt;
1892         ctx->keymgmt = NULL;
1893         EVP_PKEY_CTX_free(ctx);
1894     }
1895 
1896     /* If there's still no keymgmt to be had, give up */
1897     if (tmp_keymgmt == NULL)
1898         goto end;
1899 
1900 #ifndef FIPS_MODULE
1901     if (pk->pkey.ptr != NULL) {
1902         OP_CACHE_ELEM *op;
1903 
1904         /*
1905          * If the legacy "origin" hasn't changed since last time, we try
1906          * to find our keymgmt in the operation cache.  If it has changed,
1907          * |i| remains zero, and we will clear the cache further down.
1908          */
1909         if (pk->ameth->dirty_cnt(pk) == pk->dirty_cnt_copy) {
1910             if (!CRYPTO_THREAD_read_lock(pk->lock))
1911                 goto end;
1912             op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt,
1913                                                        selection);
1914 
1915             /*
1916              * If |tmp_keymgmt| is present in the operation cache, it means
1917              * that export doesn't need to be redone.  In that case, we take
1918              * token copies of the cached pointers, to have token success
1919              * values to return. It is possible (e.g. in a no-cached-fetch
1920              * build), for op->keymgmt to be a different pointer to tmp_keymgmt
1921              * even though the name/provider must be the same. In other words
1922              * the keymgmt instance may be different but still equivalent, i.e.
1923              * same algorithm/provider instance - but we make the simplifying
1924              * assumption that the keydata can be used with either keymgmt
1925              * instance. Not doing so introduces significant complexity and
1926              * probably requires refactoring - since we would have to ripple
1927              * the change in keymgmt instance up the call chain.
1928              */
1929             if (op != NULL && op->keymgmt != NULL) {
1930                 keydata = op->keydata;
1931                 CRYPTO_THREAD_unlock(pk->lock);
1932                 goto end;
1933             }
1934             CRYPTO_THREAD_unlock(pk->lock);
1935         }
1936 
1937         /* Make sure that the keymgmt key type matches the legacy NID */
1938         if (!EVP_KEYMGMT_is_a(tmp_keymgmt, OBJ_nid2sn(pk->type)))
1939             goto end;
1940 
1941         if ((keydata = evp_keymgmt_newdata(tmp_keymgmt)) == NULL)
1942             goto end;
1943 
1944         if (!pk->ameth->export_to(pk, keydata, tmp_keymgmt->import,
1945                                   libctx, propquery)) {
1946             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1947             keydata = NULL;
1948             goto end;
1949         }
1950 
1951         /*
1952          * If the dirty counter changed since last time, then clear the
1953          * operation cache.  In that case, we know that |i| is zero.  Just
1954          * in case this is a re-export, we increment then decrement the
1955          * keymgmt reference counter.
1956          */
1957         if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) { /* refcnt++ */
1958             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1959             keydata = NULL;
1960             goto end;
1961         }
1962 
1963         if (!CRYPTO_THREAD_write_lock(pk->lock))
1964             goto end;
1965         if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy
1966                 && !evp_keymgmt_util_clear_operation_cache(pk)) {
1967             CRYPTO_THREAD_unlock(pk->lock);
1968             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1969             keydata = NULL;
1970             EVP_KEYMGMT_free(tmp_keymgmt);
1971             goto end;
1972         }
1973         EVP_KEYMGMT_free(tmp_keymgmt); /* refcnt-- */
1974 
1975         /* Check to make sure some other thread didn't get there first */
1976         op = evp_keymgmt_util_find_operation_cache(pk, tmp_keymgmt, selection);
1977         if (op != NULL && op->keymgmt != NULL) {
1978             void *tmp_keydata = op->keydata;
1979 
1980             CRYPTO_THREAD_unlock(pk->lock);
1981             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1982             keydata = tmp_keydata;
1983             goto end;
1984         }
1985 
1986         /* Add the new export to the operation cache */
1987         if (!evp_keymgmt_util_cache_keydata(pk, tmp_keymgmt, keydata,
1988                                             selection)) {
1989             CRYPTO_THREAD_unlock(pk->lock);
1990             evp_keymgmt_freedata(tmp_keymgmt, keydata);
1991             keydata = NULL;
1992             goto end;
1993         }
1994 
1995         /* Synchronize the dirty count */
1996         pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk);
1997 
1998         CRYPTO_THREAD_unlock(pk->lock);
1999         goto end;
2000     }
2001 #endif  /* FIPS_MODULE */
2002 
2003     keydata = evp_keymgmt_util_export_to_provider(pk, tmp_keymgmt, selection);
2004 
2005  end:
2006     /*
2007      * If nothing was exported, |tmp_keymgmt| might point at a freed
2008      * EVP_KEYMGMT, so we clear it to be safe.  It shouldn't be useful for
2009      * the caller either way in that case.
2010      */
2011     if (keydata == NULL)
2012         tmp_keymgmt = NULL;
2013 
2014     if (keymgmt != NULL && tmp_keymgmt != NULL) {
2015         *keymgmt = tmp_keymgmt;
2016         allocated_keymgmt = NULL;
2017     }
2018 
2019     EVP_KEYMGMT_free(allocated_keymgmt);
2020     return keydata;
2021 }
2022 
2023 #ifndef FIPS_MODULE
evp_pkey_copy_downgraded(EVP_PKEY ** dest,const EVP_PKEY * src)2024 int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src)
2025 {
2026     EVP_PKEY *allocpkey = NULL;
2027 
2028     if (!ossl_assert(dest != NULL))
2029         return 0;
2030 
2031     if (evp_pkey_is_assigned(src) && evp_pkey_is_provided(src)) {
2032         EVP_KEYMGMT *keymgmt = src->keymgmt;
2033         void *keydata = src->keydata;
2034         int type = src->type;
2035         const char *keytype = NULL;
2036 
2037         keytype = EVP_KEYMGMT_get0_name(keymgmt);
2038 
2039         /*
2040          * If the type is EVP_PKEY_NONE, then we have a problem somewhere
2041          * else in our code.  If it's not one of the well known EVP_PKEY_xxx
2042          * values, it should at least be EVP_PKEY_KEYMGMT at this point.
2043          * The check is kept as a safety measure.
2044          */
2045         if (!ossl_assert(type != EVP_PKEY_NONE)) {
2046             ERR_raise_data(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR,
2047                            "keymgmt key type = %s but legacy type = EVP_PKEY_NONE",
2048                            keytype);
2049             return 0;
2050         }
2051 
2052         /* Prefer the legacy key type name for error reporting */
2053         if (type != EVP_PKEY_KEYMGMT)
2054             keytype = OBJ_nid2sn(type);
2055 
2056         /* Make sure we have a clean slate to copy into */
2057         if (*dest == NULL) {
2058             allocpkey = *dest = EVP_PKEY_new();
2059             if (*dest == NULL) {
2060                 ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
2061                 return 0;
2062             }
2063         } else {
2064             evp_pkey_free_it(*dest);
2065         }
2066 
2067         if (EVP_PKEY_set_type(*dest, type)) {
2068             /* If the key is typed but empty, we're done */
2069             if (keydata == NULL)
2070                 return 1;
2071 
2072             if ((*dest)->ameth->import_from == NULL) {
2073                 ERR_raise_data(ERR_LIB_EVP, EVP_R_NO_IMPORT_FUNCTION,
2074                                "key type = %s", keytype);
2075             } else {
2076                 /*
2077                  * We perform the export in the same libctx as the keymgmt
2078                  * that we are using.
2079                  */
2080                 OSSL_LIB_CTX *libctx =
2081                     ossl_provider_libctx(keymgmt->prov);
2082                 EVP_PKEY_CTX *pctx =
2083                     EVP_PKEY_CTX_new_from_pkey(libctx, *dest, NULL);
2084 
2085                 if (pctx == NULL)
2086                     ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
2087 
2088                 if (pctx != NULL
2089                     && evp_keymgmt_export(keymgmt, keydata,
2090                                           OSSL_KEYMGMT_SELECT_ALL,
2091                                           (*dest)->ameth->import_from,
2092                                           pctx)) {
2093                     /* Synchronize the dirty count */
2094                     (*dest)->dirty_cnt_copy = (*dest)->ameth->dirty_cnt(*dest);
2095 
2096                     EVP_PKEY_CTX_free(pctx);
2097                     return 1;
2098                 }
2099                 EVP_PKEY_CTX_free(pctx);
2100             }
2101 
2102             ERR_raise_data(ERR_LIB_EVP, EVP_R_KEYMGMT_EXPORT_FAILURE,
2103                            "key type = %s", keytype);
2104         }
2105     }
2106 
2107     if (allocpkey != NULL) {
2108         EVP_PKEY_free(allocpkey);
2109         *dest = NULL;
2110     }
2111     return 0;
2112 }
2113 
evp_pkey_get_legacy(EVP_PKEY * pk)2114 void *evp_pkey_get_legacy(EVP_PKEY *pk)
2115 {
2116     EVP_PKEY *tmp_copy = NULL;
2117     void *ret = NULL;
2118 
2119     if (!ossl_assert(pk != NULL))
2120         return NULL;
2121 
2122     /*
2123      * If this isn't an assigned provider side key, we just use any existing
2124      * origin legacy key.
2125      */
2126     if (!evp_pkey_is_assigned(pk))
2127         return NULL;
2128     if (!evp_pkey_is_provided(pk))
2129         return pk->pkey.ptr;
2130 
2131     if (!CRYPTO_THREAD_read_lock(pk->lock))
2132         return NULL;
2133 
2134     ret = pk->legacy_cache_pkey.ptr;
2135 
2136     if (!CRYPTO_THREAD_unlock(pk->lock))
2137         return NULL;
2138 
2139     if (ret != NULL)
2140         return ret;
2141 
2142     if (!evp_pkey_copy_downgraded(&tmp_copy, pk))
2143         goto err;
2144 
2145     if (!CRYPTO_THREAD_write_lock(pk->lock))
2146         goto err;
2147 
2148     /* Check again in case some other thread has updated it in the meantime */
2149     ret = pk->legacy_cache_pkey.ptr;
2150     if (ret == NULL) {
2151         /* Steal the legacy key reference from the temporary copy */
2152         ret = pk->legacy_cache_pkey.ptr = tmp_copy->pkey.ptr;
2153         tmp_copy->pkey.ptr = NULL;
2154     }
2155 
2156     if (!CRYPTO_THREAD_unlock(pk->lock)) {
2157         ret = NULL;
2158         goto err;
2159     }
2160 
2161  err:
2162     EVP_PKEY_free(tmp_copy);
2163 
2164     return ret;
2165 }
2166 #endif  /* FIPS_MODULE */
2167 
EVP_PKEY_get_bn_param(const EVP_PKEY * pkey,const char * key_name,BIGNUM ** bn)2168 int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name,
2169                           BIGNUM **bn)
2170 {
2171     int ret = 0;
2172     OSSL_PARAM params[2];
2173     unsigned char buffer[2048];
2174     unsigned char *buf = NULL;
2175     size_t buf_sz = 0;
2176 
2177     if (key_name == NULL
2178         || bn == NULL)
2179         return 0;
2180 
2181     memset(buffer, 0, sizeof(buffer));
2182     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, sizeof(buffer));
2183     params[1] = OSSL_PARAM_construct_end();
2184     if (!EVP_PKEY_get_params(pkey, params)) {
2185         if (!OSSL_PARAM_modified(params) || params[0].return_size == 0)
2186             return 0;
2187         buf_sz = params[0].return_size;
2188         /*
2189          * If it failed because the buffer was too small then allocate the
2190          * required buffer size and retry.
2191          */
2192         buf = OPENSSL_zalloc(buf_sz);
2193         if (buf == NULL)
2194             return 0;
2195         params[0].data = buf;
2196         params[0].data_size = buf_sz;
2197 
2198         if (!EVP_PKEY_get_params(pkey, params))
2199             goto err;
2200     }
2201     /* Fail if the param was not found */
2202     if (!OSSL_PARAM_modified(params))
2203         goto err;
2204     ret = OSSL_PARAM_get_BN(params, bn);
2205 err:
2206     if (buf != NULL) {
2207         if (OSSL_PARAM_modified(params))
2208             OPENSSL_clear_free(buf, buf_sz);
2209         else
2210             OPENSSL_free(buf);
2211     } else if (OSSL_PARAM_modified(params)) {
2212         OPENSSL_cleanse(buffer, params[0].data_size);
2213     }
2214     return ret;
2215 }
2216 
EVP_PKEY_get_octet_string_param(const EVP_PKEY * pkey,const char * key_name,unsigned char * buf,size_t max_buf_sz,size_t * out_len)2217 int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name,
2218                                     unsigned char *buf, size_t max_buf_sz,
2219                                     size_t *out_len)
2220 {
2221     OSSL_PARAM params[2];
2222     int ret1 = 0, ret2 = 0;
2223 
2224     if (key_name == NULL)
2225         return 0;
2226 
2227     params[0] = OSSL_PARAM_construct_octet_string(key_name, buf, max_buf_sz);
2228     params[1] = OSSL_PARAM_construct_end();
2229     if ((ret1 = EVP_PKEY_get_params(pkey, params)))
2230         ret2 = OSSL_PARAM_modified(params);
2231     if (ret2 && out_len != NULL)
2232         *out_len = params[0].return_size;
2233     return ret1 && ret2;
2234 }
2235 
EVP_PKEY_get_utf8_string_param(const EVP_PKEY * pkey,const char * key_name,char * str,size_t max_buf_sz,size_t * out_len)2236 int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name,
2237                                     char *str, size_t max_buf_sz,
2238                                     size_t *out_len)
2239 {
2240     OSSL_PARAM params[2];
2241     int ret1 = 0, ret2 = 0;
2242 
2243     if (key_name == NULL)
2244         return 0;
2245 
2246     params[0] = OSSL_PARAM_construct_utf8_string(key_name, str, max_buf_sz);
2247     params[1] = OSSL_PARAM_construct_end();
2248     if ((ret1 = EVP_PKEY_get_params(pkey, params)))
2249         ret2 = OSSL_PARAM_modified(params);
2250     if (ret2 && out_len != NULL)
2251         *out_len = params[0].return_size;
2252 
2253     if (ret2 && params[0].return_size == max_buf_sz)
2254         /* There was no space for a NUL byte */
2255         return 0;
2256     /* Add a terminating NUL byte for good measure */
2257     if (ret2 && str != NULL)
2258         str[params[0].return_size] = '\0';
2259 
2260     return ret1 && ret2;
2261 }
2262 
EVP_PKEY_get_int_param(const EVP_PKEY * pkey,const char * key_name,int * out)2263 int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name,
2264                            int *out)
2265 {
2266     OSSL_PARAM params[2];
2267 
2268     if (key_name == NULL)
2269         return 0;
2270 
2271     params[0] = OSSL_PARAM_construct_int(key_name, out);
2272     params[1] = OSSL_PARAM_construct_end();
2273     return EVP_PKEY_get_params(pkey, params)
2274         && OSSL_PARAM_modified(params);
2275 }
2276 
EVP_PKEY_get_size_t_param(const EVP_PKEY * pkey,const char * key_name,size_t * out)2277 int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name,
2278                               size_t *out)
2279 {
2280     OSSL_PARAM params[2];
2281 
2282     if (key_name == NULL)
2283         return 0;
2284 
2285     params[0] = OSSL_PARAM_construct_size_t(key_name, out);
2286     params[1] = OSSL_PARAM_construct_end();
2287     return EVP_PKEY_get_params(pkey, params)
2288         && OSSL_PARAM_modified(params);
2289 }
2290 
EVP_PKEY_set_int_param(EVP_PKEY * pkey,const char * key_name,int in)2291 int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in)
2292 {
2293     OSSL_PARAM params[2];
2294 
2295     if (key_name == NULL)
2296         return 0;
2297 
2298     params[0] = OSSL_PARAM_construct_int(key_name, &in);
2299     params[1] = OSSL_PARAM_construct_end();
2300     return EVP_PKEY_set_params(pkey, params);
2301 }
2302 
EVP_PKEY_set_size_t_param(EVP_PKEY * pkey,const char * key_name,size_t in)2303 int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in)
2304 {
2305     OSSL_PARAM params[2];
2306 
2307     if (key_name == NULL)
2308         return 0;
2309 
2310     params[0] = OSSL_PARAM_construct_size_t(key_name, &in);
2311     params[1] = OSSL_PARAM_construct_end();
2312     return EVP_PKEY_set_params(pkey, params);
2313 }
2314 
EVP_PKEY_set_bn_param(EVP_PKEY * pkey,const char * key_name,const BIGNUM * bn)2315 int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name,
2316                           const BIGNUM *bn)
2317 {
2318     OSSL_PARAM params[2];
2319     unsigned char buffer[2048];
2320     int bsize = 0;
2321 
2322     if (key_name == NULL
2323         || bn == NULL
2324         || pkey == NULL
2325         || !evp_pkey_is_assigned(pkey))
2326         return 0;
2327 
2328     bsize = BN_num_bytes(bn);
2329     if (!ossl_assert(bsize <= (int)sizeof(buffer)))
2330         return 0;
2331 
2332     if (BN_bn2nativepad(bn, buffer, bsize) < 0)
2333         return 0;
2334     params[0] = OSSL_PARAM_construct_BN(key_name, buffer, bsize);
2335     params[1] = OSSL_PARAM_construct_end();
2336     return EVP_PKEY_set_params(pkey, params);
2337 }
2338 
EVP_PKEY_set_utf8_string_param(EVP_PKEY * pkey,const char * key_name,const char * str)2339 int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
2340                                    const char *str)
2341 {
2342     OSSL_PARAM params[2];
2343 
2344     if (key_name == NULL)
2345         return 0;
2346 
2347     params[0] = OSSL_PARAM_construct_utf8_string(key_name, (char *)str, 0);
2348     params[1] = OSSL_PARAM_construct_end();
2349     return EVP_PKEY_set_params(pkey, params);
2350 }
2351 
EVP_PKEY_set_octet_string_param(EVP_PKEY * pkey,const char * key_name,const unsigned char * buf,size_t bsize)2352 int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name,
2353                                     const unsigned char *buf, size_t bsize)
2354 {
2355     OSSL_PARAM params[2];
2356 
2357     if (key_name == NULL)
2358         return 0;
2359 
2360     params[0] = OSSL_PARAM_construct_octet_string(key_name,
2361                                                   (unsigned char *)buf, bsize);
2362     params[1] = OSSL_PARAM_construct_end();
2363     return EVP_PKEY_set_params(pkey, params);
2364 }
2365 
EVP_PKEY_settable_params(const EVP_PKEY * pkey)2366 const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey)
2367 {
2368     return (pkey != NULL && evp_pkey_is_provided(pkey))
2369         ? EVP_KEYMGMT_settable_params(pkey->keymgmt)
2370         : NULL;
2371 }
2372 
EVP_PKEY_set_params(EVP_PKEY * pkey,OSSL_PARAM params[])2373 int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[])
2374 {
2375     if (pkey != NULL) {
2376         if (evp_pkey_is_provided(pkey)) {
2377             pkey->dirty_cnt++;
2378             return evp_keymgmt_set_params(pkey->keymgmt, pkey->keydata, params);
2379         }
2380 #ifndef FIPS_MODULE
2381         /*
2382          * We will hopefully never find the need to set individual data in
2383          * EVP_PKEYs with a legacy internal key, but we can't be entirely
2384          * sure.  This bit of code can be enabled if we find the need.  If
2385          * not, it can safely be removed when #legacy support is removed.
2386          */
2387 # if 0
2388         else if (evp_pkey_is_legacy(pkey)) {
2389             return evp_pkey_set_params_to_ctrl(pkey, params);
2390         }
2391 # endif
2392 #endif
2393     }
2394     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
2395     return 0;
2396 }
2397 
EVP_PKEY_gettable_params(const EVP_PKEY * pkey)2398 const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey)
2399 {
2400     return (pkey != NULL && evp_pkey_is_provided(pkey))
2401         ? EVP_KEYMGMT_gettable_params(pkey->keymgmt)
2402         : NULL;
2403 }
2404 
EVP_PKEY_get_params(const EVP_PKEY * pkey,OSSL_PARAM params[])2405 int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[])
2406 {
2407     if (pkey != NULL) {
2408         if (evp_pkey_is_provided(pkey))
2409             return evp_keymgmt_get_params(pkey->keymgmt, pkey->keydata, params) > 0;
2410 #ifndef FIPS_MODULE
2411         else if (evp_pkey_is_legacy(pkey))
2412             return evp_pkey_get_params_to_ctrl(pkey, params) > 0;
2413 #endif
2414     }
2415     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY);
2416     return 0;
2417 }
2418 
2419 #ifndef FIPS_MODULE
EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY * pkey)2420 int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey)
2421 {
2422     char name[80];
2423     size_t name_len;
2424 
2425     if (pkey == NULL)
2426         return 0;
2427 
2428     if (pkey->keymgmt == NULL
2429             || pkey->keydata == NULL) {
2430 # ifndef OPENSSL_NO_EC
2431         /* Might work through the legacy route */
2432         const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2433 
2434         if (ec == NULL)
2435             return 0;
2436 
2437         return EC_KEY_get_conv_form(ec);
2438 # else
2439         return 0;
2440 # endif
2441     }
2442 
2443     if (!EVP_PKEY_get_utf8_string_param(pkey,
2444                                         OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
2445                                         name, sizeof(name), &name_len))
2446         return 0;
2447 
2448     if (strcmp(name, "uncompressed") == 0)
2449         return POINT_CONVERSION_UNCOMPRESSED;
2450 
2451     if (strcmp(name, "compressed") == 0)
2452         return POINT_CONVERSION_COMPRESSED;
2453 
2454     if (strcmp(name, "hybrid") == 0)
2455         return POINT_CONVERSION_HYBRID;
2456 
2457     return 0;
2458 }
2459 
EVP_PKEY_get_field_type(const EVP_PKEY * pkey)2460 int EVP_PKEY_get_field_type(const EVP_PKEY *pkey)
2461 {
2462     char fstr[80];
2463     size_t fstrlen;
2464 
2465     if (pkey == NULL)
2466         return 0;
2467 
2468     if (pkey->keymgmt == NULL
2469             || pkey->keydata == NULL) {
2470 # ifndef OPENSSL_NO_EC
2471         /* Might work through the legacy route */
2472         const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2473         const EC_GROUP *grp;
2474 
2475         if (ec == NULL)
2476             return 0;
2477         grp = EC_KEY_get0_group(ec);
2478         if (grp == NULL)
2479             return 0;
2480 
2481         return EC_GROUP_get_field_type(grp);
2482 # else
2483         return 0;
2484 # endif
2485     }
2486 
2487     if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_EC_FIELD_TYPE,
2488                                         fstr, sizeof(fstr), &fstrlen))
2489         return 0;
2490 
2491     if (strcmp(fstr, SN_X9_62_prime_field) == 0)
2492         return NID_X9_62_prime_field;
2493     else if (strcmp(fstr, SN_X9_62_characteristic_two_field))
2494         return NID_X9_62_characteristic_two_field;
2495 
2496     return 0;
2497 }
2498 #endif
2499