Coverage Report

Created: 2026-03-09 06:55

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