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