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