Coverage Report

Created: 2025-12-10 06:24

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