Coverage Report

Created: 2025-06-13 06:56

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