Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/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
124k
{
43
124k
    return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
44
124k
}
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
862k
{
75
862k
    struct decoder_pkey_data_st *data = construct_data;
76
862k
    OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
77
862k
    void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
78
862k
    const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
79
862k
    EVP_KEYMGMT *keymgmt = NULL;
80
862k
    const OSSL_PROVIDER *keymgmt_prov = NULL;
81
862k
    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
862k
    void *object_ref = NULL;
91
862k
    size_t object_ref_sz = 0;
92
862k
    const OSSL_PARAM *p;
93
94
862k
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
95
862k
    if (p != NULL) {
96
862k
        char *object_type = NULL;
97
98
862k
        if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
99
0
            return 0;
100
862k
        OPENSSL_free(data->object_type);
101
862k
        data->object_type = object_type;
102
862k
    }
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
862k
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
110
862k
    if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
111
520k
        return 0;
112
342k
    object_ref = p->data;
113
342k
    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
342k
    end = sk_EVP_KEYMGMT_num(data->keymgmts);
120
575k
    for (i = 0; i < end; i++) {
121
575k
        keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
122
575k
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
123
124
575k
        if (keymgmt_prov == decoder_prov
125
575k
            && evp_keymgmt_has_load(keymgmt)
126
574k
            && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
127
342k
            break;
128
575k
    }
129
342k
    if (i < end) {
130
        /* To allow it to be freed further down */
131
342k
        if (!EVP_KEYMGMT_up_ref(keymgmt))
132
0
            return 0;
133
342k
    } 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
342k
    if (keymgmt != NULL) {
141
342k
        EVP_PKEY *pkey = NULL;
142
342k
        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
342k
        if (keymgmt_prov == decoder_prov) {
153
342k
            keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
154
342k
        } 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
342k
        if (keydata == NULL)
183
21
            ossl_decoder_ctx_set_harderr(data->ctx);
184
185
342k
        if (keydata != NULL
186
342k
            && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
187
0
            evp_keymgmt_freedata(keymgmt, keydata);
188
189
342k
        *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
342k
        EVP_KEYMGMT_free(keymgmt);
196
342k
    }
197
    /*
198
     * We successfully looked through, |*ctx->object| determines if we
199
     * actually found something.
200
     */
201
342k
    return (*data->object != NULL);
202
342k
}
203
204
static void decoder_clean_pkey_construct_arg(void *construct_data)
205
1.52M
{
206
1.52M
    struct decoder_pkey_data_st *data = construct_data;
207
208
1.52M
    if (data != NULL) {
209
1.27M
        sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
210
1.27M
        OPENSSL_free(data->propq);
211
1.27M
        OPENSSL_free(data->object_type);
212
1.27M
        OPENSSL_free(data);
213
1.27M
    }
214
1.52M
}
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
37.5k
{
238
37.5k
    void *decoderctx = NULL;
239
37.5k
    OSSL_DECODER_INSTANCE *di = NULL;
240
37.5k
    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
37.5k
    if (keymgmt->name_id != decoder->base.id)
248
        /* Mismatch is not an error, continue. */
249
36.0k
        return 0;
250
251
1.49k
    if ((decoderctx = decoder->newctx(provctx)) == NULL) {
252
0
        data->error_occurred = 1;
253
0
        return 0;
254
0
    }
255
256
1.49k
    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
1.49k
    if (data->ctx->start_input_type != NULL
267
1.27k
        && di->input_type != NULL
268
1.27k
        && OPENSSL_strcasecmp(di->input_type, data->ctx->start_input_type) != 0
269
335
        && (OPENSSL_strcasecmp(di->input_type, "DER") != 0
270
216
            || OPENSSL_strcasecmp(data->ctx->start_input_type, "PEM") != 0)) {
271
        /* Mismatch is not an error, continue. */
272
119
        ossl_decoder_instance_free(di);
273
119
        return 0;
274
119
    }
275
276
1.37k
    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
1.37k
    OSSL_TRACE_END(DECODER);
286
287
    /*
288
     * Get the property match score so the decoders can be prioritized later.
289
     */
290
1.37k
    props = ossl_decoder_parsed_properties(decoder);
291
1.37k
    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
1.37k
    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
1.37k
    ++data->total;
310
1.37k
    return 1;
311
1.37k
}
312
313
static void collect_decoder(OSSL_DECODER *decoder, void *arg)
314
796k
{
315
796k
    struct collect_data_st *data = arg;
316
796k
    STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts;
317
796k
    int i, end_i;
318
796k
    EVP_KEYMGMT *keymgmt;
319
796k
    const OSSL_PROVIDER *prov;
320
796k
    void *provctx;
321
322
796k
    if (data->error_occurred)
323
0
        return;
324
325
796k
    prov = OSSL_DECODER_get0_provider(decoder);
326
796k
    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
796k
    if (decoder->does_selection != NULL
334
765k
        && !decoder->does_selection(provctx, data->ctx->selection))
335
397k
        return;
336
337
398k
    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
398k
    OSSL_TRACE_END(DECODER);
347
348
398k
    end_i = sk_EVP_KEYMGMT_num(keymgmts);
349
435k
    for (i = 0; i < end_i; ++i) {
350
37.5k
        keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i);
351
352
        /* Only add this decoder once */
353
37.5k
        if (collect_decoder_keymgmt(keymgmt, decoder, provctx, data))
354
1.37k
            break;
355
36.1k
        if (data->error_occurred)
356
0
            return;
357
36.1k
    }
358
398k
}
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
529k
{
366
    /* If no keytype was specified, everything matches. */
367
529k
    if (data->keytype == NULL)
368
624
        return 1;
369
370
528k
    if (!data->keytype_resolved) {
371
        /* We haven't cached the IDs from the keytype string yet. */
372
16.5k
        OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx);
373
16.5k
        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
16.5k
        if (data->keytype_id != 0
380
958
            && (strcmp(data->keytype, "id-ecPublicKey") == 0
381
913
                || strcmp(data->keytype, "1.2.840.10045.2.1") == 0))
382
45
            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
16.5k
        data->keytype_resolved = 1;
389
16.5k
    }
390
391
    /* Specified keytype could not be resolved, so nothing matches. */
392
528k
    if (data->keytype_id == 0)
393
494k
        return 0;
394
395
    /* Does not match the keytype specified, so skip. */
396
33.6k
    if (keymgmt->name_id != data->keytype_id
397
32.8k
        && keymgmt->name_id != data->sm2_id)
398
32.7k
        return 0;
399
400
848
    return 1;
401
33.6k
}
402
403
static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
404
529k
{
405
529k
    struct collect_data_st *data = arg;
406
407
529k
    if (!check_keymgmt(keymgmt, data))
408
527k
        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
1.47k
    if (!EVP_KEYMGMT_up_ref(keymgmt))
418
0
        return;
419
420
1.47k
    if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) {
421
0
        EVP_KEYMGMT_free(keymgmt);
422
0
        data->error_occurred = 1;
423
0
    }
424
1.47k
}
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
10.4k
{
436
10.4k
    int ok = 0;
437
10.4k
    struct decoder_pkey_data_st *process_data = NULL;
438
10.4k
    struct collect_data_st collect_data = { NULL };
439
10.4k
    STACK_OF(EVP_KEYMGMT) *keymgmts = NULL;
440
10.4k
    OSSL_PROPERTY_LIST **plp;
441
10.4k
    OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL;
442
443
10.4k
    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
10.4k
    OSSL_TRACE_END(DECODER);
459
460
    /* Allocate data. */
461
10.4k
    if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL)
462
0
        goto err;
463
10.4k
    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
10.4k
    keymgmts = sk_EVP_KEYMGMT_new_null();
469
10.4k
    if (keymgmts == NULL) {
470
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
471
0
        goto err;
472
0
    }
473
474
10.4k
    process_data->object = NULL;
475
10.4k
    process_data->libctx = libctx;
476
10.4k
    process_data->selection = ctx->selection;
477
10.4k
    process_data->keymgmts = keymgmts;
478
479
    /*
480
     * Collect passed and default properties to prioritize the decoders.
481
     */
482
10.4k
    if (propquery != NULL)
483
0
        p2 = pq = ossl_parse_query(libctx, propquery, 1);
484
485
10.4k
    plp = ossl_ctx_global_properties(libctx, 0);
486
10.4k
    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
10.4k
    collect_data.ctx = ctx;
514
10.4k
    collect_data.libctx = libctx;
515
10.4k
    collect_data.keymgmts = keymgmts;
516
10.4k
    collect_data.keytype = keytype;
517
10.4k
    collect_data.pq = pq;
518
10.4k
    EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data);
519
520
10.4k
    if (collect_data.error_occurred)
521
0
        goto err;
522
523
    /* Enumerate all matching decoders. */
524
10.4k
    OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data);
525
526
10.4k
    if (collect_data.error_occurred)
527
0
        goto err;
528
529
10.4k
    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
10.4k
    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
10.4k
    if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
543
658
        if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
544
658
            || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
545
658
            || !OSSL_DECODER_CTX_set_cleanup(ctx,
546
658
                decoder_clean_pkey_construct_arg))
547
0
            goto err;
548
549
658
        process_data = NULL; /* Avoid it being freed */
550
658
    }
551
552
10.4k
    ok = 1;
553
10.4k
err:
554
10.4k
    decoder_clean_pkey_construct_arg(process_data);
555
10.4k
    ossl_property_free(p2);
556
10.4k
    return ok;
557
10.4k
}
558
559
/* Only const here because deep_copy requires it */
560
static EVP_KEYMGMT *keymgmt_dup(const EVP_KEYMGMT *keymgmt)
561
7.81M
{
562
7.81M
    if (!EVP_KEYMGMT_up_ref((EVP_KEYMGMT *)keymgmt))
563
0
        return NULL;
564
565
7.81M
    return (EVP_KEYMGMT *)keymgmt;
566
7.81M
}
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
620k
{
580
620k
    OSSL_DECODER_CTX *dest;
581
620k
    struct decoder_pkey_data_st *process_data_src, *process_data_dest = NULL;
582
583
620k
    if (src == NULL)
584
0
        return NULL;
585
586
620k
    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
620k
    if (!OSSL_DECODER_CTX_set_input_type(dest, input_type)
592
620k
        || !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
620k
    dest->selection = src->selection;
597
598
620k
    if (src->decoder_insts != NULL) {
599
574k
        dest->decoder_insts
600
574k
            = sk_OSSL_DECODER_INSTANCE_deep_copy(src->decoder_insts,
601
574k
                ossl_decoder_instance_dup,
602
574k
                ossl_decoder_instance_free);
603
574k
        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
574k
    }
608
609
620k
    if (!OSSL_DECODER_CTX_set_construct(dest,
610
620k
            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
620k
    process_data_src = OSSL_DECODER_CTX_get_construct_data(src);
616
620k
    if (process_data_src != NULL) {
617
574k
        process_data_dest = OPENSSL_zalloc(sizeof(*process_data_dest));
618
574k
        if (process_data_dest == NULL) {
619
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
620
0
            goto err;
621
0
        }
622
574k
        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
574k
        if (process_data_src->keymgmts != NULL) {
631
574k
            process_data_dest->keymgmts
632
574k
                = sk_EVP_KEYMGMT_deep_copy(process_data_src->keymgmts,
633
574k
                    keymgmt_dup,
634
574k
                    EVP_KEYMGMT_free);
635
574k
            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
574k
        }
640
641
574k
        process_data_dest->object = (void **)pkey;
642
574k
        process_data_dest->libctx = process_data_src->libctx;
643
574k
        process_data_dest->selection = process_data_src->selection;
644
574k
        process_data_dest->ctx = dest;
645
574k
        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
574k
        process_data_dest = NULL;
650
574k
    }
651
652
620k
    if (!OSSL_DECODER_CTX_set_cleanup(dest,
653
620k
            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
620k
    return dest;
659
0
err:
660
0
    decoder_clean_pkey_construct_arg(process_data_dest);
661
0
    OSSL_DECODER_CTX_free(dest);
662
0
    return NULL;
663
620k
}
664
665
typedef struct {
666
    char *input_type;
667
    char *input_structure;
668
    char *keytype;
669
    int selection;
670
    char *propquery;
671
    OSSL_DECODER_CTX *template;
672
} DECODER_CACHE_ENTRY;
673
674
DEFINE_LHASH_OF_EX(DECODER_CACHE_ENTRY);
675
676
typedef struct {
677
    CRYPTO_RWLOCK *lock;
678
    LHASH_OF(DECODER_CACHE_ENTRY) *hashtable;
679
} DECODER_CACHE;
680
681
static void decoder_cache_entry_free(DECODER_CACHE_ENTRY *entry)
682
12.6k
{
683
12.6k
    if (entry == NULL)
684
0
        return;
685
12.6k
    OPENSSL_free(entry->input_type);
686
12.6k
    OPENSSL_free(entry->input_structure);
687
12.6k
    OPENSSL_free(entry->keytype);
688
12.6k
    OPENSSL_free(entry->propquery);
689
12.6k
    OSSL_DECODER_CTX_free(entry->template);
690
12.6k
    OPENSSL_free(entry);
691
12.6k
}
692
693
static unsigned long decoder_cache_entry_hash(const DECODER_CACHE_ENTRY *cache)
694
1.11M
{
695
1.11M
    unsigned long hash = 17;
696
697
1.11M
    hash = (hash * 23)
698
1.11M
        + (cache->propquery == NULL
699
1.11M
                ? 0
700
1.11M
                : ossl_lh_strcasehash(cache->propquery));
701
1.11M
    hash = (hash * 23)
702
1.11M
        + (cache->input_structure == NULL
703
1.11M
                ? 0
704
1.11M
                : ossl_lh_strcasehash(cache->input_structure));
705
1.11M
    hash = (hash * 23)
706
1.11M
        + (cache->input_type == NULL
707
1.11M
                ? 0
708
1.11M
                : ossl_lh_strcasehash(cache->input_type));
709
1.11M
    hash = (hash * 23)
710
1.11M
        + (cache->keytype == NULL
711
1.11M
                ? 0
712
1.11M
                : ossl_lh_strcasehash(cache->keytype));
713
714
1.11M
    hash ^= cache->selection;
715
716
1.11M
    return hash;
717
1.11M
}
718
719
static ossl_inline int nullstrcmp(const char *a, const char *b, int casecmp)
720
4.24M
{
721
4.24M
    if (a == NULL || b == NULL) {
722
1.46M
        if (a == NULL) {
723
1.46M
            if (b == NULL)
724
1.46M
                return 0;
725
0
            else
726
0
                return 1;
727
1.46M
        } else {
728
0
            return -1;
729
0
        }
730
2.77M
    } else {
731
2.77M
        if (casecmp)
732
2.77M
            return OPENSSL_strcasecmp(a, b);
733
0
        else
734
0
            return strcmp(a, b);
735
2.77M
    }
736
4.24M
}
737
738
static int decoder_cache_entry_cmp(const DECODER_CACHE_ENTRY *a,
739
    const DECODER_CACHE_ENTRY *b)
740
1.06M
{
741
1.06M
    int cmp;
742
743
1.06M
    if (a->selection != b->selection)
744
0
        return (a->selection < b->selection) ? -1 : 1;
745
746
1.06M
    cmp = nullstrcmp(a->keytype, b->keytype, 1);
747
1.06M
    if (cmp != 0)
748
14
        return cmp;
749
750
1.06M
    cmp = nullstrcmp(a->input_type, b->input_type, 1);
751
1.06M
    if (cmp != 0)
752
0
        return cmp;
753
754
1.06M
    cmp = nullstrcmp(a->input_structure, b->input_structure, 1);
755
1.06M
    if (cmp != 0)
756
0
        return cmp;
757
758
1.06M
    cmp = nullstrcmp(a->propquery, b->propquery, 0);
759
760
1.06M
    return cmp;
761
1.06M
}
762
763
void *ossl_decoder_cache_new(OSSL_LIB_CTX *ctx)
764
378
{
765
378
    DECODER_CACHE *cache = OPENSSL_malloc(sizeof(*cache));
766
767
378
    if (cache == NULL)
768
0
        return NULL;
769
770
378
    cache->lock = CRYPTO_THREAD_lock_new();
771
378
    if (cache->lock == NULL) {
772
0
        OPENSSL_free(cache);
773
0
        return NULL;
774
0
    }
775
378
    cache->hashtable = lh_DECODER_CACHE_ENTRY_new(decoder_cache_entry_hash,
776
378
        decoder_cache_entry_cmp);
777
378
    if (cache->hashtable == NULL) {
778
0
        CRYPTO_THREAD_lock_free(cache->lock);
779
0
        OPENSSL_free(cache);
780
0
        return NULL;
781
0
    }
782
783
378
    return cache;
784
378
}
785
786
void ossl_decoder_cache_free(void *vcache)
787
196
{
788
196
    DECODER_CACHE *cache = (DECODER_CACHE *)vcache;
789
790
196
    lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
791
196
    lh_DECODER_CACHE_ENTRY_free(cache->hashtable);
792
196
    CRYPTO_THREAD_lock_free(cache->lock);
793
196
    OPENSSL_free(cache);
794
196
}
795
796
/*
797
 * Called whenever a provider gets activated/deactivated. In that case the
798
 * decoders that are available might change so we flush our cache.
799
 */
800
int ossl_decoder_cache_flush(OSSL_LIB_CTX *libctx)
801
291
{
802
291
    DECODER_CACHE *cache
803
291
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
804
805
291
    if (cache == NULL)
806
165
        return 0;
807
808
126
    if (!CRYPTO_THREAD_write_lock(cache->lock)) {
809
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
810
0
        return 0;
811
0
    }
812
813
126
    lh_DECODER_CACHE_ENTRY_doall(cache->hashtable, decoder_cache_entry_free);
814
126
    lh_DECODER_CACHE_ENTRY_flush(cache->hashtable);
815
816
126
    CRYPTO_THREAD_unlock(cache->lock);
817
126
    return 1;
818
126
}
819
820
OSSL_DECODER_CTX *
821
OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
822
    const char *input_type,
823
    const char *input_structure,
824
    const char *keytype, int selection,
825
    OSSL_LIB_CTX *libctx, const char *propquery)
826
620k
{
827
620k
    OSSL_DECODER_CTX *ctx = NULL;
828
620k
    OSSL_PARAM decoder_params[] = {
829
620k
        OSSL_PARAM_END,
830
620k
        OSSL_PARAM_END,
831
620k
        OSSL_PARAM_END
832
620k
    };
833
620k
    DECODER_CACHE *cache
834
620k
        = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_DECODER_CACHE_INDEX);
835
620k
    DECODER_CACHE_ENTRY cacheent, *res, *newcache = NULL;
836
620k
    int i = 0;
837
838
620k
    if (cache == NULL) {
839
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
840
0
        return NULL;
841
0
    }
842
620k
    if (input_structure != NULL)
843
528k
        decoder_params[i++] = OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_STRUCTURE,
844
528k
            (char *)input_structure, 0);
845
620k
    if (propquery != NULL)
846
0
        decoder_params[i++] = OSSL_PARAM_construct_utf8_string(OSSL_DECODER_PARAM_PROPERTIES,
847
0
            (char *)propquery, 0);
848
849
    /* It is safe to cast away the const here */
850
620k
    cacheent.input_type = (char *)input_type;
851
620k
    cacheent.input_structure = (char *)input_structure;
852
620k
    cacheent.keytype = (char *)keytype;
853
620k
    cacheent.selection = selection;
854
620k
    cacheent.propquery = (char *)propquery;
855
856
620k
    if (!CRYPTO_THREAD_read_lock(cache->lock)) {
857
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
858
0
        return NULL;
859
0
    }
860
861
    /* First see if we have a template OSSL_DECODER_CTX */
862
620k
    res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
863
864
620k
    if (res == NULL) {
865
        /*
866
         * There is no template so we will have to construct one. This will be
867
         * time consuming so release the lock and we will later upgrade it to a
868
         * write lock.
869
         */
870
10.4k
        CRYPTO_THREAD_unlock(cache->lock);
871
872
10.4k
        if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
873
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
874
0
            return NULL;
875
0
        }
876
877
10.4k
        OSSL_TRACE_BEGIN(DECODER)
878
0
        {
879
0
            BIO_printf(trc_out,
880
0
                "(ctx %p) Looking for %s decoders with selection %d\n",
881
0
                (void *)ctx, keytype, selection);
882
0
            BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
883
0
                input_type, input_structure);
884
0
        }
885
10.4k
        OSSL_TRACE_END(DECODER);
886
887
10.4k
        if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
888
10.4k
            && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
889
10.4k
            && OSSL_DECODER_CTX_set_selection(ctx, selection)
890
10.4k
            && ossl_decoder_ctx_setup_for_pkey(ctx, keytype, libctx, propquery)
891
10.4k
            && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)
892
10.4k
            && (propquery == NULL
893
10.4k
                || OSSL_DECODER_CTX_set_params(ctx, decoder_params))) {
894
10.4k
            OSSL_TRACE_BEGIN(DECODER)
895
0
            {
896
0
                BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
897
0
                    (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
898
0
            }
899
10.4k
            OSSL_TRACE_END(DECODER);
900
10.4k
        } else {
901
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
902
0
            OSSL_DECODER_CTX_free(ctx);
903
0
            return NULL;
904
0
        }
905
906
10.4k
        newcache = OPENSSL_zalloc(sizeof(*newcache));
907
10.4k
        if (newcache == NULL) {
908
0
            OSSL_DECODER_CTX_free(ctx);
909
0
            return NULL;
910
0
        }
911
912
10.4k
        if (input_type != NULL) {
913
10.4k
            newcache->input_type = OPENSSL_strdup(input_type);
914
10.4k
            if (newcache->input_type == NULL)
915
0
                goto err;
916
10.4k
        }
917
10.4k
        if (input_structure != NULL) {
918
10.4k
            newcache->input_structure = OPENSSL_strdup(input_structure);
919
10.4k
            if (newcache->input_structure == NULL)
920
0
                goto err;
921
10.4k
        }
922
10.4k
        if (keytype != NULL) {
923
10.4k
            newcache->keytype = OPENSSL_strdup(keytype);
924
10.4k
            if (newcache->keytype == NULL)
925
0
                goto err;
926
10.4k
        }
927
10.4k
        if (propquery != NULL) {
928
0
            newcache->propquery = OPENSSL_strdup(propquery);
929
0
            if (newcache->propquery == NULL)
930
0
                goto err;
931
0
        }
932
10.4k
        newcache->selection = selection;
933
10.4k
        newcache->template = ctx;
934
935
10.4k
        if (!CRYPTO_THREAD_write_lock(cache->lock)) {
936
0
            ctx = NULL;
937
0
            ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
938
0
            goto err;
939
0
        }
940
10.4k
        res = lh_DECODER_CACHE_ENTRY_retrieve(cache->hashtable, &cacheent);
941
10.4k
        if (res == NULL) {
942
10.4k
            (void)lh_DECODER_CACHE_ENTRY_insert(cache->hashtable, newcache);
943
10.4k
            if (lh_DECODER_CACHE_ENTRY_error(cache->hashtable)) {
944
0
                ctx = NULL;
945
0
                CRYPTO_THREAD_unlock(cache->lock);
946
0
                ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
947
0
                goto err;
948
0
            }
949
10.4k
        } else {
950
            /*
951
             * We raced with another thread to construct this and lost. Free
952
             * what we just created and use the entry from the hashtable instead
953
             */
954
0
            decoder_cache_entry_free(newcache);
955
0
            ctx = res->template;
956
0
        }
957
610k
    } else {
958
610k
        ctx = res->template;
959
610k
    }
960
961
620k
    ctx = ossl_decoder_ctx_for_pkey_dup(ctx, pkey, input_type, input_structure);
962
620k
    CRYPTO_THREAD_unlock(cache->lock);
963
964
620k
    return ctx;
965
0
err:
966
0
    decoder_cache_entry_free(newcache);
967
0
    OSSL_DECODER_CTX_free(ctx);
968
    return NULL;
969
620k
}