Coverage Report

Created: 2025-06-13 06:58

/src/openssl31/crypto/encode_decode/decoder_pkey.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2020-2023 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 "encoder_local.h"
22
#include "internal/namemap.h"
23
24
int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
25
                                    const unsigned char *kstr,
26
                                    size_t klen)
27
0
{
28
0
    return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
29
0
}
30
31
int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
32
                                       const UI_METHOD *ui_method,
33
                                       void *ui_data)
34
0
{
35
0
    return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
36
0
}
37
38
int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
39
                                         pem_password_cb *cb, void *cbarg)
40
55.4k
{
41
55.4k
    return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
42
55.4k
}
43
44
int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
45
                                       OSSL_PASSPHRASE_CALLBACK *cb,
46
                                       void *cbarg)
47
0
{
48
0
    return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
49
0
}
50
51
/*
52
 * Support for OSSL_DECODER_CTX_new_for_pkey:
53
 * The construct data, and collecting keymgmt information for it
54
 */
55
56
DEFINE_STACK_OF(EVP_KEYMGMT)
57
58
struct decoder_pkey_data_st {
59
    OSSL_LIB_CTX *libctx;
60
    char *propq;
61
    int selection;
62
63
    STACK_OF(EVP_KEYMGMT) *keymgmts;
64
    char *object_type;           /* recorded object data type, may be NULL */
65
    void **object;               /* Where the result should end up */
66
};
67
68
static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst,
69
                                  const OSSL_PARAM *params,
70
                                  void *construct_data)
71
960k
{
72
960k
    struct decoder_pkey_data_st *data = construct_data;
73
960k
    OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
74
960k
    void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
75
960k
    const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
76
960k
    EVP_KEYMGMT *keymgmt = NULL;
77
960k
    const OSSL_PROVIDER *keymgmt_prov = NULL;
78
960k
    int i, end;
79
    /*
80
     * |object_ref| points to a provider reference to an object, its exact
81
     * contents entirely opaque to us, but may be passed to any provider
82
     * function that expects this (such as OSSL_FUNC_keymgmt_load().
83
     *
84
     * This pointer is considered volatile, i.e. whatever it points at
85
     * is assumed to be freed as soon as this function returns.
86
     */
87
960k
    void *object_ref = NULL;
88
960k
    size_t object_ref_sz = 0;
89
960k
    const OSSL_PARAM *p;
90
91
960k
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
92
960k
    if (p != NULL) {
93
960k
        char *object_type = NULL;
94
95
960k
        if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
96
0
            return 0;
97
960k
        OPENSSL_free(data->object_type);
98
960k
        data->object_type = object_type;
99
960k
    }
100
101
    /*
102
     * For stuff that should end up in an EVP_PKEY, we only accept an object
103
     * reference for the moment.  This enforces that the key data itself
104
     * remains with the provider.
105
     */
106
960k
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
107
960k
    if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
108
618k
        return 0;
109
342k
    object_ref = p->data;
110
342k
    object_ref_sz = p->data_size;
111
112
    /*
113
     * First, we try to find a keymgmt that comes from the same provider as
114
     * the decoder that passed the params.
115
     */
116
342k
    end = sk_EVP_KEYMGMT_num(data->keymgmts);
117
712k
    for (i = 0; i < end; i++) {
118
712k
        keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
119
712k
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
120
121
712k
        if (keymgmt_prov == decoder_prov
122
712k
            && evp_keymgmt_has_load(keymgmt)
123
712k
            && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
124
342k
            break;
125
712k
    }
126
342k
    if (i < end) {
127
        /* To allow it to be freed further down */
128
342k
        if (!EVP_KEYMGMT_up_ref(keymgmt))
129
0
            return 0;
130
342k
    } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx,
131
0
                                            data->object_type,
132
0
                                            data->propq)) != NULL) {
133
0
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
134
0
    }
135
136
342k
    if (keymgmt != NULL) {
137
342k
        EVP_PKEY *pkey = NULL;
138
342k
        void *keydata = NULL;
139
140
        /*
141
         * If the EVP_KEYMGMT and the OSSL_DECODER are from the
142
         * same provider, we assume that the KEYMGMT has a key loading
143
         * function that can handle the provider reference we hold.
144
         *
145
         * Otherwise, we export from the decoder and import the
146
         * result in the keymgmt.
147
         */
148
342k
        if (keymgmt_prov == decoder_prov) {
149
342k
            keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
150
342k
        } else {
151
0
            struct evp_keymgmt_util_try_import_data_st import_data;
152
153
0
            import_data.keymgmt = keymgmt;
154
0
            import_data.keydata = NULL;
155
0
            if (data->selection == 0)
156
                /* import/export functions do not tolerate 0 selection */
157
0
                import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
158
0
            else
159
0
                import_data.selection = data->selection;
160
161
            /*
162
             * No need to check for errors here, the value of
163
             * |import_data.keydata| is as much an indicator.
164
             */
165
0
            (void)decoder->export_object(decoderctx,
166
0
                                         object_ref, object_ref_sz,
167
0
                                         &evp_keymgmt_util_try_import,
168
0
                                         &import_data);
169
0
            keydata = import_data.keydata;
170
0
            import_data.keydata = NULL;
171
0
        }
172
173
342k
        if (keydata != NULL
174
342k
            && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
175
0
            evp_keymgmt_freedata(keymgmt, keydata);
176
177
342k
        *data->object = pkey;
178
179
        /*
180
         * evp_keymgmt_util_make_pkey() increments the reference count when
181
         * assigning the EVP_PKEY, so we can free the keymgmt here.
182
         */
183
342k
        EVP_KEYMGMT_free(keymgmt);
184
342k
    }
185
    /*
186
     * We successfully looked through, |*ctx->object| determines if we
187
     * actually found something.
188
     */
189
342k
    return (*data->object != NULL);
190
342k
}
191
192
static void decoder_clean_pkey_construct_arg(void *construct_data)
193
1.42M
{
194
1.42M
    struct decoder_pkey_data_st *data = construct_data;
195
196
1.42M
    if (data != NULL) {
197
959k
        sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
198
959k
        OPENSSL_free(data->propq);
199
959k
        OPENSSL_free(data->object_type);
200
959k
        OPENSSL_free(data);
201
959k
    }
202
1.42M
}
203
204
struct collect_data_st {
205
    OSSL_LIB_CTX *libctx;
206
    OSSL_DECODER_CTX *ctx;
207
208
    const char *keytype; /* the keytype requested, if any */
209
    int keytype_id; /* if keytype_resolved is set, keymgmt name_id; else 0 */
210
    int sm2_id;     /* if keytype_resolved is set and EC, SM2 name_id; else 0 */
211
    int total;      /* number of matching results */
212
    char error_occurred;
213
    char keytype_resolved;
214
215
    STACK_OF(EVP_KEYMGMT) *keymgmts;
216
};
217
218
static void collect_decoder_keymgmt(EVP_KEYMGMT *keymgmt, OSSL_DECODER *decoder,
219
                                    void *provctx, struct collect_data_st *data)
220
16.4M
{
221
16.4M
    void *decoderctx = NULL;
222
16.4M
    OSSL_DECODER_INSTANCE *di = NULL;
223
224
    /*
225
     * We already checked the EVP_KEYMGMT is applicable in check_keymgmt so we
226
     * don't check it again here.
227
     */
228
229
16.4M
    if (keymgmt->name_id != decoder->base.id)
230
        /* Mismatch is not an error, continue. */
231
15.5M
        return;
232
233
925k
    if ((decoderctx = decoder->newctx(provctx)) == NULL) {
234
0
        data->error_occurred = 1;
235
0
        return;
236
0
    }
237
238
925k
    if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
239
0
        decoder->freectx(decoderctx);
240
0
        data->error_occurred = 1;
241
0
        return;
242
0
    }
243
244
925k
    OSSL_TRACE_BEGIN(DECODER) {
245
0
        BIO_printf(trc_out,
246
0
                   "(ctx %p) Checking out decoder %p:\n"
247
0
                   "    %s with %s\n",
248
0
                   (void *)data->ctx, (void *)decoder,
249
0
                   OSSL_DECODER_get0_name(decoder),
250
0
                   OSSL_DECODER_get0_properties(decoder));
251
925k
    } OSSL_TRACE_END(DECODER);
252
253
925k
    if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
254
0
        ossl_decoder_instance_free(di);
255
0
        data->error_occurred = 1;
256
0
        return;
257
0
    }
258
259
925k
    ++data->total;
260
925k
}
261
262
static void collect_decoder(OSSL_DECODER *decoder, void *arg)
263
9.42M
{
264
9.42M
    struct collect_data_st *data = arg;
265
9.42M
    STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts;
266
9.42M
    int i, end_i;
267
9.42M
    EVP_KEYMGMT *keymgmt;
268
9.42M
    const OSSL_PROVIDER *prov;
269
9.42M
    void *provctx;
270
271
9.42M
    if (data->error_occurred)
272
0
        return;
273
274
9.42M
    prov = OSSL_DECODER_get0_provider(decoder);
275
9.42M
    provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
276
277
    /*
278
     * Either the caller didn't give us a selection, or if they did, the decoder
279
     * must tell us if it supports that selection to be accepted. If the decoder
280
     * doesn't have |does_selection|, it's seen as taking anything.
281
     */
282
9.42M
    if (decoder->does_selection != NULL
283
9.42M
            && !decoder->does_selection(provctx, data->ctx->selection))
284
4.49M
        return;
285
286
4.92M
    OSSL_TRACE_BEGIN(DECODER) {
287
0
        BIO_printf(trc_out,
288
0
                   "(ctx %p) Checking out decoder %p:\n"
289
0
                   "    %s with %s\n",
290
0
                   (void *)data->ctx, (void *)decoder,
291
0
                   OSSL_DECODER_get0_name(decoder),
292
0
                   OSSL_DECODER_get0_properties(decoder));
293
4.92M
    } OSSL_TRACE_END(DECODER);
294
295
4.92M
    end_i = sk_EVP_KEYMGMT_num(keymgmts);
296
21.3M
    for (i = 0; i < end_i; ++i) {
297
16.4M
        keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i);
298
299
16.4M
        collect_decoder_keymgmt(keymgmt, decoder, provctx, data);
300
16.4M
        if (data->error_occurred)
301
0
            return;
302
16.4M
    }
303
4.92M
}
304
305
/*
306
 * Is this EVP_KEYMGMT applicable given the key type given in the call to
307
 * ossl_decoder_ctx_setup_for_pkey (if any)?
308
 */
309
static int check_keymgmt(EVP_KEYMGMT *keymgmt, struct collect_data_st *data)
310
4.36M
{
311
    /* If no keytype was specified, everything matches. */
312
4.36M
    if (data->keytype == NULL)
313
436k
        return 1;
314
315
3.93M
    if (!data->keytype_resolved) {
316
        /* We haven't cached the IDs from the keytype string yet. */
317
213k
        OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx);
318
213k
        data->keytype_id = ossl_namemap_name2num(namemap, data->keytype);
319
320
        /*
321
         * If keytype is a value ambiguously used for both EC and SM2,
322
         * collect the ID for SM2 as well.
323
         */
324
213k
        if (data->keytype_id != 0
325
213k
            && (strcmp(data->keytype, "id-ecPublicKey") == 0
326
188k
                || strcmp(data->keytype, "1.2.840.10045.2.1") == 0))
327
111k
            data->sm2_id = ossl_namemap_name2num(namemap, "SM2");
328
329
        /*
330
         * If keytype_id is zero the name was not found, but we still
331
         * set keytype_resolved to avoid trying all this again.
332
         */
333
213k
        data->keytype_resolved = 1;
334
213k
    }
335
336
    /* Specified keytype could not be resolved, so nothing matches. */
337
3.93M
    if (data->keytype_id == 0)
338
535k
        return 0;
339
340
    /* Does not match the keytype specified, so skip. */
341
3.39M
    if (keymgmt->name_id != data->keytype_id
342
3.39M
        && keymgmt->name_id != data->sm2_id)
343
3.09M
        return 0;
344
345
299k
    return 1;
346
3.39M
}
347
348
static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
349
4.36M
{
350
4.36M
    struct collect_data_st *data = arg;
351
352
4.36M
    if (!check_keymgmt(keymgmt, data))
353
3.63M
        return;
354
355
    /*
356
     * We have to ref EVP_KEYMGMT here because in the success case,
357
     * data->keymgmts is referenced by the constructor we register in the
358
     * OSSL_DECODER_CTX. The registered cleanup function
359
     * (decoder_clean_pkey_construct_arg) unrefs every element of the stack and
360
     * frees it.
361
     */
362
735k
    if (!EVP_KEYMGMT_up_ref(keymgmt))
363
0
        return;
364
365
735k
    if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) {
366
0
        EVP_KEYMGMT_free(keymgmt);
367
0
        data->error_occurred = 1;
368
0
    }
369
735k
}
370
371
/*
372
 * This function does the actual binding of decoders to the OSSL_DECODER_CTX. It
373
 * searches for decoders matching 'keytype', which is a string like "RSA", "DH",
374
 * etc. If 'keytype' is NULL, decoders for all keytypes are bound.
375
 */
376
int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx,
377
                                    EVP_PKEY **pkey, const char *keytype,
378
                                    OSSL_LIB_CTX *libctx,
379
                                    const char *propquery)
380
229k
{
381
229k
    int ok = 0;
382
229k
    struct decoder_pkey_data_st *process_data = NULL;
383
229k
    struct collect_data_st collect_data = { NULL };
384
229k
    STACK_OF(EVP_KEYMGMT) *keymgmts = NULL;
385
386
229k
    OSSL_TRACE_BEGIN(DECODER) {
387
0
        const char *input_type = ctx->start_input_type;
388
0
        const char *input_structure = ctx->input_structure;
389
390
0
        BIO_printf(trc_out,
391
0
                   "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n",
392
0
                   (void *)ctx,
393
0
                   keytype != NULL ? keytype : "",
394
0
                   keytype != NULL ? " keys" : "keys of any type",
395
0
                   input_type != NULL ? " from " : "",
396
0
                   input_type != NULL ? input_type : "",
397
0
                   input_structure != NULL ? " with " : "",
398
0
                   input_structure != NULL ? input_structure : "");
399
229k
    } OSSL_TRACE_END(DECODER);
400
401
    /* Allocate data. */
402
229k
    if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL
403
229k
        || (propquery != NULL
404
229k
            && (process_data->propq = OPENSSL_strdup(propquery)) == NULL)) {
405
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
406
0
        goto err;
407
0
    }
408
409
    /* Allocate our list of EVP_KEYMGMTs. */
410
229k
    keymgmts = sk_EVP_KEYMGMT_new_null();
411
229k
    if (keymgmts == NULL) {
412
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
413
0
        goto err;
414
0
    }
415
416
229k
    process_data->object    = (void **)pkey;
417
229k
    process_data->libctx    = libctx;
418
229k
    process_data->selection = ctx->selection;
419
229k
    process_data->keymgmts  = keymgmts;
420
421
    /*
422
     * Enumerate all keymgmts into a stack.
423
     *
424
     * We could nest EVP_KEYMGMT_do_all_provided inside
425
     * OSSL_DECODER_do_all_provided or vice versa but these functions become
426
     * bottlenecks if called repeatedly, which is why we collect the
427
     * EVP_KEYMGMTs into a stack here and call both functions only once.
428
     *
429
     * We resolve the keytype string to a name ID so we don't have to resolve it
430
     * multiple times, avoiding repeated calls to EVP_KEYMGMT_is_a, which is a
431
     * performance bottleneck. However, we do this lazily on the first call to
432
     * collect_keymgmt made by EVP_KEYMGMT_do_all_provided, rather than do it
433
     * upfront, as this ensures that the names for all loaded providers have
434
     * been registered by the time we try to resolve the keytype string.
435
     */
436
229k
    collect_data.ctx        = ctx;
437
229k
    collect_data.libctx     = libctx;
438
229k
    collect_data.keymgmts   = keymgmts;
439
229k
    collect_data.keytype    = keytype;
440
229k
    EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data);
441
442
229k
    if (collect_data.error_occurred)
443
0
        goto err;
444
445
    /* Enumerate all matching decoders. */
446
229k
    OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data);
447
448
229k
    if (collect_data.error_occurred)
449
0
        goto err;
450
451
229k
    OSSL_TRACE_BEGIN(DECODER) {
452
0
        BIO_printf(trc_out,
453
0
                   "(ctx %p) Got %d decoders producing keys\n",
454
0
                   (void *)ctx, collect_data.total);
455
229k
    } OSSL_TRACE_END(DECODER);
456
457
    /*
458
     * Finish initializing the decoder context. If one or more decoders matched
459
     * above then the number of decoders attached to the OSSL_DECODER_CTX will
460
     * be nonzero. Else nothing was found and we do nothing.
461
     */
462
229k
    if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
463
212k
        if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
464
212k
            || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
465
212k
            || !OSSL_DECODER_CTX_set_cleanup(ctx,
466
212k
                                             decoder_clean_pkey_construct_arg))
467
0
            goto err;
468
469
212k
        process_data = NULL; /* Avoid it being freed */
470
212k
    }
471
472
229k
    ok = 1;
473
229k
 err:
474
229k
    decoder_clean_pkey_construct_arg(process_data);
475
229k
    return ok;
476
229k
}
477
478
OSSL_DECODER_CTX *
479
OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
480
                              const char *input_type,
481
                              const char *input_structure,
482
                              const char *keytype, int selection,
483
                              OSSL_LIB_CTX *libctx, const char *propquery)
484
498k
{
485
498k
    OSSL_DECODER_CTX *ctx = NULL;
486
487
498k
    if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
488
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
489
0
        return NULL;
490
0
    }
491
492
498k
    OSSL_TRACE_BEGIN(DECODER) {
493
0
        BIO_printf(trc_out,
494
0
                   "(ctx %p) Looking for %s decoders with selection %d\n",
495
0
                   (void *)ctx, keytype, selection);
496
0
        BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
497
0
                   input_type, input_structure);
498
498k
    } OSSL_TRACE_END(DECODER);
499
500
498k
    if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
501
498k
        && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
502
498k
        && OSSL_DECODER_CTX_set_selection(ctx, selection)
503
498k
        && ossl_decoder_ctx_setup_for_pkey(ctx, pkey, keytype,
504
498k
                                           libctx, propquery)
505
498k
        && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)) {
506
498k
        OSSL_TRACE_BEGIN(DECODER) {
507
0
            BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
508
0
                       (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
509
498k
        } OSSL_TRACE_END(DECODER);
510
498k
        return ctx;
511
498k
    }
512
513
0
    OSSL_DECODER_CTX_free(ctx);
514
0
    return NULL;
515
498k
}