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/bio.h>
12 #include <openssl/params.h>
13 #include <openssl/provider.h>
14 #include <openssl/evperr.h>
15 #include <openssl/ecerr.h>
16 #include <openssl/pkcs12err.h>
17 #include <openssl/x509err.h>
18 #include <openssl/trace.h>
19 #include "internal/bio.h"
20 #include "internal/provider.h"
21 #include "crypto/decoder.h"
22 #include "encoder_local.h"
23 #include "e_os.h"
24 
25 struct decoder_process_data_st {
26     OSSL_DECODER_CTX *ctx;
27 
28     /* Current BIO */
29     BIO *bio;
30 
31     /* Index of the current decoder instance to be processed */
32     size_t current_decoder_inst_index;
33     /* For tracing, count recursion level */
34     size_t recursion;
35 
36     /*-
37      * Flags
38      */
39     unsigned int flag_next_level_called : 1;
40     unsigned int flag_construct_called : 1;
41     unsigned int flag_input_structure_checked : 1;
42 };
43 
44 static int decoder_process(const OSSL_PARAM params[], void *arg);
45 
OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in)46 int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in)
47 {
48     struct decoder_process_data_st data;
49     int ok = 0;
50     BIO *new_bio = NULL;
51     unsigned long lasterr;
52 
53     if (in == NULL) {
54         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
55         return 0;
56     }
57 
58     if (OSSL_DECODER_CTX_get_num_decoders(ctx) == 0) {
59         ERR_raise_data(ERR_LIB_OSSL_DECODER, OSSL_DECODER_R_DECODER_NOT_FOUND,
60                        "No decoders were found. For standard decoders you need "
61                        "at least one of the default or base providers "
62                        "available. Did you forget to load them?");
63         return 0;
64     }
65 
66     lasterr = ERR_peek_last_error();
67 
68     if (BIO_tell(in) < 0) {
69         new_bio = BIO_new(BIO_f_readbuffer());
70         if (new_bio == NULL)
71             return 0;
72         in = BIO_push(new_bio, in);
73     }
74     memset(&data, 0, sizeof(data));
75     data.ctx = ctx;
76     data.bio = in;
77 
78     /* Enable passphrase caching */
79     (void)ossl_pw_enable_passphrase_caching(&ctx->pwdata);
80 
81     ok = decoder_process(NULL, &data);
82 
83     if (!data.flag_construct_called) {
84         const char *spaces
85             = ctx->start_input_type != NULL && ctx->input_structure != NULL
86             ? " " : "";
87         const char *input_type_label
88             = ctx->start_input_type != NULL ? "Input type: " : "";
89         const char *input_structure_label
90             = ctx->input_structure != NULL ? "Input structure: " : "";
91         const char *comma
92             = ctx->start_input_type != NULL && ctx->input_structure != NULL
93             ? ", " : "";
94         const char *input_type
95             = ctx->start_input_type != NULL ? ctx->start_input_type : "";
96         const char *input_structure
97             = ctx->input_structure != NULL ? ctx->input_structure : "";
98 
99         if (ERR_peek_last_error() == lasterr || ERR_peek_error() == 0)
100             /* Prevent spurious decoding error but add at least something */
101             ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_UNSUPPORTED,
102                            "No supported data to decode. %s%s%s%s%s%s",
103                            spaces, input_type_label, input_type, comma,
104                            input_structure_label, input_structure);
105         ok = 0;
106     }
107 
108     /* Clear any internally cached passphrase */
109     (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata);
110 
111     if (new_bio != NULL) {
112         BIO_pop(new_bio);
113         BIO_free(new_bio);
114     }
115     return ok;
116 }
117 
118 #ifndef OPENSSL_NO_STDIO
bio_from_file(FILE *fp)119 static BIO *bio_from_file(FILE *fp)
120 {
121     BIO *b;
122 
123     if ((b = BIO_new(BIO_s_file())) == NULL) {
124         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
125         return NULL;
126     }
127     BIO_set_fp(b, fp, BIO_NOCLOSE);
128     return b;
129 }
130 
OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp)131 int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp)
132 {
133     BIO *b = bio_from_file(fp);
134     int ret = 0;
135 
136     if (b != NULL)
137         ret = OSSL_DECODER_from_bio(ctx, b);
138 
139     BIO_free(b);
140     return ret;
141 }
142 #endif
143 
OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata, size_t *pdata_len)144 int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata,
145                            size_t *pdata_len)
146 {
147     BIO *membio;
148     int ret = 0;
149 
150     if (pdata == NULL || *pdata == NULL || pdata_len == NULL) {
151         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
152         return 0;
153     }
154 
155     membio = BIO_new_mem_buf(*pdata, (int)*pdata_len);
156     if (OSSL_DECODER_from_bio(ctx, membio)) {
157         *pdata_len = (size_t)BIO_get_mem_data(membio, pdata);
158         ret = 1;
159     }
160     BIO_free(membio);
161 
162     return ret;
163 }
164 
OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection)165 int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection)
166 {
167     if (!ossl_assert(ctx != NULL)) {
168         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
169         return 0;
170     }
171 
172     /*
173      * 0 is a valid selection, and means that the caller leaves
174      * it to code to discover what the selection is.
175      */
176     ctx->selection = selection;
177     return 1;
178 }
179 
OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx, const char *input_type)180 int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx,
181                                     const char *input_type)
182 {
183     if (!ossl_assert(ctx != NULL)) {
184         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
185         return 0;
186     }
187 
188     /*
189      * NULL is a valid starting input type, and means that the caller leaves
190      * it to code to discover what the starting input type is.
191      */
192     ctx->start_input_type = input_type;
193     return 1;
194 }
195 
OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx, const char *input_structure)196 int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx,
197                                          const char *input_structure)
198 {
199     if (!ossl_assert(ctx != NULL)) {
200         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
201         return 0;
202     }
203 
204     /*
205      * NULL is a valid starting input structure, and means that the caller
206      * leaves it to code to discover what the starting input structure is.
207      */
208     ctx->input_structure = input_structure;
209     return 1;
210 }
211 
ossl_decoder_instance_new(OSSL_DECODER *decoder, void *decoderctx)212 OSSL_DECODER_INSTANCE *ossl_decoder_instance_new(OSSL_DECODER *decoder,
213                                                  void *decoderctx)
214 {
215     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
216     const OSSL_PROVIDER *prov;
217     OSSL_LIB_CTX *libctx;
218     const OSSL_PROPERTY_LIST *props;
219     const OSSL_PROPERTY_DEFINITION *prop;
220 
221     if (!ossl_assert(decoder != NULL)) {
222         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
223         return 0;
224     }
225 
226     if ((decoder_inst = OPENSSL_zalloc(sizeof(*decoder_inst))) == NULL) {
227         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
228         return 0;
229     }
230 
231     prov = OSSL_DECODER_get0_provider(decoder);
232     libctx = ossl_provider_libctx(prov);
233     props = ossl_decoder_parsed_properties(decoder);
234     if (props == NULL) {
235         ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
236                        "there are no property definitions with decoder %s",
237                        OSSL_DECODER_get0_name(decoder));
238         goto err;
239     }
240 
241     /* The "input" property is mandatory */
242     prop = ossl_property_find_property(props, libctx, "input");
243     decoder_inst->input_type = ossl_property_get_string_value(libctx, prop);
244     if (decoder_inst->input_type == NULL) {
245         ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
246                        "the mandatory 'input' property is missing "
247                        "for decoder %s (properties: %s)",
248                        OSSL_DECODER_get0_name(decoder),
249                        OSSL_DECODER_get0_properties(decoder));
250         goto err;
251     }
252 
253     /* The "structure" property is optional */
254     prop = ossl_property_find_property(props, libctx, "structure");
255     if (prop != NULL) {
256         decoder_inst->input_structure
257             = ossl_property_get_string_value(libctx, prop);
258     }
259 
260     if (!OSSL_DECODER_up_ref(decoder)) {
261         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR);
262         goto err;
263     }
264     decoder_inst->decoder = decoder;
265     decoder_inst->decoderctx = decoderctx;
266     return decoder_inst;
267  err:
268     ossl_decoder_instance_free(decoder_inst);
269     return NULL;
270 }
271 
ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst)272 void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst)
273 {
274     if (decoder_inst != NULL) {
275         if (decoder_inst->decoder != NULL)
276             decoder_inst->decoder->freectx(decoder_inst->decoderctx);
277         decoder_inst->decoderctx = NULL;
278         OSSL_DECODER_free(decoder_inst->decoder);
279         decoder_inst->decoder = NULL;
280         OPENSSL_free(decoder_inst);
281     }
282 }
283 
ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx, OSSL_DECODER_INSTANCE *di)284 int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx,
285                                       OSSL_DECODER_INSTANCE *di)
286 {
287     int ok;
288 
289     if (ctx->decoder_insts == NULL
290         && (ctx->decoder_insts =
291             sk_OSSL_DECODER_INSTANCE_new_null()) == NULL) {
292         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
293         return 0;
294     }
295 
296     ok = (sk_OSSL_DECODER_INSTANCE_push(ctx->decoder_insts, di) > 0);
297     if (ok) {
298         OSSL_TRACE_BEGIN(DECODER) {
299             BIO_printf(trc_out,
300                        "(ctx %p) Added decoder instance %p for decoder %p\n"
301                        "    %s with %s\n",
302                        (void *)ctx, (void *)di, (void *)di->decoder,
303                        OSSL_DECODER_get0_name(di->decoder),
304                        OSSL_DECODER_get0_properties(di->decoder));
305         } OSSL_TRACE_END(DECODER);
306     }
307     return ok;
308 }
309 
OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder)310 int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder)
311 {
312     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
313     const OSSL_PROVIDER *prov = NULL;
314     void *decoderctx = NULL;
315     void *provctx = NULL;
316 
317     if (!ossl_assert(ctx != NULL) || !ossl_assert(decoder != NULL)) {
318         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
319         return 0;
320     }
321 
322     prov = OSSL_DECODER_get0_provider(decoder);
323     provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
324 
325     if ((decoderctx = decoder->newctx(provctx)) == NULL
326         || (decoder_inst =
327             ossl_decoder_instance_new(decoder, decoderctx)) == NULL)
328         goto err;
329     /* Avoid double free of decoderctx on further errors */
330     decoderctx = NULL;
331 
332     if (!ossl_decoder_ctx_add_decoder_inst(ctx, decoder_inst))
333         goto err;
334 
335     return 1;
336  err:
337     ossl_decoder_instance_free(decoder_inst);
338     if (decoderctx != NULL)
339         decoder->freectx(decoderctx);
340     return 0;
341 }
342 
343 struct collect_extra_decoder_data_st {
344     OSSL_DECODER_CTX *ctx;
345     const char *output_type;
346     /*
347      * 0 to check that the decoder's input type is the same as the decoder name
348      * 1 to check that the decoder's input type differs from the decoder name
349      */
350     enum { IS_SAME = 0, IS_DIFFERENT = 1 } type_check;
351     size_t w_prev_start, w_prev_end; /* "previous" decoders */
352     size_t w_new_start, w_new_end;   /* "new" decoders */
353 };
354 
355 DEFINE_STACK_OF(OSSL_DECODER)
356 
collect_all_decoders(OSSL_DECODER *decoder, void *arg)357 static void collect_all_decoders(OSSL_DECODER *decoder, void *arg)
358 {
359     STACK_OF(OSSL_DECODER) *skdecoders = arg;
360 
361     if (OSSL_DECODER_up_ref(decoder)
362             && !sk_OSSL_DECODER_push(skdecoders, decoder))
363         OSSL_DECODER_free(decoder);
364 }
365 
collect_extra_decoder(OSSL_DECODER *decoder, void *arg)366 static void collect_extra_decoder(OSSL_DECODER *decoder, void *arg)
367 {
368     struct collect_extra_decoder_data_st *data = arg;
369     size_t j;
370     const OSSL_PROVIDER *prov = OSSL_DECODER_get0_provider(decoder);
371     void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
372 
373     if (OSSL_DECODER_is_a(decoder, data->output_type)) {
374         void *decoderctx = NULL;
375         OSSL_DECODER_INSTANCE *di = NULL;
376 
377         OSSL_TRACE_BEGIN(DECODER) {
378             BIO_printf(trc_out,
379                        "(ctx %p) [%d] Checking out decoder %p:\n"
380                        "    %s with %s\n",
381                        (void *)data->ctx, data->type_check, (void *)decoder,
382                        OSSL_DECODER_get0_name(decoder),
383                        OSSL_DECODER_get0_properties(decoder));
384         } OSSL_TRACE_END(DECODER);
385 
386         /*
387          * Check that we don't already have this decoder in our stack,
388          * starting with the previous windows but also looking at what
389          * we have added in the current window.
390          */
391         for (j = data->w_prev_start; j < data->w_new_end; j++) {
392             OSSL_DECODER_INSTANCE *check_inst =
393                 sk_OSSL_DECODER_INSTANCE_value(data->ctx->decoder_insts, j);
394 
395             if (decoder->base.algodef == check_inst->decoder->base.algodef) {
396                 /* We found it, so don't do anything more */
397                 OSSL_TRACE_BEGIN(DECODER) {
398                     BIO_printf(trc_out,
399                                "    REJECTED: already exists in the chain\n");
400                 } OSSL_TRACE_END(DECODER);
401                 return;
402             }
403         }
404 
405         if ((decoderctx = decoder->newctx(provctx)) == NULL)
406             return;
407 
408         if ((di = ossl_decoder_instance_new(decoder, decoderctx)) == NULL) {
409             decoder->freectx(decoderctx);
410             return;
411         }
412 
413         switch (data->type_check) {
414         case IS_SAME:
415             /* If it differs, this is not a decoder to add for now. */
416             if (!OSSL_DECODER_is_a(decoder,
417                                    OSSL_DECODER_INSTANCE_get_input_type(di))) {
418                 ossl_decoder_instance_free(di);
419                 OSSL_TRACE_BEGIN(DECODER) {
420                     BIO_printf(trc_out,
421                                "    REJECTED: input type doesn't match output type\n");
422                 } OSSL_TRACE_END(DECODER);
423                 return;
424             }
425             break;
426         case IS_DIFFERENT:
427             /* If it's the same, this is not a decoder to add for now. */
428             if (OSSL_DECODER_is_a(decoder,
429                                   OSSL_DECODER_INSTANCE_get_input_type(di))) {
430                 ossl_decoder_instance_free(di);
431                 OSSL_TRACE_BEGIN(DECODER) {
432                     BIO_printf(trc_out,
433                                "    REJECTED: input type matches output type\n");
434                 } OSSL_TRACE_END(DECODER);
435                 return;
436             }
437             break;
438         }
439 
440         /*
441          * Apart from keeping w_new_end up to date, We don't care about
442          * errors here.  If it doesn't collect, then it doesn't...
443          */
444         if (!ossl_decoder_ctx_add_decoder_inst(data->ctx, di)) {
445             ossl_decoder_instance_free(di);
446             return;
447         }
448 
449         data->w_new_end++;
450     }
451 }
452 
OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx, OSSL_LIB_CTX *libctx, const char *propq)453 int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx,
454                                OSSL_LIB_CTX *libctx, const char *propq)
455 {
456     /*
457      * This function goes through existing decoder methods in
458      * |ctx->decoder_insts|, and tries to fetch new decoders that produce
459      * what the existing ones want as input, and push those newly fetched
460      * decoders on top of the same stack.
461      * Then it does the same again, but looping over the newly fetched
462      * decoders, until there are no more decoders to be fetched, or
463      * when we have done this 10 times.
464      *
465      * we do this with sliding windows on the stack by keeping track of indexes
466      * and of the end.
467      *
468      * +----------------+
469      * |   DER to RSA   | <--- w_prev_start
470      * +----------------+
471      * |   DER to DSA   |
472      * +----------------+
473      * |   DER to DH    |
474      * +----------------+
475      * |   PEM to DER   | <--- w_prev_end, w_new_start
476      * +----------------+
477      *                    <--- w_new_end
478      */
479     struct collect_extra_decoder_data_st data;
480     size_t depth = 0; /* Counts the number of iterations */
481     size_t count; /* Calculates how many were added in each iteration */
482     size_t numdecoders;
483     STACK_OF(OSSL_DECODER) *skdecoders;
484 
485     if (!ossl_assert(ctx != NULL)) {
486         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
487         return 0;
488     }
489 
490     /*
491      * If there is no stack of OSSL_DECODER_INSTANCE, we have nothing
492      * more to add.  That's fine.
493      */
494     if (ctx->decoder_insts == NULL)
495         return 1;
496 
497     OSSL_TRACE_BEGIN(DECODER) {
498         BIO_printf(trc_out, "(ctx %p) Looking for extra decoders\n",
499                    (void *)ctx);
500     } OSSL_TRACE_END(DECODER);
501 
502 
503     skdecoders = sk_OSSL_DECODER_new_null();
504     if (skdecoders == NULL) {
505         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
506         return 0;
507     }
508     OSSL_DECODER_do_all_provided(libctx, collect_all_decoders, skdecoders);
509     numdecoders = sk_OSSL_DECODER_num(skdecoders);
510 
511     memset(&data, 0, sizeof(data));
512     data.ctx = ctx;
513     data.w_prev_start = 0;
514     data.w_prev_end = sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
515     do {
516         size_t i, j;
517 
518         data.w_new_start = data.w_new_end = data.w_prev_end;
519 
520         /*
521          * Two iterations:
522          * 0.  All decoders that have the same name as their input type.
523          *     This allows for decoders that unwrap some data in a specific
524          *     encoding, and pass the result on with the same encoding.
525          * 1.  All decoders that a different name than their input type.
526          */
527         for (data.type_check = IS_SAME;
528              data.type_check <= IS_DIFFERENT;
529              data.type_check++) {
530             for (i = data.w_prev_start; i < data.w_prev_end; i++) {
531                 OSSL_DECODER_INSTANCE *decoder_inst =
532                     sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
533 
534                 data.output_type
535                     = OSSL_DECODER_INSTANCE_get_input_type(decoder_inst);
536 
537 
538                 for (j = 0; j < numdecoders; j++)
539                     collect_extra_decoder(sk_OSSL_DECODER_value(skdecoders, j),
540                                           &data);
541             }
542         }
543         /* How many were added in this iteration */
544         count = data.w_new_end - data.w_new_start;
545 
546         /* Slide the "previous decoder" windows */
547         data.w_prev_start = data.w_new_start;
548         data.w_prev_end = data.w_new_end;
549 
550         depth++;
551     } while (count != 0 && depth <= 10);
552 
553     sk_OSSL_DECODER_pop_free(skdecoders, OSSL_DECODER_free);
554     return 1;
555 }
556 
OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx)557 int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx)
558 {
559     if (ctx == NULL || ctx->decoder_insts == NULL)
560         return 0;
561     return sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
562 }
563 
OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CONSTRUCT *construct)564 int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx,
565                                    OSSL_DECODER_CONSTRUCT *construct)
566 {
567     if (!ossl_assert(ctx != NULL)) {
568         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
569         return 0;
570     }
571     ctx->construct = construct;
572     return 1;
573 }
574 
OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx, void *construct_data)575 int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx,
576                                         void *construct_data)
577 {
578     if (!ossl_assert(ctx != NULL)) {
579         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
580         return 0;
581     }
582     ctx->construct_data = construct_data;
583     return 1;
584 }
585 
OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx, OSSL_DECODER_CLEANUP *cleanup)586 int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx,
587                                  OSSL_DECODER_CLEANUP *cleanup)
588 {
589     if (!ossl_assert(ctx != NULL)) {
590         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
591         return 0;
592     }
593     ctx->cleanup = cleanup;
594     return 1;
595 }
596 
597 OSSL_DECODER_CONSTRUCT *
OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx)598 OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx)
599 {
600     if (ctx == NULL)
601         return NULL;
602     return ctx->construct;
603 }
604 
OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx)605 void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx)
606 {
607     if (ctx == NULL)
608         return NULL;
609     return ctx->construct_data;
610 }
611 
612 OSSL_DECODER_CLEANUP *
OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx)613 OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx)
614 {
615     if (ctx == NULL)
616         return NULL;
617     return ctx->cleanup;
618 }
619 
OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst, void *reference, size_t reference_sz, OSSL_CALLBACK *export_cb, void *export_cbarg)620 int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst,
621                         void *reference, size_t reference_sz,
622                         OSSL_CALLBACK *export_cb, void *export_cbarg)
623 {
624     OSSL_DECODER *decoder = NULL;
625     void *decoderctx = NULL;
626 
627     if (!(ossl_assert(decoder_inst != NULL)
628           && ossl_assert(reference != NULL)
629           && ossl_assert(export_cb != NULL)
630           && ossl_assert(export_cbarg != NULL))) {
631         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
632         return 0;
633     }
634 
635     decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
636     decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
637     return decoder->export_object(decoderctx, reference, reference_sz,
638                                   export_cb, export_cbarg);
639 }
640 
641 OSSL_DECODER *
OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst)642 OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst)
643 {
644     if (decoder_inst == NULL)
645         return NULL;
646     return decoder_inst->decoder;
647 }
648 
649 void *
OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst)650 OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst)
651 {
652     if (decoder_inst == NULL)
653         return NULL;
654     return decoder_inst->decoderctx;
655 }
656 
657 const char *
OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst)658 OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst)
659 {
660     if (decoder_inst == NULL)
661         return NULL;
662     return decoder_inst->input_type;
663 }
664 
665 const char *
OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst, int *was_set)666 OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst,
667                                           int *was_set)
668 {
669     if (decoder_inst == NULL)
670         return NULL;
671     *was_set = decoder_inst->flag_input_structure_was_set;
672     return decoder_inst->input_structure;
673 }
674 
decoder_process(const OSSL_PARAM params[], void *arg)675 static int decoder_process(const OSSL_PARAM params[], void *arg)
676 {
677     struct decoder_process_data_st *data = arg;
678     OSSL_DECODER_CTX *ctx = data->ctx;
679     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
680     OSSL_DECODER *decoder = NULL;
681     OSSL_CORE_BIO *cbio = NULL;
682     BIO *bio = data->bio;
683     long loc;
684     size_t i;
685     int ok = 0;
686     /* For recursions */
687     struct decoder_process_data_st new_data;
688     const char *data_type = NULL;
689     const char *data_structure = NULL;
690 
691     /*
692      * This is an indicator up the call stack that something was indeed
693      * decoded, leading to a recursive call of this function.
694      */
695     data->flag_next_level_called = 1;
696 
697     memset(&new_data, 0, sizeof(new_data));
698     new_data.ctx = data->ctx;
699     new_data.recursion = data->recursion + 1;
700 
701 #define LEVEL_STR ">>>>>>>>>>>>>>>>"
702 #define LEVEL (new_data.recursion < sizeof(LEVEL_STR)                   \
703                ? &LEVEL_STR[sizeof(LEVEL_STR) - new_data.recursion - 1] \
704                : LEVEL_STR "...")
705 
706     if (params == NULL) {
707         /* First iteration, where we prepare for what is to come */
708 
709         OSSL_TRACE_BEGIN(DECODER) {
710             BIO_printf(trc_out,
711                        "(ctx %p) starting to walk the decoder chain\n",
712                        (void *)new_data.ctx);
713         } OSSL_TRACE_END(DECODER);
714 
715         data->current_decoder_inst_index =
716             OSSL_DECODER_CTX_get_num_decoders(ctx);
717 
718         bio = data->bio;
719     } else {
720         const OSSL_PARAM *p;
721         const char *trace_data_structure;
722 
723         decoder_inst =
724             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts,
725                                            data->current_decoder_inst_index);
726         decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
727 
728         data->flag_construct_called = 0;
729         if (ctx->construct != NULL) {
730             int rv;
731 
732             OSSL_TRACE_BEGIN(DECODER) {
733                 BIO_printf(trc_out,
734                            "(ctx %p) %s Running constructor\n",
735                            (void *)new_data.ctx, LEVEL);
736             } OSSL_TRACE_END(DECODER);
737 
738             rv = ctx->construct(decoder_inst, params, ctx->construct_data);
739 
740             OSSL_TRACE_BEGIN(DECODER) {
741                 BIO_printf(trc_out,
742                            "(ctx %p) %s Running constructor => %d\n",
743                            (void *)new_data.ctx, LEVEL, rv);
744             } OSSL_TRACE_END(DECODER);
745 
746             data->flag_construct_called = 1;
747             ok = (rv > 0);
748             if (ok)
749                 goto end;
750         }
751 
752         /* The constructor didn't return success */
753 
754         /*
755          * so we try to use the object we got and feed it to any next
756          * decoder that will take it.  Object references are not
757          * allowed for this.
758          * If this data isn't present, decoding has failed.
759          */
760 
761         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA);
762         if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
763             goto end;
764         new_data.bio = BIO_new_mem_buf(p->data, (int)p->data_size);
765         if (new_data.bio == NULL)
766             goto end;
767         bio = new_data.bio;
768 
769         /* Get the data type if there is one */
770         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
771         if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_type))
772             goto end;
773 
774         /* Get the data structure if there is one */
775         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE);
776         if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_structure))
777             goto end;
778 
779         /*
780          * If the data structure is "type-specific" and the data type is
781          * given, we drop the data structure.  The reasoning is that the
782          * data type is already enough to find the applicable next decoder,
783          * so an additional "type-specific" data structure is extraneous.
784          *
785          * Furthermore, if the OSSL_DECODER caller asked for a type specific
786          * structure under another name, such as "DH", we get a mismatch
787          * if the data structure we just received is "type-specific".
788          * There's only so much you can do without infusing this code with
789          * too special knowledge.
790          */
791         trace_data_structure = data_structure;
792         if (data_type != NULL && data_structure != NULL
793             && OPENSSL_strcasecmp(data_structure, "type-specific") == 0)
794             data_structure = NULL;
795 
796         OSSL_TRACE_BEGIN(DECODER) {
797             BIO_printf(trc_out,
798                        "(ctx %p) %s incoming from previous decoder (%p):\n"
799                        "    data type: %s, data structure: %s%s\n",
800                        (void *)new_data.ctx, LEVEL, (void *)decoder,
801                        data_type, trace_data_structure,
802                        (trace_data_structure == data_structure
803                         ? "" : " (dropped)"));
804         } OSSL_TRACE_END(DECODER);
805     }
806 
807     /*
808      * If we have no more decoders to look through at this point,
809      * we failed
810      */
811     if (data->current_decoder_inst_index == 0)
812         goto end;
813 
814     if ((loc = BIO_tell(bio)) < 0) {
815         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
816         goto end;
817     }
818 
819     if ((cbio = ossl_core_bio_new_from_bio(bio)) == NULL) {
820         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
821         goto end;
822     }
823 
824     for (i = data->current_decoder_inst_index; i-- > 0;) {
825         OSSL_DECODER_INSTANCE *new_decoder_inst =
826             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
827         OSSL_DECODER *new_decoder =
828             OSSL_DECODER_INSTANCE_get_decoder(new_decoder_inst);
829         void *new_decoderctx =
830             OSSL_DECODER_INSTANCE_get_decoder_ctx(new_decoder_inst);
831         const char *new_input_type =
832             OSSL_DECODER_INSTANCE_get_input_type(new_decoder_inst);
833         int n_i_s_was_set = 0;   /* We don't care here */
834         const char *new_input_structure =
835             OSSL_DECODER_INSTANCE_get_input_structure(new_decoder_inst,
836                                                       &n_i_s_was_set);
837 
838         OSSL_TRACE_BEGIN(DECODER) {
839             BIO_printf(trc_out,
840                        "(ctx %p) %s [%u] Considering decoder instance %p (decoder %p):\n"
841                        "    %s with %s\n",
842                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
843                        (void *)new_decoder_inst, (void *)new_decoder,
844                        OSSL_DECODER_get0_name(new_decoder),
845                        OSSL_DECODER_get0_properties(new_decoder));
846         } OSSL_TRACE_END(DECODER);
847 
848         /*
849          * If |decoder| is NULL, it means we've just started, and the caller
850          * may have specified what it expects the initial input to be.  If
851          * that's the case, we do this extra check.
852          */
853         if (decoder == NULL && ctx->start_input_type != NULL
854             && OPENSSL_strcasecmp(ctx->start_input_type, new_input_type) != 0) {
855             OSSL_TRACE_BEGIN(DECODER) {
856                 BIO_printf(trc_out,
857                            "(ctx %p) %s [%u] the start input type '%s' doesn't match the input type of the considered decoder, skipping...\n",
858                            (void *)new_data.ctx, LEVEL, (unsigned int)i,
859                            ctx->start_input_type);
860             } OSSL_TRACE_END(DECODER);
861             continue;
862         }
863 
864         /*
865          * If we have a previous decoder, we check that the input type
866          * of the next to be used matches the type of this previous one.
867          * |new_input_type| holds the value of the "input-type" parameter
868          * for the decoder we're currently considering.
869          */
870         if (decoder != NULL && !OSSL_DECODER_is_a(decoder, new_input_type)) {
871             OSSL_TRACE_BEGIN(DECODER) {
872                 BIO_printf(trc_out,
873                            "(ctx %p) %s [%u] the input type doesn't match the name of the previous decoder (%p), skipping...\n",
874                            (void *)new_data.ctx, LEVEL, (unsigned int)i,
875                            (void *)decoder);
876             } OSSL_TRACE_END(DECODER);
877             continue;
878         }
879 
880         /*
881          * If the previous decoder gave us a data type, we check to see
882          * if that matches the decoder we're currently considering.
883          */
884         if (data_type != NULL && !OSSL_DECODER_is_a(new_decoder, data_type)) {
885             OSSL_TRACE_BEGIN(DECODER) {
886                 BIO_printf(trc_out,
887                            "(ctx %p) %s [%u] the previous decoder's data type doesn't match the name of the considered decoder, skipping...\n",
888                            (void *)new_data.ctx, LEVEL, (unsigned int)i);
889             } OSSL_TRACE_END(DECODER);
890             continue;
891         }
892 
893         /*
894          * If the previous decoder gave us a data structure name, we check
895          * to see that it matches the input data structure of the decoder
896          * we're currently considering.
897          */
898         if (data_structure != NULL
899             && (new_input_structure == NULL
900                 || OPENSSL_strcasecmp(data_structure,
901                                       new_input_structure) != 0)) {
902             OSSL_TRACE_BEGIN(DECODER) {
903                 BIO_printf(trc_out,
904                            "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure of the considered decoder, skipping...\n",
905                            (void *)new_data.ctx, LEVEL, (unsigned int)i);
906             } OSSL_TRACE_END(DECODER);
907             continue;
908         }
909 
910         /*
911          * If the decoder we're currently considering specifies a structure,
912          * and this check hasn't already been done earlier in this chain of
913          * decoder_process() calls, check that it matches the user provided
914          * input structure, if one is given.
915          */
916         if (!data->flag_input_structure_checked
917             && ctx->input_structure != NULL
918             && new_input_structure != NULL) {
919             data->flag_input_structure_checked = 1;
920             if (OPENSSL_strcasecmp(new_input_structure,
921                                    ctx->input_structure) != 0) {
922                 OSSL_TRACE_BEGIN(DECODER) {
923                     BIO_printf(trc_out,
924                                "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure given by the user, skipping...\n",
925                                (void *)new_data.ctx, LEVEL, (unsigned int)i);
926                 } OSSL_TRACE_END(DECODER);
927                 continue;
928             }
929         }
930 
931         /*
932          * Checking the return value of BIO_reset() or BIO_seek() is unsafe.
933          * Furthermore, BIO_reset() is unsafe to use if the source BIO happens
934          * to be a BIO_s_mem(), because the earlier BIO_tell() gives us zero
935          * no matter where we are in the underlying buffer we're reading from.
936          *
937          * So, we simply do a BIO_seek(), and use BIO_tell() that we're back
938          * at the same position.  This is a best effort attempt, but BIO_seek()
939          * and BIO_tell() should come as a pair...
940          */
941         (void)BIO_seek(bio, loc);
942         if (BIO_tell(bio) != loc)
943             goto end;
944 
945         /* Recurse */
946         OSSL_TRACE_BEGIN(DECODER) {
947             BIO_printf(trc_out,
948                        "(ctx %p) %s [%u] Running decoder instance %p\n",
949                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
950                        (void *)new_decoder_inst);
951         } OSSL_TRACE_END(DECODER);
952 
953         /*
954          * We only care about errors reported from decoder implementations
955          * if it returns false (i.e. there was a fatal error).
956          */
957         ERR_set_mark();
958 
959         new_data.current_decoder_inst_index = i;
960         new_data.flag_input_structure_checked
961             = data->flag_input_structure_checked;
962         ok = new_decoder->decode(new_decoderctx, cbio,
963                                  new_data.ctx->selection,
964                                  decoder_process, &new_data,
965                                  ossl_pw_passphrase_callback_dec,
966                                  &new_data.ctx->pwdata);
967 
968         OSSL_TRACE_BEGIN(DECODER) {
969             BIO_printf(trc_out,
970                        "(ctx %p) %s [%u] Running decoder instance %p => %d"
971                        " (recursed further: %s, construct called: %s)\n",
972                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
973                        (void *)new_decoder_inst, ok,
974                        new_data.flag_next_level_called ? "yes" : "no",
975                        new_data.flag_construct_called ? "yes" : "no");
976         } OSSL_TRACE_END(DECODER);
977 
978         data->flag_construct_called = new_data.flag_construct_called;
979 
980         /* Break on error or if we tried to construct an object already */
981         if (!ok || data->flag_construct_called) {
982             ERR_clear_last_mark();
983             break;
984         }
985         ERR_pop_to_mark();
986 
987         /*
988          * Break if the decoder implementation that we called recursed, since
989          * that indicates that it successfully decoded something.
990          */
991         if (new_data.flag_next_level_called)
992             break;
993     }
994 
995  end:
996     ossl_core_bio_free(cbio);
997     BIO_free(new_data.bio);
998     return ok;
999 }
1000