xref: /freebsd/crypto/openssl/crypto/encode_decode/decoder_pkey.c (revision 88b8b7f0c4e9948667a2279e78e975a784049cba)
1 /*
2  * Copyright 2020-2025 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 #include <openssl/core_names.h>
11 #include <openssl/core_object.h>
12 #include <openssl/provider.h>
13 #include <openssl/evp.h>
14 #include <openssl/ui.h>
15 #include <openssl/decoder.h>
16 #include <openssl/safestack.h>
17 #include <openssl/trace.h>
18 #include "crypto/evp.h"
19 #include "crypto/decoder.h"
20 #include "crypto/evp/evp_local.h"
21 #include "crypto/lhash.h"
22 #include "encoder_local.h"
23 #include "internal/namemap.h"
24 #include "internal/sizes.h"
25 
OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX * ctx,const unsigned char * kstr,size_t klen)26 int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
27                                     const unsigned char *kstr,
28                                     size_t klen)
29 {
30     return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
31 }
32 
OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX * ctx,const UI_METHOD * ui_method,void * ui_data)33 int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
34                                        const UI_METHOD *ui_method,
35                                        void *ui_data)
36 {
37     return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
38 }
39 
OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX * ctx,pem_password_cb * cb,void * cbarg)40 int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
41                                          pem_password_cb *cb, void *cbarg)
42 {
43     return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
44 }
45 
OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX * ctx,OSSL_PASSPHRASE_CALLBACK * cb,void * cbarg)46 int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
47                                        OSSL_PASSPHRASE_CALLBACK *cb,
48                                        void *cbarg)
49 {
50     return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
51 }
52 
53 /*
54  * Support for OSSL_DECODER_CTX_new_for_pkey:
55  * The construct data, and collecting keymgmt information for it
56  */
57 
58 DEFINE_STACK_OF(EVP_KEYMGMT)
59 
60 struct decoder_pkey_data_st {
61     OSSL_LIB_CTX *libctx;
62     char *propq;
63     int selection;
64 
65     STACK_OF(EVP_KEYMGMT) *keymgmts;
66     char *object_type;           /* recorded object data type, may be NULL */
67     void **object;               /* Where the result should end up */
68     OSSL_DECODER_CTX *ctx;       /* The parent decoder context */
69 };
70 
decoder_construct_pkey(OSSL_DECODER_INSTANCE * decoder_inst,const OSSL_PARAM * params,void * construct_data)71 static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst,
72                                   const OSSL_PARAM *params,
73                                   void *construct_data)
74 {
75     struct decoder_pkey_data_st *data = construct_data;
76     OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
77     void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
78     const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
79     EVP_KEYMGMT *keymgmt = NULL;
80     const OSSL_PROVIDER *keymgmt_prov = NULL;
81     int i, end;
82     /*
83      * |object_ref| points to a provider reference to an object, its exact
84      * contents entirely opaque to us, but may be passed to any provider
85      * function that expects this (such as OSSL_FUNC_keymgmt_load().
86      *
87      * This pointer is considered volatile, i.e. whatever it points at
88      * is assumed to be freed as soon as this function returns.
89      */
90     void *object_ref = NULL;
91     size_t object_ref_sz = 0;
92     const OSSL_PARAM *p;
93 
94     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
95     if (p != NULL) {
96         char *object_type = NULL;
97 
98         if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
99             return 0;
100         OPENSSL_free(data->object_type);
101         data->object_type = object_type;
102     }
103 
104     /*
105      * For stuff that should end up in an EVP_PKEY, we only accept an object
106      * reference for the moment.  This enforces that the key data itself
107      * remains with the provider.
108      */
109     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
110     if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
111         return 0;
112     object_ref = p->data;
113     object_ref_sz = p->data_size;
114 
115     /*
116      * First, we try to find a keymgmt that comes from the same provider as
117      * the decoder that passed the params.
118      */
119     end = sk_EVP_KEYMGMT_num(data->keymgmts);
120     for (i = 0; i < end; i++) {
121         keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
122         keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
123 
124         if (keymgmt_prov == decoder_prov
125             && evp_keymgmt_has_load(keymgmt)
126             && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
127             break;
128     }
129     if (i < end) {
130         /* To allow it to be freed further down */
131         if (!EVP_KEYMGMT_up_ref(keymgmt))
132             return 0;
133     } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx,
134                                             data->object_type,
135                                             data->propq)) != NULL) {
136         keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
137     }
138 
139     if (keymgmt != NULL) {
140         EVP_PKEY *pkey = NULL;
141         void *keydata = NULL;
142 
143         /*
144          * If the EVP_KEYMGMT and the OSSL_DECODER are from the
145          * same provider, we assume that the KEYMGMT has a key loading
146          * function that can handle the provider reference we hold.
147          *
148          * Otherwise, we export from the decoder and import the
149          * result in the keymgmt.
150          */
151         if (keymgmt_prov == decoder_prov) {
152             keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
153         } else {
154             struct evp_keymgmt_util_try_import_data_st import_data;
155 
156             import_data.keymgmt = keymgmt;
157             import_data.keydata = NULL;
158             if (data->selection == 0)
159                 /* import/export functions do not tolerate 0 selection */
160                 import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
161             else
162                 import_data.selection = data->selection;
163 
164             /*
165              * No need to check for errors here, the value of
166              * |import_data.keydata| is as much an indicator.
167              */
168             (void)decoder->export_object(decoderctx,
169                                          object_ref, object_ref_sz,
170                                          &evp_keymgmt_util_try_import,
171                                          &import_data);
172             keydata = import_data.keydata;
173             import_data.keydata = NULL;
174         }
175         /*
176          * When load or import fails, because this is not an acceptable key
177          * (despite the provided key material being syntactically valid), the
178          * reason why the key is rejected would be lost, unless we signal a
179          * hard error, and suppress resetting for another try.
180          */
181         if (keydata == NULL)
182             ossl_decoder_ctx_set_harderr(data->ctx);
183 
184         if (keydata != NULL
185             && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
186             evp_keymgmt_freedata(keymgmt, keydata);
187 
188         *data->object = pkey;
189 
190         /*
191          * evp_keymgmt_util_make_pkey() increments the reference count when
192          * assigning the EVP_PKEY, so we can free the keymgmt here.
193          */
194         EVP_KEYMGMT_free(keymgmt);
195     }
196     /*
197      * We successfully looked through, |*ctx->object| determines if we
198      * actually found something.
199      */
200     return (*data->object != NULL);
201 }
202 
decoder_clean_pkey_construct_arg(void * construct_data)203 static void decoder_clean_pkey_construct_arg(void *construct_data)
204 {
205     struct decoder_pkey_data_st *data = construct_data;
206 
207     if (data != NULL) {
208         sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
209         OPENSSL_free(data->propq);
210         OPENSSL_free(data->object_type);
211         OPENSSL_free(data);
212     }
213 }
214 
215 struct collect_data_st {
216     OSSL_LIB_CTX *libctx;
217     OSSL_DECODER_CTX *ctx;
218 
219     const char *keytype; /* the keytype requested, if any */
220     int keytype_id; /* if keytype_resolved is set, keymgmt name_id; else 0 */
221     int sm2_id;     /* if keytype_resolved is set and EC, SM2 name_id; else 0 */
222     int total;      /* number of matching results */
223     char error_occurred;
224     char keytype_resolved;
225     OSSL_PROPERTY_LIST *pq;
226 
227     STACK_OF(EVP_KEYMGMT) *keymgmts;
228 };
229 
230 /*
231  * Add decoder instance to the decoder context if it is compatible. Returns 1
232  * if a decoder was added, 0 otherwise.
233  */
collect_decoder_keymgmt(EVP_KEYMGMT * keymgmt,OSSL_DECODER * decoder,void * provctx,struct collect_data_st * data)234 static int collect_decoder_keymgmt(EVP_KEYMGMT *keymgmt, OSSL_DECODER *decoder,
235                                    void *provctx, struct collect_data_st *data)
236 {
237     void *decoderctx = NULL;
238     OSSL_DECODER_INSTANCE *di = NULL;
239     const OSSL_PROPERTY_LIST *props;
240 
241     /*
242      * We already checked the EVP_KEYMGMT is applicable in check_keymgmt so we
243      * don't check it again here.
244      */
245 
246     if (keymgmt->name_id != decoder->base.id)
247         /* Mismatch is not an error, continue. */
248         return 0;
249 
250     if ((decoderctx = decoder->newctx(provctx)) == NULL) {
251         data->error_occurred = 1;
252         return 0;
253     }
254 
255     if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
256         decoder->freectx(decoderctx);
257         data->error_occurred = 1;
258         return 0;
259     }
260 
261     /*
262      * Input types must be compatible, but we must accept DER encoders when the
263      * start input type is "PEM".
264      */
265     if (data->ctx->start_input_type != NULL
266         && di->input_type != NULL
267         && OPENSSL_strcasecmp(di->input_type, data->ctx->start_input_type) != 0
268         && (OPENSSL_strcasecmp(di->input_type, "DER") != 0
269             || OPENSSL_strcasecmp(data->ctx->start_input_type, "PEM") != 0)) {
270         /* Mismatch is not an error, continue. */
271         ossl_decoder_instance_free(di);
272         return 0;
273     }
274 
275     OSSL_TRACE_BEGIN(DECODER) {
276         BIO_printf(trc_out,
277                    "(ctx %p) Checking out decoder %p:\n"
278                    "    %s with %s\n",
279                    (void *)data->ctx, (void *)decoder,
280                    OSSL_DECODER_get0_name(decoder),
281                    OSSL_DECODER_get0_properties(decoder));
282     } OSSL_TRACE_END(DECODER);
283 
284     /*
285      * Get the property match score so the decoders can be prioritized later.
286      */
287     props = ossl_decoder_parsed_properties(decoder);
288     if (data->pq != NULL && props != NULL) {
289         di->score = ossl_property_match_count(data->pq, props);
290         /*
291          * Mismatch of mandatory properties is not an error, the decoder is just
292          * ignored, continue.
293          */
294         if (di->score < 0) {
295             ossl_decoder_instance_free(di);
296             return 0;
297         }
298     }
299 
300     if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
301         ossl_decoder_instance_free(di);
302         data->error_occurred = 1;
303         return 0;
304     }
305 
306     ++data->total;
307     return 1;
308 }
309 
collect_decoder(OSSL_DECODER * decoder,void * arg)310 static void collect_decoder(OSSL_DECODER *decoder, void *arg)
311 {
312     struct collect_data_st *data = arg;
313     STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts;
314     int i, end_i;
315     EVP_KEYMGMT *keymgmt;
316     const OSSL_PROVIDER *prov;
317     void *provctx;
318 
319     if (data->error_occurred)
320         return;
321 
322     prov = OSSL_DECODER_get0_provider(decoder);
323     provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
324 
325     /*
326      * Either the caller didn't give us a selection, or if they did, the decoder
327      * must tell us if it supports that selection to be accepted. If the decoder
328      * doesn't have |does_selection|, it's seen as taking anything.
329      */
330     if (decoder->does_selection != NULL
331             && !decoder->does_selection(provctx, data->ctx->selection))
332         return;
333 
334     OSSL_TRACE_BEGIN(DECODER) {
335         BIO_printf(trc_out,
336                    "(ctx %p) Checking out decoder %p:\n"
337                    "    %s with %s\n",
338                    (void *)data->ctx, (void *)decoder,
339                    OSSL_DECODER_get0_name(decoder),
340                    OSSL_DECODER_get0_properties(decoder));
341     } OSSL_TRACE_END(DECODER);
342 
343     end_i = sk_EVP_KEYMGMT_num(keymgmts);
344     for (i = 0; i < end_i; ++i) {
345         keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i);
346 
347         /* Only add this decoder once */
348         if (collect_decoder_keymgmt(keymgmt, decoder, provctx, data))
349             break;
350         if (data->error_occurred)
351             return;
352     }
353 }
354 
355 /*
356  * Is this EVP_KEYMGMT applicable given the key type given in the call to
357  * ossl_decoder_ctx_setup_for_pkey (if any)?
358  */
check_keymgmt(EVP_KEYMGMT * keymgmt,struct collect_data_st * data)359 static int check_keymgmt(EVP_KEYMGMT *keymgmt, struct collect_data_st *data)
360 {
361     /* If no keytype was specified, everything matches. */
362     if (data->keytype == NULL)
363         return 1;
364 
365     if (!data->keytype_resolved) {
366         /* We haven't cached the IDs from the keytype string yet. */
367         OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx);
368         data->keytype_id = ossl_namemap_name2num(namemap, data->keytype);
369 
370         /*
371          * If keytype is a value ambiguously used for both EC and SM2,
372          * collect the ID for SM2 as well.
373          */
374         if (data->keytype_id != 0
375             && (strcmp(data->keytype, "id-ecPublicKey") == 0
376                 || strcmp(data->keytype, "1.2.840.10045.2.1") == 0))
377             data->sm2_id = ossl_namemap_name2num(namemap, "SM2");
378 
379         /*
380          * If keytype_id is zero the name was not found, but we still
381          * set keytype_resolved to avoid trying all this again.
382          */
383         data->keytype_resolved = 1;
384     }
385 
386     /* Specified keytype could not be resolved, so nothing matches. */
387     if (data->keytype_id == 0)
388         return 0;
389 
390     /* Does not match the keytype specified, so skip. */
391     if (keymgmt->name_id != data->keytype_id
392         && keymgmt->name_id != data->sm2_id)
393         return 0;
394 
395     return 1;
396 }
397 
collect_keymgmt(EVP_KEYMGMT * keymgmt,void * arg)398 static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
399 {
400     struct collect_data_st *data = arg;
401 
402     if (!check_keymgmt(keymgmt, data))
403         return;
404 
405     /*
406      * We have to ref EVP_KEYMGMT here because in the success case,
407      * data->keymgmts is referenced by the constructor we register in the
408      * OSSL_DECODER_CTX. The registered cleanup function
409      * (decoder_clean_pkey_construct_arg) unrefs every element of the stack and
410      * frees it.
411      */
412     if (!EVP_KEYMGMT_up_ref(keymgmt))
413         return;
414 
415     if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) {
416         EVP_KEYMGMT_free(keymgmt);
417         data->error_occurred = 1;
418     }
419 }
420 
421 /*
422  * This function does the actual binding of decoders to the OSSL_DECODER_CTX. It
423  * searches for decoders matching 'keytype', which is a string like "RSA", "DH",
424  * etc. If 'keytype' is NULL, decoders for all keytypes are bound.
425  */
ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX * ctx,const char * keytype,OSSL_LIB_CTX * libctx,const char * propquery)426 static int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx,
427                                            const char *keytype,
428                                            OSSL_LIB_CTX *libctx,
429                                            const char *propquery)
430 {
431     int ok = 0;
432     struct decoder_pkey_data_st *process_data = NULL;
433     struct collect_data_st collect_data = { NULL };
434     STACK_OF(EVP_KEYMGMT) *keymgmts = NULL;
435     OSSL_PROPERTY_LIST **plp;
436     OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
437 
438     OSSL_TRACE_BEGIN(DECODER) {
439         const char *input_type = ctx->start_input_type;
440         const char *input_structure = ctx->input_structure;
441 
442         BIO_printf(trc_out,
443                    "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n",
444                    (void *)ctx,
445                    keytype != NULL ? keytype : "",
446                    keytype != NULL ? " keys" : "keys of any type",
447                    input_type != NULL ? " from " : "",
448                    input_type != NULL ? input_type : "",
449                    input_structure != NULL ? " with " : "",
450                    input_structure != NULL ? input_structure : "");
451     } OSSL_TRACE_END(DECODER);
452 
453     /* Allocate data. */
454     if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL)
455         goto err;
456     if ((propquery != NULL
457             && (process_data->propq = OPENSSL_strdup(propquery)) == NULL))
458         goto err;
459 
460     /* Allocate our list of EVP_KEYMGMTs. */
461     keymgmts = sk_EVP_KEYMGMT_new_null();
462     if (keymgmts == NULL) {
463         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
464         goto err;
465     }
466 
467     process_data->object    = NULL;
468     process_data->libctx    = libctx;
469     process_data->selection = ctx->selection;
470     process_data->keymgmts  = keymgmts;
471 
472     /*
473      * Collect passed and default properties to prioritize the decoders.
474      */
475     if (propquery != NULL)
476         p2 = pq = ossl_parse_query(libctx, propquery, 1);
477 
478     plp = ossl_ctx_global_properties(libctx, 0);
479     if (plp != NULL && *plp != NULL) {
480         if (pq == NULL) {
481             pq = *plp;
482         } else {
483             p2 = ossl_property_merge(pq, *plp);
484             ossl_property_free(pq);
485             if (p2 == NULL)
486                 goto err;
487             pq = p2;
488         }
489     }
490 
491     /*
492      * Enumerate all keymgmts into a stack.
493      *
494      * We could nest EVP_KEYMGMT_do_all_provided inside
495      * OSSL_DECODER_do_all_provided or vice versa but these functions become
496      * bottlenecks if called repeatedly, which is why we collect the
497      * EVP_KEYMGMTs into a stack here and call both functions only once.
498      *
499      * We resolve the keytype string to a name ID so we don't have to resolve it
500      * multiple times, avoiding repeated calls to EVP_KEYMGMT_is_a, which is a
501      * performance bottleneck. However, we do this lazily on the first call to
502      * collect_keymgmt made by EVP_KEYMGMT_do_all_provided, rather than do it
503      * upfront, as this ensures that the names for all loaded providers have
504      * been registered by the time we try to resolve the keytype string.
505      */
506     collect_data.ctx            = ctx;
507     collect_data.libctx         = libctx;
508     collect_data.keymgmts       = keymgmts;
509     collect_data.keytype        = keytype;
510     collect_data.pq             = pq;
511     EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data);
512 
513     if (collect_data.error_occurred)
514         goto err;
515 
516     /* Enumerate all matching decoders. */
517     OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data);
518 
519     if (collect_data.error_occurred)
520         goto err;
521 
522     OSSL_TRACE_BEGIN(DECODER) {
523         BIO_printf(trc_out,
524                    "(ctx %p) Got %d decoders producing keys\n",
525                    (void *)ctx, collect_data.total);
526     } OSSL_TRACE_END(DECODER);
527 
528     /*
529      * Finish initializing the decoder context. If one or more decoders matched
530      * above then the number of decoders attached to the OSSL_DECODER_CTX will
531      * be nonzero. Else nothing was found and we do nothing.
532      */
533     if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
534         if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
535             || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
536             || !OSSL_DECODER_CTX_set_cleanup(ctx,
537                                              decoder_clean_pkey_construct_arg))
538             goto err;
539 
540         process_data = NULL; /* Avoid it being freed */
541     }
542 
543     ok = 1;
544  err:
545     decoder_clean_pkey_construct_arg(process_data);
546     ossl_property_free(p2);
547     return ok;
548 }
549 
550 /* Only const here because deep_copy requires it */
keymgmt_dup(const EVP_KEYMGMT * keymgmt)551 static EVP_KEYMGMT *keymgmt_dup(const EVP_KEYMGMT *keymgmt)
552 {
553     if (!EVP_KEYMGMT_up_ref((EVP_KEYMGMT *)keymgmt))
554         return NULL;
555 
556     return (EVP_KEYMGMT *)keymgmt;
557 }
558 
559 /*
560  * Duplicates a template OSSL_DECODER_CTX that has been setup for an EVP_PKEY
561  * operation and sets up the duplicate for a new operation.
562  * It does not duplicate the pwdata on the assumption that this does not form
563  * part of the template. That is set up later.
564  */
565 static OSSL_DECODER_CTX *
ossl_decoder_ctx_for_pkey_dup(OSSL_DECODER_CTX * src,EVP_PKEY ** pkey,const char * input_type,const char * input_structure)566 ossl_decoder_ctx_for_pkey_dup(OSSL_DECODER_CTX *src,
567                               EVP_PKEY **pkey,
568                               const char *input_type,
569                               const char *input_structure)
570 {
571     OSSL_DECODER_CTX *dest;
572     struct decoder_pkey_data_st *process_data_src, *process_data_dest = NULL;
573 
574     if (src == NULL)
575         return NULL;
576 
577     if ((dest = OSSL_DECODER_CTX_new()) == NULL) {
578         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
579         return NULL;
580     }
581 
582     if (!OSSL_DECODER_CTX_set_input_type(dest, input_type)
583             || !OSSL_DECODER_CTX_set_input_structure(dest, input_structure)) {
584         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
585         goto err;
586     }
587     dest->selection = src->selection;
588 
589     if (src->decoder_insts != NULL) {
590         dest->decoder_insts
591             = sk_OSSL_DECODER_INSTANCE_deep_copy(src->decoder_insts,
592                                                  ossl_decoder_instance_dup,
593                                                  ossl_decoder_instance_free);
594         if (dest->decoder_insts == NULL) {
595             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
596             goto err;
597         }
598     }
599 
600     if (!OSSL_DECODER_CTX_set_construct(dest,
601                                         OSSL_DECODER_CTX_get_construct(src))) {
602         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
603         goto err;
604     }
605 
606     process_data_src = OSSL_DECODER_CTX_get_construct_data(src);
607     if (process_data_src != NULL) {
608         process_data_dest = OPENSSL_zalloc(sizeof(*process_data_dest));
609         if (process_data_dest == NULL) {
610             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
611             goto err;
612         }
613         if (process_data_src->propq != NULL) {
614             process_data_dest->propq = OPENSSL_strdup(process_data_src->propq);
615             if (process_data_dest->propq == NULL) {
616                 ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
617                 goto err;
618             }
619         }
620 
621         if (process_data_src->keymgmts != NULL) {
622             process_data_dest->keymgmts
623                 = sk_EVP_KEYMGMT_deep_copy(process_data_src->keymgmts,
624                                            keymgmt_dup,
625                                            EVP_KEYMGMT_free);
626             if (process_data_dest->keymgmts == NULL) {
627                 ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_EVP_LIB);
628                 goto err;
629             }
630         }
631 
632         process_data_dest->object    = (void **)pkey;
633         process_data_dest->libctx    = process_data_src->libctx;
634         process_data_dest->selection = process_data_src->selection;
635         process_data_dest->ctx       = dest;
636         if (!OSSL_DECODER_CTX_set_construct_data(dest, process_data_dest)) {
637             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
638             goto err;
639         }
640         process_data_dest = NULL;
641     }
642 
643     if (!OSSL_DECODER_CTX_set_cleanup(dest,
644                                       OSSL_DECODER_CTX_get_cleanup(src))) {
645         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
646         goto err;
647     }
648 
649     return dest;
650  err:
651     decoder_clean_pkey_construct_arg(process_data_dest);
652     OSSL_DECODER_CTX_free(dest);
653     return NULL;
654 }
655 
656 typedef struct {
657     char *input_type;
658     char *input_structure;
659     char *keytype;
660     int selection;
661     char *propquery;
662     OSSL_DECODER_CTX *template;
663 } DECODER_CACHE_ENTRY;
664 
665 DEFINE_LHASH_OF_EX(DECODER_CACHE_ENTRY);
666 
667 typedef struct {
668     CRYPTO_RWLOCK *lock;
669     LHASH_OF(DECODER_CACHE_ENTRY) *hashtable;
670 } DECODER_CACHE;
671 
decoder_cache_entry_free(DECODER_CACHE_ENTRY * entry)672 static void decoder_cache_entry_free(DECODER_CACHE_ENTRY *entry)
673 {
674     if (entry == NULL)
675         return;
676     OPENSSL_free(entry->input_type);
677     OPENSSL_free(entry->input_structure);
678     OPENSSL_free(entry->keytype);
679     OPENSSL_free(entry->propquery);
680     OSSL_DECODER_CTX_free(entry->template);
681     OPENSSL_free(entry);
682 }
683 
decoder_cache_entry_hash(const DECODER_CACHE_ENTRY * cache)684 static unsigned long decoder_cache_entry_hash(const DECODER_CACHE_ENTRY *cache)
685 {
686     unsigned long hash = 17;
687 
688     hash = (hash * 23)
689            + (cache->propquery == NULL
690               ? 0 : ossl_lh_strcasehash(cache->propquery));
691     hash = (hash * 23)
692            + (cache->input_structure == NULL
693               ? 0  : ossl_lh_strcasehash(cache->input_structure));
694     hash = (hash * 23)
695            + (cache->input_type == NULL
696               ? 0  : ossl_lh_strcasehash(cache->input_type));
697     hash = (hash * 23)
698            + (cache->keytype == NULL
699               ? 0  : ossl_lh_strcasehash(cache->keytype));
700 
701     hash ^= cache->selection;
702 
703     return hash;
704 }
705 
nullstrcmp(const char * a,const char * b,int casecmp)706 static ossl_inline int nullstrcmp(const char *a, const char *b, int casecmp)
707 {
708     if (a == NULL || b == NULL) {
709         if (a == NULL) {
710             if (b == NULL)
711                 return 0;
712             else
713                 return 1;
714         } else {
715             return -1;
716         }
717     } else {
718         if (casecmp)
719             return OPENSSL_strcasecmp(a, b);
720         else
721             return strcmp(a, b);
722     }
723 }
724 
decoder_cache_entry_cmp(const DECODER_CACHE_ENTRY * a,const DECODER_CACHE_ENTRY * b)725 static int decoder_cache_entry_cmp(const DECODER_CACHE_ENTRY *a,
726                                    const DECODER_CACHE_ENTRY *b)
727 {
728     int cmp;
729 
730     if (a->selection != b->selection)
731         return (a->selection < b->selection) ? -1 : 1;
732 
733     cmp = nullstrcmp(a->keytype, b->keytype, 1);
734     if (cmp != 0)
735         return cmp;
736 
737     cmp = nullstrcmp(a->input_type, b->input_type, 1);
738     if (cmp != 0)
739         return cmp;
740 
741     cmp = nullstrcmp(a->input_structure, b->input_structure, 1);
742     if (cmp != 0)
743         return cmp;
744 
745     cmp = nullstrcmp(a->propquery, b->propquery, 0);
746 
747     return cmp;
748 }
749 
ossl_decoder_cache_new(OSSL_LIB_CTX * ctx)750 void *ossl_decoder_cache_new(OSSL_LIB_CTX *ctx)
751 {
752     DECODER_CACHE *cache = OPENSSL_malloc(sizeof(*cache));
753 
754     if (cache == NULL)
755         return NULL;
756 
757     cache->lock = CRYPTO_THREAD_lock_new();
758     if (cache->lock == NULL) {
759         OPENSSL_free(cache);
760         return NULL;
761     }
762     cache->hashtable = lh_DECODER_CACHE_ENTRY_new(decoder_cache_entry_hash,
763                                                   decoder_cache_entry_cmp);
764     if (cache->hashtable == NULL) {
765         CRYPTO_THREAD_lock_free(cache->lock);
766         OPENSSL_free(cache);
767         return NULL;
768     }
769 
770     return cache;
771 }
772 
ossl_decoder_cache_free(void * vcache)773 void ossl_decoder_cache_free(void *vcache)
774 {
775     DECODER_CACHE *cache = (DECODER_CACHE *)vcache;
776 
777     lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
778     lh_DECODER_CACHE_ENTRY_free(cache->hashtable);
779     CRYPTO_THREAD_lock_free(cache->lock);
780     OPENSSL_free(cache);
781 }
782 
783 /*
784  * Called whenever a provider gets activated/deactivated. In that case the
785  * decoders that are available might change so we flush our cache.
786  */
ossl_decoder_cache_flush(OSSL_LIB_CTX * libctx)787 int ossl_decoder_cache_flush(OSSL_LIB_CTX *libctx)
788 {
789     DECODER_CACHE *cache
790         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
791 
792     if (cache == NULL)
793         return 0;
794 
795 
796     if (!CRYPTO_THREAD_write_lock(cache->lock)) {
797         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
798         return 0;
799     }
800 
801     lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
802     lh_DECODER_CACHE_ENTRY_flush(cache->hashtable);
803 
804     CRYPTO_THREAD_unlock(cache->lock);
805     return 1;
806 }
807 
808 OSSL_DECODER_CTX *
OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY ** pkey,const char * input_type,const char * input_structure,const char * keytype,int selection,OSSL_LIB_CTX * libctx,const char * propquery)809 OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
810                               const char *input_type,
811                               const char *input_structure,
812                               const char *keytype, int selection,
813                               OSSL_LIB_CTX *libctx, const char *propquery)
814 {
815     OSSL_DECODER_CTX *ctx = NULL;
816     OSSL_PARAM decoder_params[] = {
817         OSSL_PARAM_END,
818         OSSL_PARAM_END,
819         OSSL_PARAM_END
820     };
821     DECODER_CACHE *cache
822         = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
823     DECODER_CACHE_ENTRY cacheent, *res, *newcache = NULL;
824     int i = 0;
825 
826     if (cache == NULL) {
827         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
828         return NULL;
829     }
830     if (input_structure != NULL)
831         decoder_params[i++] =
832             OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE,
833                                              (char *)input_structure, 0);
834     if (propquery != NULL)
835         decoder_params[i++] =
836             OSSL_PARAM_construct_utf8_string(OSSL_DECODER_PARAM_PROPERTIES,
837                                              (char *)propquery, 0);
838 
839     /* It is safe to cast away the const here */
840     cacheent.input_type = (char *)input_type;
841     cacheent.input_structure = (char *)input_structure;
842     cacheent.keytype = (char *)keytype;
843     cacheent.selection = selection;
844     cacheent.propquery = (char *)propquery;
845 
846     if (!CRYPTO_THREAD_read_lock(cache->lock)) {
847         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
848         return NULL;
849     }
850 
851     /* First see if we have a template OSSL_DECODER_CTX */
852     res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
853 
854     if (res == NULL) {
855         /*
856          * There is no template so we will have to construct one. This will be
857          * time consuming so release the lock and we will later upgrade it to a
858          * write lock.
859          */
860         CRYPTO_THREAD_unlock(cache->lock);
861 
862         if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
863             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
864             return NULL;
865         }
866 
867         OSSL_TRACE_BEGIN(DECODER) {
868             BIO_printf(trc_out,
869                     "(ctx %p) Looking for %s decoders with selection %d\n",
870                     (void *)ctx, keytype, selection);
871             BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
872                     input_type, input_structure);
873         } OSSL_TRACE_END(DECODER);
874 
875         if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
876             && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
877             && OSSL_DECODER_CTX_set_selection(ctx, selection)
878             && ossl_decoder_ctx_setup_for_pkey(ctx, keytype, libctx, propquery)
879             && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)
880             && (propquery == NULL
881                 || OSSL_DECODER_CTX_set_params(ctx, decoder_params))) {
882             OSSL_TRACE_BEGIN(DECODER) {
883                 BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
884                         (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
885             } OSSL_TRACE_END(DECODER);
886         } else {
887             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
888             OSSL_DECODER_CTX_free(ctx);
889             return NULL;
890         }
891 
892         newcache = OPENSSL_zalloc(sizeof(*newcache));
893         if (newcache == NULL) {
894             OSSL_DECODER_CTX_free(ctx);
895             return NULL;
896         }
897 
898         if (input_type != NULL) {
899             newcache->input_type = OPENSSL_strdup(input_type);
900             if (newcache->input_type == NULL)
901                 goto err;
902         }
903         if (input_structure != NULL) {
904             newcache->input_structure = OPENSSL_strdup(input_structure);
905             if (newcache->input_structure == NULL)
906                 goto err;
907         }
908         if (keytype != NULL) {
909             newcache->keytype = OPENSSL_strdup(keytype);
910             if (newcache->keytype == NULL)
911                 goto err;
912         }
913         if (propquery != NULL) {
914             newcache->propquery = OPENSSL_strdup(propquery);
915             if (newcache->propquery == NULL)
916                 goto err;
917         }
918         newcache->selection = selection;
919         newcache->template = ctx;
920 
921         if (!CRYPTO_THREAD_write_lock(cache->lock)) {
922             ctx = NULL;
923             ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
924             goto err;
925         }
926         res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
927         if (res == NULL) {
928             (void)lh_DECODER_CACHE_ENTRY_insert(cache->hashtable, newcache);
929             if (lh_DECODER_CACHE_ENTRY_error(cache->hashtable)) {
930                 ctx = NULL;
931                 ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
932                 goto err;
933             }
934         } else {
935             /*
936              * We raced with another thread to construct this and lost. Free
937              * what we just created and use the entry from the hashtable instead
938              */
939             decoder_cache_entry_free(newcache);
940             ctx = res->template;
941         }
942     } else {
943         ctx = res->template;
944     }
945 
946     ctx = ossl_decoder_ctx_for_pkey_dup(ctx, pkey, input_type, input_structure);
947     CRYPTO_THREAD_unlock(cache->lock);
948 
949     return ctx;
950  err:
951     decoder_cache_entry_free(newcache);
952     OSSL_DECODER_CTX_free(ctx);
953     return NULL;
954 }
955