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