Rename OPENSSL_CTX prefix to OSSL_LIB_CTX
[openssl.git] / crypto / encode_decode / decoder_lib.c
1 /*
2  * Copyright 2020 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/x509err.h>
17 #include "internal/passphrase.h"
18 #include "crypto/decoder.h"
19 #include "encoder_local.h"
20 #include "e_os.h"
21
22 struct decoder_process_data_st {
23     OSSL_DECODER_CTX *ctx;
24
25     /* Current BIO */
26     BIO *bio;
27
28     /* Index of the current decoder instance to be processed */
29     size_t current_decoder_inst_index;
30 };
31
32 static int decoder_process(const OSSL_PARAM params[], void *arg);
33
34 int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in)
35 {
36     struct decoder_process_data_st data;
37     int ok = 0;
38
39     memset(&data, 0, sizeof(data));
40     data.ctx = ctx;
41     data.bio = in;
42
43     /* Enable passphrase caching */
44     (void)ossl_pw_enable_passphrase_caching(&ctx->pwdata);
45
46     ok = decoder_process(NULL, &data);
47
48     /* Clear any internally cached passphrase */
49     (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata);
50
51     return ok;
52 }
53
54 #ifndef OPENSSL_NO_STDIO
55 static BIO *bio_from_file(FILE *fp)
56 {
57     BIO *b;
58
59     if ((b = BIO_new(BIO_s_file())) == NULL) {
60         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
61         return NULL;
62     }
63     BIO_set_fp(b, fp, BIO_NOCLOSE);
64     return b;
65 }
66
67 int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp)
68 {
69     BIO *b = bio_from_file(fp);
70     int ret = 0;
71
72     if (b != NULL)
73         ret = OSSL_DECODER_from_bio(ctx, b);
74
75     BIO_free(b);
76     return ret;
77 }
78 #endif
79
80 int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata,
81                            size_t *pdata_len)
82 {
83     BIO *membio;
84     int ret = 0;
85
86     if (pdata == NULL || *pdata == NULL || pdata_len == NULL) {
87         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
88         return 0;
89     }
90
91     membio = BIO_new_mem_buf(*pdata, (int)*pdata_len);
92     if (OSSL_DECODER_from_bio(ctx, membio)) {
93         *pdata_len = (size_t)BIO_get_mem_data(membio, pdata);
94         ret = 1;
95     }
96     BIO_free(membio);
97
98     return ret;
99 }
100
101 int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx,
102                                     const char *input_type)
103 {
104     if (!ossl_assert(ctx != NULL)) {
105         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
106         return 0;
107     }
108
109     /*
110      * NULL is a valid starting input type, and means that the caller leaves
111      * it to code to discover what the starting input type is.
112      */
113     ctx->start_input_type = input_type;
114     return 1;
115 }
116
117 OSSL_DECODER_INSTANCE *ossl_decoder_instance_new(OSSL_DECODER *decoder,
118                                                  void *decoderctx)
119 {
120     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
121     OSSL_PARAM params[2];
122
123     if (!ossl_assert(decoder != NULL)) {
124         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
125         return 0;
126     }
127
128     if (decoder->get_params == NULL) {
129         ERR_raise(ERR_LIB_OSSL_DECODER,
130                   OSSL_DECODER_R_MISSING_GET_PARAMS);
131         return 0;
132     }
133
134     if ((decoder_inst = OPENSSL_zalloc(sizeof(*decoder_inst))) == NULL) {
135         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
136         return 0;
137     }
138     if (!OSSL_DECODER_up_ref(decoder)) {
139         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR);
140         goto err;
141     }
142
143     /* Cache the input type for this encoder */
144     params[0] =
145         OSSL_PARAM_construct_utf8_ptr(OSSL_DECODER_PARAM_INPUT_TYPE,
146                                       (char **)&decoder_inst->input_type, 0);
147     params[1] = OSSL_PARAM_construct_end();
148
149     if (!decoder->get_params(params)
150         || !OSSL_PARAM_modified(&params[0]))
151         goto err;
152
153     decoder_inst->decoder = decoder;
154     decoder_inst->decoderctx = decoderctx;
155     return decoder_inst;
156  err:
157     ossl_decoder_instance_free(decoder_inst);
158     return NULL;
159 }
160
161 void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst)
162 {
163     if (decoder_inst != NULL) {
164         if (decoder_inst->decoder != NULL)
165             decoder_inst->decoder->freectx(decoder_inst->decoderctx);
166         decoder_inst->decoderctx = NULL;
167         OSSL_DECODER_free(decoder_inst->decoder);
168         decoder_inst->decoder = NULL;
169         OPENSSL_free(decoder_inst);
170     }
171 }
172
173 int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx,
174                                          OSSL_DECODER_INSTANCE *di)
175 {
176     if (ctx->decoder_insts == NULL
177         && (ctx->decoder_insts =
178             sk_OSSL_DECODER_INSTANCE_new_null()) == NULL) {
179         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
180         return 0;
181     }
182
183     return (sk_OSSL_DECODER_INSTANCE_push(ctx->decoder_insts, di) > 0);
184 }
185
186 int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder)
187 {
188     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
189     const OSSL_PROVIDER *prov = NULL;
190     void *decoderctx = NULL;
191     void *provctx = NULL;
192
193     if (!ossl_assert(ctx != NULL) || !ossl_assert(decoder != NULL)) {
194         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
195         return 0;
196     }
197
198     prov = OSSL_DECODER_provider(decoder);
199     provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
200
201     if ((decoderctx = decoder->newctx(provctx)) == NULL
202         || (decoder_inst =
203             ossl_decoder_instance_new(decoder, decoderctx)) == NULL)
204         goto err;
205     /* Avoid double free of decoderctx on further errors */
206     decoderctx = NULL;
207
208     if (!ossl_decoder_ctx_add_decoder_inst(ctx, decoder_inst))
209         goto err;
210
211     return 1;
212  err:
213     ossl_decoder_instance_free(decoder_inst);
214     if (decoderctx != NULL)
215         decoder->freectx(decoderctx);
216     return 0;
217 }
218
219 int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx,
220                                OSSL_LIB_CTX *libctx, const char *propq)
221 {
222     /*
223      * This function goes through existing decoder methods in
224      * |ctx->decoder_insts|, and tries to fetch new decoders that produce
225      * what the existing ones want as input, and push those newly fetched
226      * decoders on top of the same stack.
227      * Then it does the same again, but looping over the newly fetched
228      * decoders, until there are no more encoders to be fetched, or
229      * when we have done this 10 times.
230      *
231      * we do this with sliding windows on the stack by keeping track of indexes
232      * and of the end.
233      *
234      * +----------------+
235      * |   DER to RSA   | <--- w_prev_start
236      * +----------------+
237      * |   DER to DSA   |
238      * +----------------+
239      * |   DER to DH    |
240      * +----------------+
241      * |   PEM to DER   | <--- w_prev_end, w_new_start
242      * +----------------+
243      *                    <--- w_new_end
244      */
245     size_t w_prev_start, w_prev_end; /* "previous" decoders */
246     size_t w_new_start, w_new_end;   /* "new" decoders */
247     size_t count = 0; /* Calculates how many were added in each iteration */
248     size_t depth = 0; /* Counts the number of iterations */
249
250     if (!ossl_assert(ctx != NULL)) {
251         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
252         return 0;
253     }
254
255     /*
256      * If there is no stack of OSSL_DECODER_INSTANCE, we have nothing
257      * more to add.  That's fine.
258      */
259     if (ctx->decoder_insts == NULL)
260         return 1;
261
262     w_prev_start = 0;
263     w_prev_end = sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
264     do {
265         size_t i;
266
267         w_new_start = w_new_end = w_prev_end;
268
269         for (i = w_prev_start; i < w_prev_end; i++) {
270             OSSL_DECODER_INSTANCE *decoder_inst =
271                 sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
272             const char *input_type =
273                 OSSL_DECODER_INSTANCE_get_input_type(decoder_inst);
274             OSSL_DECODER *decoder = NULL;
275
276             /*
277              * If the caller has specified what the initial input should be,
278              * and the decoder implementation we're looking at has that
279              * input type, there's no point adding on more implementations
280              * on top of this one, so we don't.
281              */
282             if (ctx->start_input_type != NULL
283                 && strcasecmp(ctx->start_input_type, input_type) == 0)
284                 continue;
285
286             ERR_set_mark();
287             decoder = OSSL_DECODER_fetch(libctx, input_type, propq);
288             ERR_pop_to_mark();
289
290             if (decoder != NULL) {
291                 size_t j;
292
293                 /*
294                  * Check that we don't already have this decoder in our
295                  * stack We only need to check among the newly added ones.
296                  */
297                 for (j = w_new_start; j < w_new_end; j++) {
298                     OSSL_DECODER_INSTANCE *check_inst =
299                         sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, j);
300
301                     if (decoder == check_inst->decoder) {
302                         /* We found it, so drop the new fetch */
303                         OSSL_DECODER_free(decoder);
304                         decoder = NULL;
305                         break;
306                     }
307                 }
308             }
309
310             if (decoder == NULL)
311                 continue;
312
313             /*
314              * Apart from keeping w_new_end up to date, We don't care about
315              * errors here.  If it doesn't collect, then it doesn't...
316              */
317             if (OSSL_DECODER_CTX_add_decoder(ctx, decoder)) /* ref++ */
318                 w_new_end++;
319             OSSL_DECODER_free(decoder); /* ref-- */
320         }
321         /* How many were added in this iteration */
322         count = w_new_end - w_new_start;
323
324         /* Slide the "previous decoder" windows */
325         w_prev_start = w_new_start;
326         w_prev_end = w_new_end;
327
328         depth++;
329     } while (count != 0 && depth <= 10);
330
331     return 1;
332 }
333
334 int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx)
335 {
336     if (ctx == NULL || ctx->decoder_insts == NULL)
337         return 0;
338     return sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
339 }
340
341 int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx,
342                                    OSSL_DECODER_CONSTRUCT *construct)
343 {
344     if (!ossl_assert(ctx != NULL)) {
345         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
346         return 0;
347     }
348     ctx->construct = construct;
349     return 1;
350 }
351
352 int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx,
353                                         void *construct_data)
354 {
355     if (!ossl_assert(ctx != NULL)) {
356         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
357         return 0;
358     }
359     ctx->construct_data = construct_data;
360     return 1;
361 }
362
363 int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx,
364                                  OSSL_DECODER_CLEANUP *cleanup)
365 {
366     if (!ossl_assert(ctx != NULL)) {
367         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
368         return 0;
369     }
370     ctx->cleanup = cleanup;
371     return 1;
372 }
373
374 OSSL_DECODER_CONSTRUCT *
375 OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx)
376 {
377     if (ctx == NULL)
378         return NULL;
379     return ctx->construct;
380 }
381
382 void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx)
383 {
384     if (ctx == NULL)
385         return NULL;
386     return ctx->construct_data;
387 }
388
389 OSSL_DECODER_CLEANUP *
390 OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx)
391 {
392     if (ctx == NULL)
393         return NULL;
394     return ctx->cleanup;
395 }
396
397 int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst,
398                         void *reference, size_t reference_sz,
399                         OSSL_CALLBACK *export_cb, void *export_cbarg)
400 {
401     OSSL_DECODER *decoder = NULL;
402     void *decoderctx = NULL;
403
404     if (!(ossl_assert(decoder_inst != NULL)
405           && ossl_assert(reference != NULL)
406           && ossl_assert(export_cb != NULL)
407           && ossl_assert(export_cbarg != NULL))) {
408         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
409         return 0;
410     }
411
412     decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
413     decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
414     return decoder->export_object(decoderctx, reference, reference_sz,
415                                   export_cb, export_cbarg);
416 }
417
418 OSSL_DECODER *
419 OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst)
420 {
421     if (decoder_inst == NULL)
422         return NULL;
423     return decoder_inst->decoder;
424 }
425
426 void *
427 OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst)
428 {
429     if (decoder_inst == NULL)
430         return NULL;
431     return decoder_inst->decoderctx;
432 }
433
434 const char *
435 OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst)
436 {
437     if (decoder_inst == NULL)
438         return NULL;
439     return decoder_inst->input_type;
440 }
441
442 static int decoder_process(const OSSL_PARAM params[], void *arg)
443 {
444     struct decoder_process_data_st *data = arg;
445     OSSL_DECODER_CTX *ctx = data->ctx;
446     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
447     OSSL_DECODER *decoder = NULL;
448     BIO *bio = data->bio;
449     long loc;
450     size_t i;
451     int err, ok = 0;
452     /* For recursions */
453     struct decoder_process_data_st new_data;
454     const char *object_type = NULL;
455
456     memset(&new_data, 0, sizeof(new_data));
457     new_data.ctx = data->ctx;
458
459     if (params == NULL) {
460         /* First iteration, where we prepare for what is to come */
461
462         data->current_decoder_inst_index =
463             OSSL_DECODER_CTX_get_num_decoders(ctx);
464
465         bio = data->bio;
466     } else {
467         const OSSL_PARAM *p;
468
469         decoder_inst =
470             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts,
471                                            data->current_decoder_inst_index);
472         decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
473
474         if (ctx->construct != NULL
475             && ctx->construct(decoder_inst, params, ctx->construct_data)) {
476             ok = 1;
477             goto end;
478         }
479
480         /* The constructor didn't return success */
481
482         /*
483          * so we try to use the object we got and feed it to any next
484          * decoder that will take it.  Object references are not
485          * allowed for this.
486          * If this data isn't present, decoding has failed.
487          */
488
489         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA);
490         if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
491             goto end;
492         new_data.bio = BIO_new_mem_buf(p->data, (int)p->data_size);
493         if (new_data.bio == NULL)
494             goto end;
495         bio = new_data.bio;
496
497         /* Get the object type if there is one */
498         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
499         if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &object_type))
500             goto end;
501     }
502
503     /*
504      * If we have no more decoders to look through at this point,
505      * we failed
506      */
507     if (data->current_decoder_inst_index == 0)
508         goto end;
509
510     if ((loc = BIO_tell(bio)) < 0) {
511         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
512         goto end;
513     }
514
515     for (i = data->current_decoder_inst_index; i-- > 0;) {
516         OSSL_DECODER_INSTANCE *new_decoder_inst =
517             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
518         OSSL_DECODER *new_decoder =
519             OSSL_DECODER_INSTANCE_get_decoder(new_decoder_inst);
520         void *new_decoderctx =
521             OSSL_DECODER_INSTANCE_get_decoder_ctx(new_decoder_inst);
522         const char *new_input_type =
523             OSSL_DECODER_INSTANCE_get_input_type(new_decoder_inst);
524
525         /*
526          * If |decoder| is NULL, it means we've just started, and the caller
527          * may have specified what it expects the initial input to be.  If
528          * that's the case, we do this extra check.
529          */
530         if (decoder == NULL && ctx->start_input_type != NULL
531             && strcasecmp(ctx->start_input_type, new_input_type) != 0)
532             continue;
533
534         /*
535          * If we have a previous decoder, we check that the input type
536          * of the next to be used matches the type of this previous one.
537          * input_type is a cache of the parameter "input-type" value for
538          * that decoder.
539          */
540         if (decoder != NULL && !OSSL_DECODER_is_a(decoder, new_input_type))
541             continue;
542
543         /*
544          * If the previous decoder gave us an object type, we check to see
545          * if that matches the decoder we're currently considering.
546          */
547         if (object_type != NULL && !OSSL_DECODER_is_a(new_decoder, object_type))
548             continue;
549
550         /*
551          * Checking the return value of BIO_reset() or BIO_seek() is unsafe.
552          * Furthermore, BIO_reset() is unsafe to use if the source BIO happens
553          * to be a BIO_s_mem(), because the earlier BIO_tell() gives us zero
554          * no matter where we are in the underlying buffer we're reading from.
555          *
556          * So, we simply do a BIO_seek(), and use BIO_tell() that we're back
557          * at the same position.  This is a best effort attempt, but BIO_seek()
558          * and BIO_tell() should come as a pair...
559          */
560         (void)BIO_seek(bio, loc);
561         if (BIO_tell(bio) != loc)
562             goto end;
563
564         /* Recurse */
565         new_data.current_decoder_inst_index = i;
566         ok = new_decoder->decode(new_decoderctx, (OSSL_CORE_BIO *)bio,
567                                  decoder_process, &new_data,
568                                  ossl_pw_passphrase_callback_dec,
569                                  &new_data.ctx->pwdata);
570         if (ok)
571             break;
572         err = ERR_peek_last_error();
573         if ((ERR_GET_LIB(err) == ERR_LIB_EVP
574              && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM)
575 #ifndef OPENSSL_NO_EC
576             || (ERR_GET_LIB(err) == ERR_LIB_EC
577                 && ERR_GET_REASON(err) == EC_R_UNKNOWN_GROUP)
578 #endif
579             || (ERR_GET_LIB(err) == ERR_LIB_X509
580                 && ERR_GET_REASON(err) == X509_R_UNSUPPORTED_ALGORITHM))
581             break; /* fatal error; preserve it on the error queue and stop */
582     }
583
584  end:
585     BIO_free(new_data.bio);
586     return ok;
587 }