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