Coverage Report

Created: 2023-06-08 06:40

/src/openssl/crypto/encode_decode/decoder_pkey.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2020-2022 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
0
{
41
0
    return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
42
0
}
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
0
{
72
0
    struct decoder_pkey_data_st *data = construct_data;
73
0
    OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
74
0
    void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
75
0
    const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
76
0
    EVP_KEYMGMT *keymgmt = NULL;
77
0
    const OSSL_PROVIDER *keymgmt_prov = NULL;
78
0
    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
0
    void *object_ref = NULL;
88
0
    size_t object_ref_sz = 0;
89
0
    const OSSL_PARAM *p;
90
91
0
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
92
0
    if (p != NULL) {
93
0
        char *object_type = NULL;
94
95
0
        if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
96
0
            return 0;
97
0
        OPENSSL_free(data->object_type);
98
0
        data->object_type = object_type;
99
0
    }
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
0
    p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
107
0
    if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
108
0
        return 0;
109
0
    object_ref = p->data;
110
0
    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
0
    end = sk_EVP_KEYMGMT_num(data->keymgmts);
117
0
    for (i = 0; i < end; i++) {
118
0
        keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
119
0
        keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
120
121
0
        if (keymgmt_prov == decoder_prov
122
0
            && evp_keymgmt_has_load(keymgmt)
123
0
            && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
124
0
            break;
125
0
    }
126
0
    if (i < end) {
127
        /* To allow it to be freed further down */
128
0
        if (!EVP_KEYMGMT_up_ref(keymgmt))
129
0
            return 0;
130
0
    } 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
0
    if (keymgmt != NULL) {
137
0
        EVP_PKEY *pkey = NULL;
138
0
        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
0
        if (keymgmt_prov == decoder_prov) {
149
0
            keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
150
0
        } 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
            import_data.selection = data->selection;
156
157
            /*
158
             * No need to check for errors here, the value of
159
             * |import_data.keydata| is as much an indicator.
160
             */
161
0
            (void)decoder->export_object(decoderctx,
162
0
                                         object_ref, object_ref_sz,
163
0
                                         &evp_keymgmt_util_try_import,
164
0
                                         &import_data);
165
0
            keydata = import_data.keydata;
166
0
            import_data.keydata = NULL;
167
0
        }
168
169
0
        if (keydata != NULL
170
0
            && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
171
0
            evp_keymgmt_freedata(keymgmt, keydata);
172
173
0
        *data->object = pkey;
174
175
        /*
176
         * evp_keymgmt_util_make_pkey() increments the reference count when
177
         * assigning the EVP_PKEY, so we can free the keymgmt here.
178
         */
179
0
        EVP_KEYMGMT_free(keymgmt);
180
0
    }
181
    /*
182
     * We successfully looked through, |*ctx->object| determines if we
183
     * actually found something.
184
     */
185
0
    return (*data->object != NULL);
186
0
}
187
188
static void decoder_clean_pkey_construct_arg(void *construct_data)
189
0
{
190
0
    struct decoder_pkey_data_st *data = construct_data;
191
192
0
    if (data != NULL) {
193
0
        sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
194
0
        OPENSSL_free(data->propq);
195
0
        OPENSSL_free(data->object_type);
196
0
        OPENSSL_free(data);
197
0
    }
198
0
}
199
200
struct collect_data_st {
201
    OSSL_LIB_CTX *libctx;
202
    OSSL_DECODER_CTX *ctx;
203
204
    const char *keytype; /* the keytype requested, if any */
205
    int keytype_id; /* if keytype_resolved is set, keymgmt name_id; else 0 */
206
    int sm2_id;     /* if keytype_resolved is set and EC, SM2 name_id; else 0 */
207
    int total;      /* number of matching results */
208
    char error_occurred;
209
    char keytype_resolved;
210
211
    STACK_OF(EVP_KEYMGMT) *keymgmts;
212
};
213
214
static void collect_decoder_keymgmt(EVP_KEYMGMT *keymgmt, OSSL_DECODER *decoder,
215
                                    void *provctx, struct collect_data_st *data)
216
0
{
217
0
    void *decoderctx = NULL;
218
0
    OSSL_DECODER_INSTANCE *di = NULL;
219
220
    /*
221
     * We already checked the EVP_KEYMGMT is applicable in check_keymgmt so we
222
     * don't check it again here.
223
     */
224
225
0
    if (keymgmt->name_id != decoder->base.id)
226
        /* Mismatch is not an error, continue. */
227
0
        return;
228
229
0
    if ((decoderctx = decoder->newctx(provctx)) == NULL) {
230
0
        data->error_occurred = 1;
231
0
        return;
232
0
    }
233
234
0
    if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
235
0
        decoder->freectx(decoderctx);
236
0
        data->error_occurred = 1;
237
0
        return;
238
0
    }
239
240
0
    OSSL_TRACE_BEGIN(DECODER) {
241
0
        BIO_printf(trc_out,
242
0
                   "(ctx %p) Checking out decoder %p:\n"
243
0
                   "    %s with %s\n",
244
0
                   (void *)data->ctx, (void *)decoder,
245
0
                   OSSL_DECODER_get0_name(decoder),
246
0
                   OSSL_DECODER_get0_properties(decoder));
247
0
    } OSSL_TRACE_END(DECODER);
248
249
0
    if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
250
0
        ossl_decoder_instance_free(di);
251
0
        data->error_occurred = 1;
252
0
        return;
253
0
    }
254
255
0
    ++data->total;
256
0
}
257
258
static void collect_decoder(OSSL_DECODER *decoder, void *arg)
259
0
{
260
0
    struct collect_data_st *data = arg;
261
0
    STACK_OF(EVP_KEYMGMT) *keymgmts = data->keymgmts;
262
0
    int i, end_i;
263
0
    EVP_KEYMGMT *keymgmt;
264
0
    const OSSL_PROVIDER *prov;
265
0
    void *provctx;
266
267
0
    if (data->error_occurred)
268
0
        return;
269
270
0
    prov = OSSL_DECODER_get0_provider(decoder);
271
0
    provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
272
273
    /*
274
     * Either the caller didn't give us a selection, or if they did, the decoder
275
     * must tell us if it supports that selection to be accepted. If the decoder
276
     * doesn't have |does_selection|, it's seen as taking anything.
277
     */
278
0
    if (decoder->does_selection != NULL
279
0
            && !decoder->does_selection(provctx, data->ctx->selection))
280
0
        return;
281
282
0
    OSSL_TRACE_BEGIN(DECODER) {
283
0
        BIO_printf(trc_out,
284
0
                   "(ctx %p) Checking out decoder %p:\n"
285
0
                   "    %s with %s\n",
286
0
                   (void *)data->ctx, (void *)decoder,
287
0
                   OSSL_DECODER_get0_name(decoder),
288
0
                   OSSL_DECODER_get0_properties(decoder));
289
0
    } OSSL_TRACE_END(DECODER);
290
291
0
    end_i = sk_EVP_KEYMGMT_num(keymgmts);
292
0
    for (i = 0; i < end_i; ++i) {
293
0
        keymgmt = sk_EVP_KEYMGMT_value(keymgmts, i);
294
295
0
        collect_decoder_keymgmt(keymgmt, decoder, provctx, data);
296
0
        if (data->error_occurred)
297
0
            return;
298
0
    }
299
0
}
300
301
/*
302
 * Is this EVP_KEYMGMT applicable given the key type given in the call to
303
 * ossl_decoder_ctx_setup_for_pkey (if any)?
304
 */
305
static int check_keymgmt(EVP_KEYMGMT *keymgmt, struct collect_data_st *data)
306
0
{
307
    /* If no keytype was specified, everything matches. */
308
0
    if (data->keytype == NULL)
309
0
        return 1;
310
311
0
    if (!data->keytype_resolved) {
312
        /* We haven't cached the IDs from the keytype string yet. */
313
0
        OSSL_NAMEMAP *namemap = ossl_namemap_stored(data->libctx);
314
0
        data->keytype_id = ossl_namemap_name2num(namemap, data->keytype);
315
316
        /*
317
         * If keytype is a value ambiguously used for both EC and SM2,
318
         * collect the ID for SM2 as well.
319
         */
320
0
        if (data->keytype_id != 0
321
0
            && (strcmp(data->keytype, "id-ecPublicKey") == 0
322
0
                || strcmp(data->keytype, "1.2.840.10045.2.1") == 0))
323
0
            data->sm2_id = ossl_namemap_name2num(namemap, "SM2");
324
325
        /*
326
         * If keytype_id is zero the name was not found, but we still
327
         * set keytype_resolved to avoid trying all this again.
328
         */
329
0
        data->keytype_resolved = 1;
330
0
    }
331
332
    /* Specified keytype could not be resolved, so nothing matches. */
333
0
    if (data->keytype_id == 0)
334
0
        return 0;
335
336
    /* Does not match the keytype specified, so skip. */
337
0
    if (keymgmt->name_id != data->keytype_id
338
0
        && keymgmt->name_id != data->sm2_id)
339
0
        return 0;
340
341
0
    return 1;
342
0
}
343
344
static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
345
0
{
346
0
    struct collect_data_st *data = arg;
347
348
0
    if (!check_keymgmt(keymgmt, data))
349
0
        return;
350
351
    /*
352
     * We have to ref EVP_KEYMGMT here because in the success case,
353
     * data->keymgmts is referenced by the constructor we register in the
354
     * OSSL_DECODER_CTX. The registered cleanup function
355
     * (decoder_clean_pkey_construct_arg) unrefs every element of the stack and
356
     * frees it.
357
     */
358
0
    if (!EVP_KEYMGMT_up_ref(keymgmt))
359
0
        return;
360
361
0
    if (sk_EVP_KEYMGMT_push(data->keymgmts, keymgmt) <= 0) {
362
0
        EVP_KEYMGMT_free(keymgmt);
363
0
        data->error_occurred = 1;
364
0
    }
365
0
}
366
367
/*
368
 * This function does the actual binding of decoders to the OSSL_DECODER_CTX. It
369
 * searches for decoders matching 'keytype', which is a string like "RSA", "DH",
370
 * etc. If 'keytype' is NULL, decoders for all keytypes are bound.
371
 */
372
int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx,
373
                                    EVP_PKEY **pkey, const char *keytype,
374
                                    OSSL_LIB_CTX *libctx,
375
                                    const char *propquery)
376
0
{
377
0
    int ok = 0;
378
0
    struct decoder_pkey_data_st *process_data = NULL;
379
0
    struct collect_data_st collect_data = { NULL };
380
0
    STACK_OF(EVP_KEYMGMT) *keymgmts = NULL;
381
382
0
    OSSL_TRACE_BEGIN(DECODER) {
383
0
        const char *input_type = ctx->start_input_type;
384
0
        const char *input_structure = ctx->input_structure;
385
386
0
        BIO_printf(trc_out,
387
0
                   "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n",
388
0
                   (void *)ctx,
389
0
                   keytype != NULL ? keytype : "",
390
0
                   keytype != NULL ? " keys" : "keys of any type",
391
0
                   input_type != NULL ? " from " : "",
392
0
                   input_type != NULL ? input_type : "",
393
0
                   input_structure != NULL ? " with " : "",
394
0
                   input_structure != NULL ? input_structure : "");
395
0
    } OSSL_TRACE_END(DECODER);
396
397
    /* Allocate data. */
398
0
    if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL)
399
0
        goto err;
400
0
    if ((propquery != NULL
401
0
            && (process_data->propq = OPENSSL_strdup(propquery)) == NULL))
402
0
        goto err;
403
404
    /* Allocate our list of EVP_KEYMGMTs. */
405
0
    keymgmts = sk_EVP_KEYMGMT_new_null();
406
0
    if (keymgmts == NULL) {
407
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_CRYPTO_LIB);
408
0
        goto err;
409
0
    }
410
411
0
    process_data->object    = (void **)pkey;
412
0
    process_data->libctx    = libctx;
413
0
    process_data->selection = ctx->selection;
414
0
    process_data->keymgmts  = keymgmts;
415
416
    /*
417
     * Enumerate all keymgmts into a stack.
418
     *
419
     * We could nest EVP_KEYMGMT_do_all_provided inside
420
     * OSSL_DECODER_do_all_provided or vice versa but these functions become
421
     * bottlenecks if called repeatedly, which is why we collect the
422
     * EVP_KEYMGMTs into a stack here and call both functions only once.
423
     *
424
     * We resolve the keytype string to a name ID so we don't have to resolve it
425
     * multiple times, avoiding repeated calls to EVP_KEYMGMT_is_a, which is a
426
     * performance bottleneck. However, we do this lazily on the first call to
427
     * collect_keymgmt made by EVP_KEYMGMT_do_all_provided, rather than do it
428
     * upfront, as this ensures that the names for all loaded providers have
429
     * been registered by the time we try to resolve the keytype string.
430
     */
431
0
    collect_data.ctx        = ctx;
432
0
    collect_data.libctx     = libctx;
433
0
    collect_data.keymgmts   = keymgmts;
434
0
    collect_data.keytype    = keytype;
435
0
    EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt, &collect_data);
436
437
0
    if (collect_data.error_occurred)
438
0
        goto err;
439
440
    /* Enumerate all matching decoders. */
441
0
    OSSL_DECODER_do_all_provided(libctx, collect_decoder, &collect_data);
442
443
0
    if (collect_data.error_occurred)
444
0
        goto err;
445
446
0
    OSSL_TRACE_BEGIN(DECODER) {
447
0
        BIO_printf(trc_out,
448
0
                   "(ctx %p) Got %d decoders producing keys\n",
449
0
                   (void *)ctx, collect_data.total);
450
0
    } OSSL_TRACE_END(DECODER);
451
452
    /*
453
     * Finish initializing the decoder context. If one or more decoders matched
454
     * above then the number of decoders attached to the OSSL_DECODER_CTX will
455
     * be nonzero. Else nothing was found and we do nothing.
456
     */
457
0
    if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
458
0
        if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
459
0
            || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
460
0
            || !OSSL_DECODER_CTX_set_cleanup(ctx,
461
0
                                             decoder_clean_pkey_construct_arg))
462
0
            goto err;
463
464
0
        process_data = NULL; /* Avoid it being freed */
465
0
    }
466
467
0
    ok = 1;
468
0
 err:
469
0
    decoder_clean_pkey_construct_arg(process_data);
470
0
    return ok;
471
0
}
472
473
OSSL_DECODER_CTX *
474
OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
475
                              const char *input_type,
476
                              const char *input_structure,
477
                              const char *keytype, int selection,
478
                              OSSL_LIB_CTX *libctx, const char *propquery)
479
0
{
480
0
    OSSL_DECODER_CTX *ctx = NULL;
481
482
0
    if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
483
0
        ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_OSSL_DECODER_LIB);
484
0
        return NULL;
485
0
    }
486
487
0
    OSSL_TRACE_BEGIN(DECODER) {
488
0
        BIO_printf(trc_out,
489
0
                   "(ctx %p) Looking for %s decoders with selection %d\n",
490
0
                   (void *)ctx, keytype, selection);
491
0
        BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
492
0
                   input_type, input_structure);
493
0
    } OSSL_TRACE_END(DECODER);
494
495
0
    if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
496
0
        && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
497
0
        && OSSL_DECODER_CTX_set_selection(ctx, selection)
498
0
        && ossl_decoder_ctx_setup_for_pkey(ctx, pkey, keytype,
499
0
                                           libctx, propquery)
500
0
        && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)) {
501
0
        OSSL_TRACE_BEGIN(DECODER) {
502
0
            BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
503
0
                       (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
504
0
        } OSSL_TRACE_END(DECODER);
505
0
        return ctx;
506
0
    }
507
508
0
    OSSL_DECODER_CTX_free(ctx);
509
0
    return NULL;
510
0
}