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 "encoder_local.h"
21 
22 int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
23                                     const unsigned char *kstr,
24                                     size_t klen)
25 {
26     return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
27 }
28 
29 int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
30                                        const UI_METHOD *ui_method,
31                                        void *ui_data)
32 {
33     return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
34 }
35 
36 int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
37                                          pem_password_cb *cb, void *cbarg)
38 {
39     return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
40 }
41 
42 int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
43                                        OSSL_PASSPHRASE_CALLBACK *cb,
44                                        void *cbarg)
45 {
46     return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
47 }
48 
49 /*
50  * Support for OSSL_DECODER_CTX_new_for_pkey:
51  * The construct data, and collecting keymgmt information for it
52  */
53 
54 DEFINE_STACK_OF(EVP_KEYMGMT)
55 
56 struct decoder_pkey_data_st {
57     OSSL_LIB_CTX *libctx;
58     char *propq;
59     int selection;
60 
61     STACK_OF(EVP_KEYMGMT) *keymgmts;
62     char *object_type;           /* recorded object data type, may be NULL */
63     void **object;               /* Where the result should end up */
64 };
65 
66 static int decoder_construct_pkey(OSSL_DECODER_INSTANCE *decoder_inst,
67                                   const OSSL_PARAM *params,
68                                   void *construct_data)
69 {
70     struct decoder_pkey_data_st *data = construct_data;
71     OSSL_DECODER *decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
72     void *decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
73     const OSSL_PROVIDER *decoder_prov = OSSL_DECODER_get0_provider(decoder);
74     EVP_KEYMGMT *keymgmt = NULL;
75     const OSSL_PROVIDER *keymgmt_prov = NULL;
76     int i, end;
77     /*
78      * |object_ref| points to a provider reference to an object, its exact
79      * contents entirely opaque to us, but may be passed to any provider
80      * function that expects this (such as OSSL_FUNC_keymgmt_load().
81      *
82      * This pointer is considered volatile, i.e. whatever it points at
83      * is assumed to be freed as soon as this function returns.
84      */
85     void *object_ref = NULL;
86     size_t object_ref_sz = 0;
87     const OSSL_PARAM *p;
88 
89     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
90     if (p != NULL) {
91         char *object_type = NULL;
92 
93         if (!OSSL_PARAM_get_utf8_string(p, &object_type, 0))
94             return 0;
95         OPENSSL_free(data->object_type);
96         data->object_type = object_type;
97     }
98 
99     /*
100      * For stuff that should end up in an EVP_PKEY, we only accept an object
101      * reference for the moment.  This enforces that the key data itself
102      * remains with the provider.
103      */
104     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
105     if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
106         return 0;
107     object_ref = p->data;
108     object_ref_sz = p->data_size;
109 
110     /*
111      * First, we try to find a keymgmt that comes from the same provider as
112      * the decoder that passed the params.
113      */
114     end = sk_EVP_KEYMGMT_num(data->keymgmts);
115     for (i = 0; i < end; i++) {
116         keymgmt = sk_EVP_KEYMGMT_value(data->keymgmts, i);
117         keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
118 
119         if (keymgmt_prov == decoder_prov
120             && evp_keymgmt_has_load(keymgmt)
121             && EVP_KEYMGMT_is_a(keymgmt, data->object_type))
122             break;
123     }
124     if (i < end) {
125         /* To allow it to be freed further down */
126         if (!EVP_KEYMGMT_up_ref(keymgmt))
127             return 0;
128     } else if ((keymgmt = EVP_KEYMGMT_fetch(data->libctx,
129                                             data->object_type,
130                                             data->propq)) != NULL) {
131         keymgmt_prov = EVP_KEYMGMT_get0_provider(keymgmt);
132     }
133 
134     if (keymgmt != NULL) {
135         EVP_PKEY *pkey = NULL;
136         void *keydata = NULL;
137 
138         /*
139          * If the EVP_KEYMGMT and the OSSL_DECODER are from the
140          * same provider, we assume that the KEYMGMT has a key loading
141          * function that can handle the provider reference we hold.
142          *
143          * Otherwise, we export from the decoder and import the
144          * result in the keymgmt.
145          */
146         if (keymgmt_prov == decoder_prov) {
147             keydata = evp_keymgmt_load(keymgmt, object_ref, object_ref_sz);
148         } else {
149             struct evp_keymgmt_util_try_import_data_st import_data;
150 
151             import_data.keymgmt = keymgmt;
152             import_data.keydata = NULL;
153             if (data->selection == 0)
154                 /* import/export functions do not tolerate 0 selection */
155                 import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
156             else
157                 import_data.selection = data->selection;
158 
159             /*
160              * No need to check for errors here, the value of
161              * |import_data.keydata| is as much an indicator.
162              */
163             (void)decoder->export_object(decoderctx,
164                                          object_ref, object_ref_sz,
165                                          &evp_keymgmt_util_try_import,
166                                          &import_data);
167             keydata = import_data.keydata;
168             import_data.keydata = NULL;
169         }
170 
171         if (keydata != NULL
172             && (pkey = evp_keymgmt_util_make_pkey(keymgmt, keydata)) == NULL)
173             evp_keymgmt_freedata(keymgmt, keydata);
174 
175         *data->object = pkey;
176 
177         /*
178          * evp_keymgmt_util_make_pkey() increments the reference count when
179          * assigning the EVP_PKEY, so we can free the keymgmt here.
180          */
181         EVP_KEYMGMT_free(keymgmt);
182     }
183     /*
184      * We successfully looked through, |*ctx->object| determines if we
185      * actually found something.
186      */
187     return (*data->object != NULL);
188 }
189 
190 static void decoder_clean_pkey_construct_arg(void *construct_data)
191 {
192     struct decoder_pkey_data_st *data = construct_data;
193 
194     if (data != NULL) {
195         sk_EVP_KEYMGMT_pop_free(data->keymgmts, EVP_KEYMGMT_free);
196         OPENSSL_free(data->propq);
197         OPENSSL_free(data->object_type);
198         OPENSSL_free(data);
199     }
200 }
201 
202 static void collect_name(const char *name, void *arg)
203 {
204     STACK_OF(OPENSSL_CSTRING) *names = arg;
205 
206     sk_OPENSSL_CSTRING_push(names, name);
207 }
208 
209 static void collect_keymgmt(EVP_KEYMGMT *keymgmt, void *arg)
210 {
211     STACK_OF(EVP_KEYMGMT) *keymgmts = arg;
212 
213     if (!EVP_KEYMGMT_up_ref(keymgmt) /* ref++ */)
214         return;
215     if (sk_EVP_KEYMGMT_push(keymgmts, keymgmt) <= 0) {
216         EVP_KEYMGMT_free(keymgmt);   /* ref-- */
217         return;
218     }
219 }
220 
221 struct collect_decoder_data_st {
222     STACK_OF(OPENSSL_CSTRING) *names;
223     OSSL_DECODER_CTX *ctx;
224 
225     int total;
226     unsigned int error_occurred:1;
227 };
228 
229 static void collect_decoder(OSSL_DECODER *decoder, void *arg)
230 {
231     struct collect_decoder_data_st *data = arg;
232     size_t i, end_i;
233     const OSSL_PROVIDER *prov = OSSL_DECODER_get0_provider(decoder);
234     void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
235 
236     if (data->error_occurred)
237         return;
238 
239     if (data->names == NULL) {
240         data->error_occurred = 1;
241         return;
242     }
243 
244     /*
245      * Either the caller didn't give a selection, or if they did,
246      * the decoder must tell us if it supports that selection to
247      * be accepted.  If the decoder doesn't have |does_selection|,
248      * it's seen as taking anything.
249      */
250     if (decoder->does_selection != NULL
251             && !decoder->does_selection(provctx, data->ctx->selection))
252         return;
253 
254     OSSL_TRACE_BEGIN(DECODER) {
255         BIO_printf(trc_out,
256                    "(ctx %p) Checking out decoder %p:\n"
257                    "    %s with %s\n",
258                    (void *)data->ctx, (void *)decoder,
259                    OSSL_DECODER_get0_name(decoder),
260                    OSSL_DECODER_get0_properties(decoder));
261     } OSSL_TRACE_END(DECODER);
262 
263     end_i = sk_OPENSSL_CSTRING_num(data->names);
264     for (i = 0; i < end_i; i++) {
265         const char *name = sk_OPENSSL_CSTRING_value(data->names, i);
266 
267         if (OSSL_DECODER_is_a(decoder, name)) {
268             void *decoderctx = NULL;
269             OSSL_DECODER_INSTANCE *di = NULL;
270 
271             if ((decoderctx = decoder->newctx(provctx)) == NULL) {
272                 data->error_occurred = 1;
273                 return;
274             }
275             if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
276                 decoder->freectx(decoderctx);
277                 data->error_occurred = 1;
278                 return;
279             }
280 
281             OSSL_TRACE_BEGIN(DECODER) {
282                 BIO_printf(trc_out,
283                            "(ctx %p) Checking out decoder %p:\n"
284                            "    %s with %s\n",
285                            (void *)data->ctx, (void *)decoder,
286                            OSSL_DECODER_get0_name(decoder),
287                            OSSL_DECODER_get0_properties(decoder));
288             } OSSL_TRACE_END(DECODER);
289 
290             if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
291                 ossl_decoder_instance_free(di);
292                 data->error_occurred = 1;
293                 return;
294             }
295             data->total++;
296 
297             /* Success */
298             return;
299         }
300     }
301 
302     /* Decoder not suitable - but not a fatal error */
303     data->error_occurred = 0;
304 }
305 
306 int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx,
307                                     EVP_PKEY **pkey, const char *keytype,
308                                     OSSL_LIB_CTX *libctx,
309                                     const char *propquery)
310 {
311     struct decoder_pkey_data_st *process_data = NULL;
312     STACK_OF(OPENSSL_CSTRING) *names = NULL;
313     const char *input_type = ctx->start_input_type;
314     const char *input_structure = ctx->input_structure;
315     int ok = 0;
316     int isecoid = 0;
317     int i, end;
318 
319     if (keytype != NULL
320             && (strcmp(keytype, "id-ecPublicKey") == 0
321                 || strcmp(keytype, "1.2.840.10045.2.1") == 0))
322         isecoid = 1;
323 
324     OSSL_TRACE_BEGIN(DECODER) {
325         BIO_printf(trc_out,
326                    "(ctx %p) Looking for decoders producing %s%s%s%s%s%s\n",
327                    (void *)ctx,
328                    keytype != NULL ? keytype : "",
329                    keytype != NULL ? " keys" : "keys of any type",
330                    input_type != NULL ? " from " : "",
331                    input_type != NULL ? input_type : "",
332                    input_structure != NULL ? " with " : "",
333                    input_structure != NULL ? input_structure : "");
334     } OSSL_TRACE_END(DECODER);
335 
336     if ((process_data = OPENSSL_zalloc(sizeof(*process_data))) == NULL
337         || (propquery != NULL
338             && (process_data->propq = OPENSSL_strdup(propquery)) == NULL)
339         || (process_data->keymgmts = sk_EVP_KEYMGMT_new_null()) == NULL
340         || (names = sk_OPENSSL_CSTRING_new_null()) == NULL) {
341         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
342         goto err;
343     }
344 
345     process_data->object = (void **)pkey;
346     process_data->libctx = libctx;
347     process_data->selection = ctx->selection;
348 
349     /* First, find all keymgmts to form goals */
350     EVP_KEYMGMT_do_all_provided(libctx, collect_keymgmt,
351                                 process_data->keymgmts);
352 
353     /* Then, we collect all the keymgmt names */
354     end = sk_EVP_KEYMGMT_num(process_data->keymgmts);
355     for (i = 0; i < end; i++) {
356         EVP_KEYMGMT *keymgmt = sk_EVP_KEYMGMT_value(process_data->keymgmts, i);
357 
358         /*
359          * If the key type is given by the caller, we only use the matching
360          * KEYMGMTs, otherwise we use them all.
361          * We have to special case SM2 here because of its abuse of the EC OID.
362          * The EC OID can be used to identify an EC key or an SM2 key - so if
363          * we have seen that OID we try both key types
364          */
365         if (keytype == NULL
366                 || EVP_KEYMGMT_is_a(keymgmt, keytype)
367                 || (isecoid && EVP_KEYMGMT_is_a(keymgmt, "SM2"))) {
368             if (!EVP_KEYMGMT_names_do_all(keymgmt, collect_name, names)) {
369                 ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR);
370                 goto err;
371             }
372         }
373     }
374 
375     OSSL_TRACE_BEGIN(DECODER) {
376         end = sk_OPENSSL_CSTRING_num(names);
377         BIO_printf(trc_out,
378                    "    Found %d keytypes (possibly with duplicates)",
379                    end);
380         for (i = 0; i < end; i++)
381             BIO_printf(trc_out, "%s%s",
382                        i == 0 ? ": " : ", ",
383                        sk_OPENSSL_CSTRING_value(names, i));
384         BIO_printf(trc_out, "\n");
385     } OSSL_TRACE_END(DECODER);
386 
387     /*
388      * Finally, find all decoders that have any keymgmt of the collected
389      * keymgmt names
390      */
391     {
392         struct collect_decoder_data_st collect_decoder_data = { NULL, };
393 
394         collect_decoder_data.names = names;
395         collect_decoder_data.ctx = ctx;
396         OSSL_DECODER_do_all_provided(libctx,
397                                      collect_decoder, &collect_decoder_data);
398         sk_OPENSSL_CSTRING_free(names);
399         names = NULL;
400 
401         if (collect_decoder_data.error_occurred)
402             goto err;
403 
404         OSSL_TRACE_BEGIN(DECODER) {
405             BIO_printf(trc_out,
406                        "(ctx %p) Got %d decoders producing keys\n",
407                        (void *)ctx, collect_decoder_data.total);
408         } OSSL_TRACE_END(DECODER);
409     }
410 
411     if (OSSL_DECODER_CTX_get_num_decoders(ctx) != 0) {
412         if (!OSSL_DECODER_CTX_set_construct(ctx, decoder_construct_pkey)
413             || !OSSL_DECODER_CTX_set_construct_data(ctx, process_data)
414             || !OSSL_DECODER_CTX_set_cleanup(ctx,
415                                              decoder_clean_pkey_construct_arg))
416             goto err;
417 
418         process_data = NULL; /* Avoid it being freed */
419     }
420 
421     ok = 1;
422  err:
423     decoder_clean_pkey_construct_arg(process_data);
424     sk_OPENSSL_CSTRING_free(names);
425 
426     return ok;
427 }
428 
429 OSSL_DECODER_CTX *
430 OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
431                               const char *input_type,
432                               const char *input_structure,
433                               const char *keytype, int selection,
434                               OSSL_LIB_CTX *libctx, const char *propquery)
435 {
436     OSSL_DECODER_CTX *ctx = NULL;
437 
438     if ((ctx = OSSL_DECODER_CTX_new()) == NULL) {
439         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
440         return NULL;
441     }
442 
443     OSSL_TRACE_BEGIN(DECODER) {
444         BIO_printf(trc_out,
445                    "(ctx %p) Looking for %s decoders with selection %d\n",
446                    (void *)ctx, keytype, selection);
447         BIO_printf(trc_out, "    input type: %s, input structure: %s\n",
448                    input_type, input_structure);
449     } OSSL_TRACE_END(DECODER);
450 
451     if (OSSL_DECODER_CTX_set_input_type(ctx, input_type)
452         && OSSL_DECODER_CTX_set_input_structure(ctx, input_structure)
453         && OSSL_DECODER_CTX_set_selection(ctx, selection)
454         && ossl_decoder_ctx_setup_for_pkey(ctx, pkey, keytype,
455                                            libctx, propquery)
456         && OSSL_DECODER_CTX_add_extra(ctx, libctx, propquery)) {
457         OSSL_TRACE_BEGIN(DECODER) {
458             BIO_printf(trc_out, "(ctx %p) Got %d decoders\n",
459                        (void *)ctx, OSSL_DECODER_CTX_get_num_decoders(ctx));
460         } OSSL_TRACE_END(DECODER);
461         return ctx;
462     }
463 
464     OSSL_DECODER_CTX_free(ctx);
465     return NULL;
466 }
467