Coverage Report

Created: 2025-07-11 06:57

/src/openssl/crypto/encode_decode/decoder_pkey.c
Line
Count
Source (jump to first uncovered line)
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
26
int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
27
                                    const unsigned char *kstr,
28
                                    size_t klen)
29
0
{
30
0
    return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
31
0
}
32
33
int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
34
                                       const UI_METHOD *ui_method,
35
                                       void *ui_data)
36
0
{
37
0
    return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
38
0
}
39
40
int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
41
                                         pem_password_cb *cb, void *cbarg)
42
0
{
43
0
    return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
44
0
}
45
46
int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
47
                                       OSSL_PASSPHRASE_CALLBACK *cb,
48
                                       void *cbarg)
49
0
{
50
0
    return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
51
0
}
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
71
static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst,
72
                                  const OSSL_PARAM *params,
73
                                  void *construct_data)
74
0
{
75
0
    struct decoder_pkey_data_st *data = construct_data;
76
0
    OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
77
0
    void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
78
0
    const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
79
0
    EVP_KEYMGMT *keymgmt = NULL;
80
0
    const OSSL_PROVIDER *keymgmt_prov = NULL;
81
0
    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
0
    void *object_ref = NULL;
91
0
    size_t object_ref_sz = 0;
92
0
    const OSSL_PARAM *p;
93
94
0
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
95
0
    if (p != NULL) {
96
0
        char *object_type = NULL;
97
98
0
        if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
99
0
            return 0;
100
0
        OPENSSL_free(data->object_type);
101
0
        data->object_type = object_type;
102
0
    }
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
0
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
110
0
    if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
111
0
        return 0;
112
0
    object_ref = p->data;
113
0
    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
0
    end = sk_EVP_KEYMGMT_num(data->keymgmts);
120
0
    for (i = 0; i < end; i++) {
121
0
        keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
122
0
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
123
124
0
        if (keymgmt_prov == decoder_prov
125
0
            && evp_keymgmt_has_load(keymgmt)
126
0
            && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
127
0
            break;
128
0
    }
129
0
    if (i < end) {
130
        /* To allow it to be freed further down */
131
0
        if (!EVP_KEYMGMT_up_ref(keymgmt))
132
0
            return 0;
133
0
    } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx,
134
0
                                            data->object_type,
135
0
                                            data->propq)) != NULL) {
136
0
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
137
0
    }
138
139
0
    if (keymgmt != NULL) {
140
0
        EVP_PKEY *pkey = NULL;
141
0
        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
0
        if (keymgmt_prov == decoder_prov) {
152
0
            keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
153
0
        } else {
154
0
            struct evp_keymgmt_util_try_import_data_st import_data;
155
156
0
            import_data.keymgmt = keymgmt;
157
0
            import_data.keydata = NULL;
158
0
            if (data->selection == 0)
159
                /* import/export functions do not tolerate 0 selection */
160
0
                import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
161
0
            else
162
0
                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
0
            (void)decoder->export_object(decoderctx,
169
0
                                         object_ref, object_ref_sz,
170
0
                                         &evp_keymgmt_util_try_import,
171
0
                                         &import_data);
172
0
            keydata = import_data.keydata;
173
0
            import_data.keydata = NULL;
174
0
        }
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
0
        if (keydata == NULL)
182
0
            ossl_decoder_ctx_set_harderr(data->ctx);
183
184
0
        if (keydata != NULL
185
0
            && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
186
0
            evp_keymgmt_freedata(keymgmt, keydata);
187
188
0
        *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
0
        EVP_KEYMGMT_free(keymgmt);
195
0
    }
196
    /*
197
     * We successfully looked through, |*ctx->object| determines if we
198
     * actually found something.
199
     */
200
0
    return (*data->object != NULL);
201
0
}
202
203
static void decoder_clean_pkey_construct_arg(void *construct_data)
204
0
{
205
0
    struct decoder_pkey_data_st *data = construct_data;
206
207
0
    if (data != NULL) {
208
0
        sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
209
0
        OPENSSL_free(data->propq);
210
0
        OPENSSL_free(data->object_type);
211
0
        OPENSSL_free(data);
212
0
    }
213
0
}
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
 */
234
static int collect_decoder_keymgmt(EVP_KEYMGMT *keymgmt, OSSL_DECODER *decoder,
235
                                   void *provctx, struct collect_data_st *data)
236
0
{
237
0
    void *decoderctx = NULL;
238
0
    OSSL_DECODER_INSTANCE *di = NULL;
239
0
    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
0
    if (keymgmt->name_id != decoder->base.id)
247
        /* Mismatch is not an error, continue. */
248
0
        return 0;
249
250
0
    if ((decoderctx = decoder->newctx(provctx)) == NULL) {
251
0
        data->error_occurred = 1;
252
0
        return 0;
253
0
    }
254
255
0
    if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
256
0
        decoder->freectx(decoderctx);
257
0
        data->error_occurred = 1;
258
0
        return 0;
259
0
    }
260
261
    /*
262
     * Input types must be compatible, but we must accept DER encoders when the
263
     * start input type is "PEM".
264
     */
265
0
    if (data->ctx->start_input_type != NULL
266
0
        && di->input_type != NULL
267
0
        && OPENSSL_strcasecmp(di->input_type, data->ctx->start_input_type) != 0
268
0
        && (OPENSSL_strcasecmp(di->input_type, "DER") != 0
269
0
            || OPENSSL_strcasecmp(data->ctx->start_input_type, "PEM") != 0)) {
270
        /* Mismatch is not an error, continue. */
271
0
        ossl_decoder_instance_free(di);
272
0
        return 0;
273
0
    }
274
275
0
    OSSL_TRACE_BEGIN(DECODER) {
276
0
        BIO_printf(trc_out,
277
0
                   "(ctx %p) Checking out decoder %p:\n"
278
0
                   "    %s with %s\n",
279
0
                   (void *)data->ctx, (void *)decoder,
280
0
                   OSSL_DECODER_get0_name(decoder),
281
0
                   OSSL_DECODER_get0_properties(decoder));
282
0
    } OSSL_TRACE_END(DECODER);
283
284
    /*
285
     * Get the property match score so the decoders can be prioritized later.
286
     */
287
0
    props = ossl_decoder_parsed_properties(decoder);
288
0
    if (data->pq != NULL && props != NULL) {
289
0
        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
0
        if (di->score < 0) {
295
0
            ossl_decoder_instance_free(di);
296
0
            return 0;
297
0
        }
298
0
    }
299
300
0
    if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
301
0
        ossl_decoder_instance_free(di);
302
0
        data->error_occurred = 1;
303
0
        return 0;
304
0
    }
305
306
0
    ++data->total;
307
0
    return 1;
308
0
}
309
310
static void collect_decoder(OSSL_DECODER *decoder, void *arg)
311
0
{
312
0
    struct collect_data_st *data = arg;
313
0
    STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts;
314
0
    int i, end_i;
315
0
    EVP_KEYMGMT *keymgmt;
316
0
    const OSSL_PROVIDER *prov;
317
0
    void *provctx;
318
319
0
    if (data->error_occurred)
320
0
        return;
321
322
0
    prov = OSSL_DECODER_get0_provider(decoder);
323
0
    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
0
    if (decoder->does_selection != NULL
331
0
            && !decoder->does_selection(provctx, data->ctx->selection))
332
0
        return;
333
334
0
    OSSL_TRACE_BEGIN(DECODER) {
335
0
        BIO_printf(trc_out,
336
0
                   "(ctx %p) Checking out decoder %p:\n"
337
0
                   "    %s with %s\n",
338
0
                   (void *)data->ctx, (void *)decoder,
339
0
                   OSSL_DECODER_get0_name(decoder),
340
0
                   OSSL_DECODER_get0_properties(decoder));
341
0
    } OSSL_TRACE_END(DECODER);
342
343
0
    end_i = sk_EVP_KEYMGMT_num(keymgmts);
344
0
    for (i = 0; i < end_i; ++i) {
345
0
        keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i);
346
347
        /* Only add this decoder once */
348
0
        if (collect_decoder_keymgmt(keymgmt, decoder, provctx, data))
349
0
            break;
350
0
        if (data->error_occurred)
351
0
            return;
352
0
    }
353
0
}
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
 */
359
static int check_keymgmt(EVP_KEYMGMT *keymgmt, struct collect_data_st *data)
360
0
{
361
    /* If no keytype was specified, everything matches. */
362
0
    if (data->keytype == NULL)
363
0
        return 1;
364
365
0
    if (!data->keytype_resolved) {
366
        /* We haven't cached the IDs from the keytype string yet. */
367
0
        OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx);
368
0
        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
0
        if (data->keytype_id != 0
375
0
            && (strcmp(data->keytype, "id-ecPublicKey") == 0
376
0
                || strcmp(data->keytype, "1.2.840.10045.2.1") == 0))
377
0
            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
0
        data->keytype_resolved = 1;
384
0
    }
385
386
    /* Specified keytype could not be resolved, so nothing matches. */
387
0
    if (data->keytype_id == 0)
388
0
        return 0;
389
390
    /* Does not match the keytype specified, so skip. */
391
0
    if (keymgmt->name_id != data->keytype_id
392
0
        && keymgmt->name_id != data->sm2_id)
393
0
        return 0;
394
395
0
    return 1;
396
0
}
397
398
static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
399
0
{
400
0
    struct collect_data_st *data = arg;
401
402
0
    if (!check_keymgmt(keymgmt, data))
403
0
        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
0
    if (!EVP_KEYMGMT_up_ref(keymgmt))
413
0
        return;
414
415
0
    if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) {
416
0
        EVP_KEYMGMT_free(keymgmt);
417
0
        data->error_occurred = 1;
418
0
    }
419
0
}
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
 */
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
0
{
431
0
    int ok = 0;
432
0
    struct decoder_pkey_data_st *process_data = NULL;
433
0
    struct collect_data_st collect_data = { NULL };
434
0
    STACK_OF(EVP_KEYMGMT) *keymgmts = NULL;
435
0
    OSSL_PROPERTY_LIST **plp;
436
0
    OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
437
438
0
    OSSL_TRACE_BEGIN(DECODER) {
439
0
        const char *input_type = ctx->start_input_type;
440
0
        const char *input_structure = ctx->input_structure;
441
442
0
        BIO_printf(trc_out,
443
0
                   "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n",
444
0
                   (void *)ctx,
445
0
                   keytype != NULL ? keytype : "",
446
0
                   keytype != NULL ? " keys" : "keys of any type",
447
0
                   input_type != NULL ? " from " : "",
448
0
                   input_type != NULL ? input_type : "",
449
0
                   input_structure != NULL ? " with " : "",
450
0
                   input_structure != NULL ? input_structure : "");
451
0
    } OSSL_TRACE_END(DECODER);
452
453
    /* Allocate data. */
454
0
    if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL)
455
0
        goto err;
456
0
    if ((propquery != NULL
457
0
            && (process_data->propq = OPENSSL_strdup(propquery)) == NULL))
458
0
        goto err;
459
460
    /* Allocate our list of EVP_KEYMGMTs. */
461
0
    keymgmts = sk_EVP_KEYMGMT_new_null();
462
0
    if (keymgmts == NULL) {
463
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
464
0
        goto err;
465
0
    }
466
467
0
    process_data->object    = NULL;
468
0
    process_data->libctx    = libctx;
469
0
    process_data->selection = ctx->selection;
470
0
    process_data->keymgmts  = keymgmts;
471
472
    /*
473
     * Collect passed and default properties to prioritize the decoders.
474
     */
475
0
    if (propquery != NULL)
476
0
        p2 = pq = ossl_parse_query(libctx, propquery, 1);
477
478
0
    plp = ossl_ctx_global_properties(libctx, 0);
479
0
    if (plp != NULL && *plp != NULL) {
480
0
        if (pq == NULL) {
481
0
            pq = *plp;
482
0
        } else {
483
0
            p2 = ossl_property_merge(pq, *plp);
484
0
            ossl_property_free(pq);
485
0
            if (p2 == NULL)
486
0
                goto err;
487
0
            pq = p2;
488
0
        }
489
0
    }
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
0
    collect_data.ctx            = ctx;
507
0
    collect_data.libctx         = libctx;
508
0
    collect_data.keymgmts       = keymgmts;
509
0
    collect_data.keytype        = keytype;
510
0
    collect_data.pq             = pq;
511
0
    EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data);
512
513
0
    if (collect_data.error_occurred)
514
0
        goto err;
515
516
    /* Enumerate all matching decoders. */
517
0
    OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data);
518
519
0
    if (collect_data.error_occurred)
520
0
        goto err;
521
522
0
    OSSL_TRACE_BEGIN(DECODER) {
523
0
        BIO_printf(trc_out,
524
0
                   "(ctx %p) Got %d decoders producing keys\n",
525
0
                   (void *)ctx, collect_data.total);
526
0
    } 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
0
    if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
534
0
        if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
535
0
            || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
536
0
            || !OSSL_DECODER_CTX_set_cleanup(ctx,
537
0
                                             decoder_clean_pkey_construct_arg))
538
0
            goto err;
539
540
0
        process_data = NULL; /* Avoid it being freed */
541
0
    }
542
543
0
    ok = 1;
544
0
 err:
545
0
    decoder_clean_pkey_construct_arg(process_data);
546
0
    ossl_property_free(p2);
547
0
    return ok;
548
0
}
549
550
/* Only const here because deep_copy requires it */
551
static EVP_KEYMGMT *keymgmt_dup(const EVP_KEYMGMT *keymgmt)
552
0
{
553
0
    if (!EVP_KEYMGMT_up_ref((EVP_KEYMGMT *)keymgmt))
554
0
        return NULL;
555
556
0
    return (EVP_KEYMGMT *)keymgmt;
557
0
}
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 *
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
0
{
571
0
    OSSL_DECODER_CTX *dest;
572
0
    struct decoder_pkey_data_st *process_data_src, *process_data_dest = NULL;
573
574
0
    if (src == NULL)
575
0
        return NULL;
576
577
0
    if ((dest = OSSL_DECODER_CTX_new()) == NULL) {
578
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
579
0
        return NULL;
580
0
    }
581
582
0
    if (!OSSL_DECODER_CTX_set_input_type(dest, input_type)
583
0
            || !OSSL_DECODER_CTX_set_input_structure(dest, input_structure)) {
584
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
585
0
        goto err;
586
0
    }
587
0
    dest->selection = src->selection;
588
589
0
    if (src->decoder_insts != NULL) {
590
0
        dest->decoder_insts
591
0
            = sk_OSSL_DECODER_INSTANCE_deep_copy(src->decoder_insts,
592
0
                                                 ossl_decoder_instance_dup,
593
0
                                                 ossl_decoder_instance_free);
594
0
        if (dest->decoder_insts == NULL) {
595
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
596
0
            goto err;
597
0
        }
598
0
    }
599
600
0
    if (!OSSL_DECODER_CTX_set_construct(dest,
601
0
                                        OSSL_DECODER_CTX_get_construct(src))) {
602
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
603
0
        goto err;
604
0
    }
605
606
0
    process_data_src = OSSL_DECODER_CTX_get_construct_data(src);
607
0
    if (process_data_src != NULL) {
608
0
        process_data_dest = OPENSSL_zalloc(sizeof(*process_data_dest));
609
0
        if (process_data_dest == NULL) {
610
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
611
0
            goto err;
612
0
        }
613
0
        if (process_data_src->propq != NULL) {
614
0
            process_data_dest->propq = OPENSSL_strdup(process_data_src->propq);
615
0
            if (process_data_dest->propq == NULL) {
616
0
                ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
617
0
                goto err;
618
0
            }
619
0
        }
620
621
0
        if (process_data_src->keymgmts != NULL) {
622
0
            process_data_dest->keymgmts
623
0
                = sk_EVP_KEYMGMT_deep_copy(process_data_src->keymgmts,
624
0
                                           keymgmt_dup,
625
0
                                           EVP_KEYMGMT_free);
626
0
            if (process_data_dest->keymgmts == NULL) {
627
0
                ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_EVP_LIB);
628
0
                goto err;
629
0
            }
630
0
        }
631
632
0
        process_data_dest->object    = (void **)pkey;
633
0
        process_data_dest->libctx    = process_data_src->libctx;
634
0
        process_data_dest->selection = process_data_src->selection;
635
0
        process_data_dest->ctx       = dest;
636
0
        if (!OSSL_DECODER_CTX_set_construct_data(dest, process_data_dest)) {
637
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
638
0
            goto err;
639
0
        }
640
0
        process_data_dest = NULL;
641
0
    }
642
643
0
    if (!OSSL_DECODER_CTX_set_cleanup(dest,
644
0
                                      OSSL_DECODER_CTX_get_cleanup(src))) {
645
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
646
0
        goto err;
647
0
    }
648
649
0
    return dest;
650
0
 err:
651
0
    decoder_clean_pkey_construct_arg(process_data_dest);
652
0
    OSSL_DECODER_CTX_free(dest);
653
0
    return NULL;
654
0
}
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
672
static void decoder_cache_entry_free(DECODER_CACHE_ENTRY *entry)
673
0
{
674
0
    if (entry == NULL)
675
0
        return;
676
0
    OPENSSL_free(entry->input_type);
677
0
    OPENSSL_free(entry->input_structure);
678
0
    OPENSSL_free(entry->keytype);
679
0
    OPENSSL_free(entry->propquery);
680
0
    OSSL_DECODER_CTX_free(entry->template);
681
0
    OPENSSL_free(entry);
682
0
}
683
684
static unsigned long decoder_cache_entry_hash(const DECODER_CACHE_ENTRY *cache)
685
0
{
686
0
    unsigned long hash = 17;
687
688
0
    hash = (hash * 23)
689
0
           + (cache->propquery == NULL
690
0
              ? 0 : ossl_lh_strcasehash(cache->propquery));
691
0
    hash = (hash * 23)
692
0
           + (cache->input_structure == NULL
693
0
              ? 0  : ossl_lh_strcasehash(cache->input_structure));
694
0
    hash = (hash * 23)
695
0
           + (cache->input_type == NULL
696
0
              ? 0  : ossl_lh_strcasehash(cache->input_type));
697
0
    hash = (hash * 23)
698
0
           + (cache->keytype == NULL
699
0
              ? 0  : ossl_lh_strcasehash(cache->keytype));
700
701
0
    hash ^= cache->selection;
702
703
0
    return hash;
704
0
}
705
706
static ossl_inline int nullstrcmp(const char *a, const char *b, int casecmp)
707
0
{
708
0
    if (a == NULL || b == NULL) {
709
0
        if (a == NULL) {
710
0
            if (b == NULL)
711
0
                return 0;
712
0
            else
713
0
                return 1;
714
0
        } else {
715
0
            return -1;
716
0
        }
717
0
    } else {
718
0
        if (casecmp)
719
0
            return OPENSSL_strcasecmp(a, b);
720
0
        else
721
0
            return strcmp(a, b);
722
0
    }
723
0
}
724
725
static int decoder_cache_entry_cmp(const DECODER_CACHE_ENTRY *a,
726
                                   const DECODER_CACHE_ENTRY *b)
727
0
{
728
0
    int cmp;
729
730
0
    if (a->selection != b->selection)
731
0
        return (a->selection < b->selection) ? -1 : 1;
732
733
0
    cmp = nullstrcmp(a->keytype, b->keytype, 1);
734
0
    if (cmp != 0)
735
0
        return cmp;
736
737
0
    cmp = nullstrcmp(a->input_type, b->input_type, 1);
738
0
    if (cmp != 0)
739
0
        return cmp;
740
741
0
    cmp = nullstrcmp(a->input_structure, b->input_structure, 1);
742
0
    if (cmp != 0)
743
0
        return cmp;
744
745
0
    cmp = nullstrcmp(a->propquery, b->propquery, 0);
746
747
0
    return cmp;
748
0
}
749
750
void *ossl_decoder_cache_new(OSSL_LIB_CTX *ctx)
751
16
{
752
16
    DECODER_CACHE *cache = OPENSSL_malloc(sizeof(*cache));
753
754
16
    if (cache == NULL)
755
0
        return NULL;
756
757
16
    cache->lock = CRYPTO_THREAD_lock_new();
758
16
    if (cache->lock == NULL) {
759
0
        OPENSSL_free(cache);
760
0
        return NULL;
761
0
    }
762
16
    cache->hashtable = lh_DECODER_CACHE_ENTRY_new(decoder_cache_entry_hash,
763
16
                                                  decoder_cache_entry_cmp);
764
16
    if (cache->hashtable == NULL) {
765
0
        CRYPTO_THREAD_lock_free(cache->lock);
766
0
        OPENSSL_free(cache);
767
0
        return NULL;
768
0
    }
769
770
16
    return cache;
771
16
}
772
773
void ossl_decoder_cache_free(void *vcache)
774
16
{
775
16
    DECODER_CACHE *cache = (DECODER_CACHE *)vcache;
776
777
16
    lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
778
16
    lh_DECODER_CACHE_ENTRY_free(cache->hashtable);
779
16
    CRYPTO_THREAD_lock_free(cache->lock);
780
16
    OPENSSL_free(cache);
781
16
}
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
 */
787
int ossl_decoder_cache_flush(OSSL_LIB_CTX *libctx)
788
16
{
789
16
    DECODER_CACHE *cache
790
16
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
791
792
16
    if (cache == NULL)
793
16
        return 0;
794
795
796
0
    if (!CRYPTO_THREAD_write_lock(cache->lock)) {
797
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
798
0
        return 0;
799
0
    }
800
801
0
    lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
802
0
    lh_DECODER_CACHE_ENTRY_flush(cache->hashtable);
803
804
0
    CRYPTO_THREAD_unlock(cache->lock);
805
0
    return 1;
806
0
}
807
808
OSSL_DECODER_CTX *
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
0
{
815
0
    OSSL_DECODER_CTX *ctx = NULL;
816
0
    OSSL_PARAM decoder_params[] = {
817
0
        OSSL_PARAM_END,
818
0
        OSSL_PARAM_END,
819
0
        OSSL_PARAM_END
820
0
    };
821
0
    DECODER_CACHE *cache
822
0
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
823
0
    DECODER_CACHE_ENTRY cacheent, *res, *newcache = NULL;
824
0
    int i = 0;
825
826
0
    if (cache == NULL) {
827
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
828
0
        return NULL;
829
0
    }
830
0
    if (input_structure != NULL)
831
0
        decoder_params[i++] =
832
0
            OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE,
833
0
                                             (char *)input_structure, 0);
834
0
    if (propquery != NULL)
835
0
        decoder_params[i++] =
836
0
            OSSL_PARAM_construct_utf8_string(OSSL_DECODER_PARAM_PROPERTIES,
837
0
                                             (char *)propquery, 0);
838
839
    /* It is safe to cast away the const here */
840
0
    cacheent.input_type = (char *)input_type;
841
0
    cacheent.input_structure = (char *)input_structure;
842
0
    cacheent.keytype = (char *)keytype;
843
0
    cacheent.selection = selection;
844
0
    cacheent.propquery = (char *)propquery;
845
846
0
    if (!CRYPTO_THREAD_read_lock(cache->lock)) {
847
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
848
0
        return NULL;
849
0
    }
850
851
    /* First see if we have a template OSSL_DECODER_CTX */
852
0
    res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
853
854
0
    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
0
        CRYPTO_THREAD_unlock(cache->lock);
861
862
0
        if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
863
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
864
0
            return NULL;
865
0
        }
866
867
0
        OSSL_TRACE_BEGIN(DECODER) {
868
0
            BIO_printf(trc_out,
869
0
                    "(ctx %p) Looking for %s decoders with selection %d\n",
870
0
                    (void *)ctx, keytype, selection);
871
0
            BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
872
0
                    input_type, input_structure);
873
0
        } OSSL_TRACE_END(DECODER);
874
875
0
        if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
876
0
            && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
877
0
            && OSSL_DECODER_CTX_set_selection(ctx, selection)
878
0
            && ossl_decoder_ctx_setup_for_pkey(ctx, keytype, libctx, propquery)
879
0
            && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)
880
0
            && (propquery == NULL
881
0
                || OSSL_DECODER_CTX_set_params(ctx, decoder_params))) {
882
0
            OSSL_TRACE_BEGIN(DECODER) {
883
0
                BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
884
0
                        (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
885
0
            } OSSL_TRACE_END(DECODER);
886
0
        } else {
887
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
888
0
            OSSL_DECODER_CTX_free(ctx);
889
0
            return NULL;
890
0
        }
891
892
0
        newcache = OPENSSL_zalloc(sizeof(*newcache));
893
0
        if (newcache == NULL) {
894
0
            OSSL_DECODER_CTX_free(ctx);
895
0
            return NULL;
896
0
        }
897
898
0
        if (input_type != NULL) {
899
0
            newcache->input_type = OPENSSL_strdup(input_type);
900
0
            if (newcache->input_type == NULL)
901
0
                goto err;
902
0
        }
903
0
        if (input_structure != NULL) {
904
0
            newcache->input_structure = OPENSSL_strdup(input_structure);
905
0
            if (newcache->input_structure == NULL)
906
0
                goto err;
907
0
        }
908
0
        if (keytype != NULL) {
909
0
            newcache->keytype = OPENSSL_strdup(keytype);
910
0
            if (newcache->keytype == NULL)
911
0
                goto err;
912
0
        }
913
0
        if (propquery != NULL) {
914
0
            newcache->propquery = OPENSSL_strdup(propquery);
915
0
            if (newcache->propquery == NULL)
916
0
                goto err;
917
0
        }
918
0
        newcache->selection = selection;
919
0
        newcache->template = ctx;
920
921
0
        if (!CRYPTO_THREAD_write_lock(cache->lock)) {
922
0
            ctx = NULL;
923
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
924
0
            goto err;
925
0
        }
926
0
        res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
927
0
        if (res == NULL) {
928
0
            (void)lh_DECODER_CACHE_ENTRY_insert(cache->hashtable, newcache);
929
0
            if (lh_DECODER_CACHE_ENTRY_error(cache->hashtable)) {
930
0
                ctx = NULL;
931
0
                ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
932
0
                goto err;
933
0
            }
934
0
        } 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
0
            decoder_cache_entry_free(newcache);
940
0
            ctx = res->template;
941
0
        }
942
0
    } else {
943
0
        ctx = res->template;
944
0
    }
945
946
0
    ctx = ossl_decoder_ctx_for_pkey_dup(ctx, pkey, input_type, input_structure);
947
0
    CRYPTO_THREAD_unlock(cache->lock);
948
949
0
    return ctx;
950
0
 err:
951
0
    decoder_cache_entry_free(newcache);
952
0
    OSSL_DECODER_CTX_free(ctx);
953
0
    return NULL;
954
0
}