STORE 'file' scheme loader: refactor file_load to support decoding restart
[openssl.git] / crypto / store / loader_file.c
1 /*
2  * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <string.h>
11
12 #include <openssl/bio.h>
13 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
14 #include <openssl/err.h>
15 #include <openssl/evp.h>
16 #include <openssl/pem.h>
17 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
18 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
19 #include <openssl/safestack.h>
20 #include <openssl/store.h>
21 #include <openssl/ui.h>
22 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
23 #include "internal/asn1_int.h"
24 #include "store_locl.h"
25
26 #include "e_os.h"
27
28 /*
29  *  Password prompting
30  */
31
32 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
33                            size_t maxsize, const char *prompt_info, void *data)
34 {
35     UI *ui = UI_new();
36     char *prompt = NULL;
37
38     if (ui == NULL) {
39         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
40         return NULL;
41     }
42
43     if (ui_method != NULL)
44         UI_set_method(ui, ui_method);
45     UI_add_user_data(ui, data);
46
47     if ((prompt = UI_construct_prompt(ui, "pass phrase",
48                                       prompt_info)) == NULL) {
49         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
50         pass = NULL;
51     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
52                                     pass, 0, maxsize - 1)) {
53         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
54         pass = NULL;
55     } else {
56         switch (UI_process(ui)) {
57         case -2:
58             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
59                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
60             pass = NULL;
61             break;
62         case -1:
63             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
64             pass = NULL;
65             break;
66         default:
67             break;
68         }
69     }
70
71     OPENSSL_free(prompt);
72     UI_free(ui);
73     return pass;
74 }
75
76 struct pem_pass_data {
77     const UI_METHOD *ui_method;
78     void *data;
79     const char *prompt_info;
80 };
81 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
82                                    const char *prompt_info,
83                                    const UI_METHOD *ui_method, void *ui_data)
84 {
85     if (pass_data == NULL)
86         return 0;
87     pass_data->ui_method = ui_method;
88     pass_data->data = ui_data;
89     pass_data->prompt_info = prompt_info;
90     return 1;
91 }
92 static int file_get_pem_pass(char *buf, int num, int w, void *data)
93 {
94     struct pem_pass_data *pass_data = data;
95     char *pass = file_get_pass(pass_data->ui_method, buf, num,
96                                pass_data->prompt_info, pass_data->data);
97
98     return pass == NULL ? 0 : strlen(pass);
99 }
100
101 /*
102  *  The file scheme handlers
103  */
104
105 /*-
106  * The try_decode function is called to check if the blob of data can
107  * be used by this handler, and if it can, decodes it into a supported
108  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
109  * Input:
110  *    pem_name:     If this blob comes from a PEM file, this holds
111  *                  the PEM name.  If it comes from another type of
112  *                  file, this is NULL.
113  *    pem_header:   If this blob comes from a PEM file, this holds
114  *                  the PEM headers.  If it comes from another type of
115  *                  file, this is NULL.
116  *    blob:         The blob of data to match with what this handler
117  *                  can use.
118  *    len:          The length of the blob.
119  *    handler_ctx:  For a handler marked repeatable, this pointer can
120  *                  be used to create a context for the handler.  IT IS
121  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
122  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
123  *                  and destroy when about to return NULL.
124  *    ui_method:    Application UI method for getting a password, pin
125  *                  or any other interactive data.
126  *    ui_data:      Application data to be passed to ui_method when
127  *                  it's called.
128  * Output:
129  *    a OSSL_STORE_INFO
130  */
131 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
132                                                const char *pem_header,
133                                                const unsigned char *blob,
134                                                size_t len, void **handler_ctx,
135                                                const UI_METHOD *ui_method,
136                                                void *ui_data);
137 /*
138  * The eof function should return 1 if there's no more data to be found
139  * with the handler_ctx, otherwise 0.  This is only used when the handler is
140  * marked repeatable.
141  */
142 typedef int (*file_eof_fn)(void *handler_ctx);
143 /*
144  * The destroy_ctx function is used to destroy the handler_ctx that was
145  * intiated by a repeatable try_decode fuction.  This is only used when
146  * the handler is marked repeatable.
147  */
148 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
149
150 typedef struct file_handler_st {
151     const char *name;
152     file_try_decode_fn try_decode;
153     file_eof_fn eof;
154     file_destroy_ctx_fn destroy_ctx;
155
156     /* flags */
157     int repeatable;
158 } FILE_HANDLER;
159
160 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
161                                           const char *pem_header,
162                                           const unsigned char *blob,
163                                           size_t len, void **pctx,
164                                           const UI_METHOD *ui_method,
165                                           void *ui_data)
166 {
167     OSSL_STORE_INFO *store_info = NULL;
168     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
169
170     if (ctx == NULL) {
171         /* Initial parsing */
172         PKCS12 *p12;
173         int ok = 0;
174
175         if (pem_name != NULL)
176             /* No match, there is no PEM PKCS12 tag */
177             return NULL;
178
179         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
180             char *pass = NULL;
181             char tpass[PEM_BUFSIZE];
182             EVP_PKEY *pkey = NULL;
183             X509 *cert = NULL;
184             STACK_OF(X509) *chain = NULL;
185
186             if (PKCS12_verify_mac(p12, "", 0)
187                 || PKCS12_verify_mac(p12, NULL, 0)) {
188                 pass = "";
189             } else {
190                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
191                                           "PKCS12 import password",
192                                           ui_data)) == NULL) {
193                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
194                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
195                     goto p12_end;
196                 }
197                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
198                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
199                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
200                     goto p12_end;
201                 }
202             }
203
204             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
205                 OSSL_STORE_INFO *si_pkey = NULL;
206                 OSSL_STORE_INFO *si_cert = NULL;
207                 OSSL_STORE_INFO *si_ca = NULL;
208
209                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
210                     && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
211                     && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0
212                     && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
213                     && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) {
214                     ok = 1;
215                     si_pkey = NULL;
216                     si_cert = NULL;
217
218                     while(sk_X509_num(chain) > 0) {
219                         X509 *ca = sk_X509_value(chain, 0);
220
221                         if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
222                             || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) {
223                             ok = 0;
224                             break;
225                         }
226                         si_ca = NULL;
227                         (void)sk_X509_shift(chain);
228                     }
229                 }
230                 if (!ok) {
231                     OSSL_STORE_INFO_free(si_ca);
232                     OSSL_STORE_INFO_free(si_cert);
233                     OSSL_STORE_INFO_free(si_pkey);
234                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
235                     EVP_PKEY_free(pkey);
236                     X509_free(cert);
237                     sk_X509_pop_free(chain, X509_free);
238                     ctx = NULL;
239                 }
240                 *pctx = ctx;
241             }
242         }
243      p12_end:
244         PKCS12_free(p12);
245         if (!ok)
246             return NULL;
247     }
248
249     if (ctx != NULL)
250         store_info = sk_OSSL_STORE_INFO_shift(ctx);
251
252     return store_info;
253 }
254 static int eof_PKCS12(void *ctx_)
255 {
256     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
257
258     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
259 }
260 static void destroy_ctx_PKCS12(void **pctx)
261 {
262     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
263
264     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
265     *pctx = NULL;
266 }
267 static FILE_HANDLER PKCS12_handler = {
268     "PKCS12",
269     try_decode_PKCS12,
270     eof_PKCS12,
271     destroy_ctx_PKCS12,
272     1                            /* repeatable */
273 };
274
275 int pem_check_suffix(const char *pem_str, const char *suffix);
276 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
277                                               const char *pem_header,
278                                               const unsigned char *blob,
279                                               size_t len, void **pctx,
280                                               const UI_METHOD *ui_method,
281                                               void *ui_data)
282 {
283     OSSL_STORE_INFO *store_info = NULL;
284     EVP_PKEY *pkey = NULL;
285     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
286
287     if (pem_name != NULL) {
288         int slen;
289
290         if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
291             && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL)
292             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
293     } else {
294         int i;
295
296         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
297             ameth = EVP_PKEY_asn1_get0(i);
298             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
299                 continue;
300             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
301             if (pkey != NULL)
302                 break;
303         }
304     }
305     if (pkey == NULL)
306         /* No match */
307         return NULL;
308
309     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
310     if (store_info == NULL)
311         EVP_PKEY_free(pkey);
312
313     return store_info;
314 }
315 static FILE_HANDLER PrivateKey_handler = {
316     "PrivateKey",
317     try_decode_PrivateKey
318 };
319
320 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
321                                           const char *pem_header,
322                                           const unsigned char *blob,
323                                           size_t len, void **pctx,
324                                           const UI_METHOD *ui_method,
325                                           void *ui_data)
326 {
327     OSSL_STORE_INFO *store_info = NULL;
328     EVP_PKEY *pkey = NULL;
329
330     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
331         /* No match */
332         return NULL;
333
334     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL)
335         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
336
337     return store_info;
338 }
339 static FILE_HANDLER PUBKEY_handler = {
340     "PUBKEY",
341     try_decode_PUBKEY
342 };
343
344 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
345                                           const char *pem_header,
346                                           const unsigned char *blob,
347                                           size_t len, void **pctx,
348                                           const UI_METHOD *ui_method,
349                                           void *ui_data)
350 {
351     OSSL_STORE_INFO *store_info = NULL;
352     EVP_PKEY *pkey = EVP_PKEY_new();
353     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
354     int ok = 0;
355
356     if (pkey == NULL) {
357         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
358         return NULL;
359     }
360
361     if (pem_name != NULL) {
362         int slen;
363
364         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) > 0
365             && EVP_PKEY_set_type_str(pkey, pem_name, slen)
366             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
367             && ameth->param_decode != NULL
368             && ameth->param_decode(pkey, &blob, len))
369             ok = 1;
370     } else {
371         int i;
372
373         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
374             ameth = EVP_PKEY_asn1_get0(i);
375             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
376                 continue;
377             if (EVP_PKEY_set_type(pkey, ameth->pkey_id)
378                 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
379                 && ameth->param_decode != NULL
380                 && ameth->param_decode(pkey, &blob, len)) {
381                 ok = 1;
382                 break;
383             }
384         }
385     }
386
387     if (ok)
388         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
389     if (store_info == NULL)
390         EVP_PKEY_free(pkey);
391
392     return store_info;
393 }
394 static FILE_HANDLER params_handler = {
395     "params",
396     try_decode_params
397 };
398
399 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
400                                                    const char *pem_header,
401                                                    const unsigned char *blob,
402                                                    size_t len, void **pctx,
403                                                    const UI_METHOD *ui_method,
404                                                    void *ui_data)
405 {
406     OSSL_STORE_INFO *store_info = NULL;
407     X509 *cert = NULL;
408
409     /*
410      * In most cases, we can try to interpret the serialized data as a trusted
411      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
412      * (just X509), but if the PEM name specifically declares it as a trusted
413      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
414      * the fallback can be used (1) or not (0).
415      */
416     int ignore_trusted = 1;
417
418     if (pem_name != NULL) {
419         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
420             ignore_trusted = 0;
421         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
422                  && strcmp(pem_name, PEM_STRING_X509) != 0)
423             /* No match */
424             return NULL;
425     }
426
427     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
428         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL))
429         store_info = OSSL_STORE_INFO_new_CERT(cert);
430
431     if (store_info == NULL)
432         X509_free(cert);
433
434     return store_info;
435 }
436 static FILE_HANDLER X509Certificate_handler = {
437     "X509Certificate",
438     try_decode_X509Certificate
439 };
440
441 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
442                                            const char *pem_header,
443                                            const unsigned char *blob,
444                                            size_t len, void **pctx,
445                                            const UI_METHOD *ui_method,
446                                            void *ui_data)
447 {
448     OSSL_STORE_INFO *store_info = NULL;
449     X509_CRL *crl = NULL;
450
451     if (pem_name != NULL
452         && strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
453         /* No match */
454         return NULL;
455
456     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL)
457         store_info = OSSL_STORE_INFO_new_CRL(crl);
458
459     if (store_info == NULL)
460         X509_CRL_free(crl);
461
462     return store_info;
463 }
464 static FILE_HANDLER X509CRL_handler = {
465     "X509CRL",
466     try_decode_X509CRL
467 };
468
469 static const FILE_HANDLER *file_handlers[] = {
470     &PKCS12_handler,
471     &X509Certificate_handler,
472     &X509CRL_handler,
473     &params_handler,
474     &PUBKEY_handler,
475     &PrivateKey_handler,
476 };
477
478
479 /*
480  *  The loader itself
481  */
482
483 struct ossl_store_loader_ctx_st {
484     BIO *file;
485     int is_pem;
486     int errcnt;
487
488     /* The following are used when the handler is marked as repeatable */
489     const FILE_HANDLER *last_handler;
490     void *last_handler_ctx;
491 };
492
493 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
494                                         const char *uri,
495                                         const UI_METHOD *ui_method,
496                                         void *ui_data)
497 {
498     BIO *buff = NULL;
499     char peekbuf[4096];
500     OSSL_STORE_LOADER_CTX *ctx = NULL;
501     const char *path = NULL;
502
503     if (strncasecmp(uri, "file:", 5) == 0) {
504         if (strncmp(&uri[5], "//localhost/", 12) == 0) {
505             path = &uri[16];
506         } else if (strncmp(&uri[5], "///", 3) == 0) {
507             path = &uri[7];
508         } else if (strncmp(&uri[5], "//", 2) != 0) {
509             path = &uri[5];
510         } else {
511             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
512                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
513             return NULL;
514         }
515
516         /*
517          * If the scheme "file" was an explicit part of the URI, the path must
518          * be absolute.  So says RFC 8089
519          */
520         if (path[0] != '/') {
521             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
522                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
523             return NULL;
524         }
525
526 #ifdef _WIN32
527         /* Windows file: URIs with a drive letter start with a / */
528         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
529             path++;
530 #endif
531     } else {
532         path = uri;
533     }
534
535
536     ctx = OPENSSL_zalloc(sizeof(*ctx));
537     if (ctx == NULL) {
538         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
539         return NULL;
540     }
541
542     if ((buff = BIO_new(BIO_f_buffer())) == NULL)
543         goto err;
544     if ((ctx->file = BIO_new_file(path, "rb")) == NULL) {
545         goto err;
546     }
547     ctx->file = BIO_push(buff, ctx->file);
548     if (BIO_buffer_peek(ctx->file, peekbuf, sizeof(peekbuf)-1) > 0) {
549         peekbuf[sizeof(peekbuf)-1] = '\0';
550         if (strstr(peekbuf, "-----BEGIN ") != NULL)
551             ctx->is_pem = 1;
552     }
553
554     return ctx;
555  err:
556     if (buff != NULL)
557         BIO_free(buff);
558     OPENSSL_free(ctx);
559     return NULL;
560 }
561
562 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
563                                              const char *pem_name,
564                                              const char *pem_header,
565                                              unsigned char *data, size_t len,
566                                              const UI_METHOD *ui_method,
567                                              void *ui_data, int *matchcount)
568 {
569     OSSL_STORE_INFO *result = NULL;
570     BUF_MEM *new_mem = NULL;
571     char *new_pem_name = NULL;
572     int t = 0;
573
574  again:
575     {
576         size_t i = 0;
577         void *handler_ctx = NULL;
578         const FILE_HANDLER **matching_handlers =
579             OPENSSL_zalloc(sizeof(*matching_handlers)
580                            * OSSL_NELEM(file_handlers));
581
582         if (matching_handlers == NULL) {
583             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
584                           ERR_R_MALLOC_FAILURE);
585             goto err;
586         }
587
588         *matchcount = 0;
589         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
590             const FILE_HANDLER *handler = file_handlers[i];
591             void *tmp_handler_ctx = NULL;
592             OSSL_STORE_INFO *tmp_result =
593                 handler->try_decode(pem_name, pem_header, data, len,
594                                     &tmp_handler_ctx, ui_method, ui_data);
595
596             if (tmp_result == NULL) {
597                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
598                               OSSL_STORE_R_IS_NOT_A);
599                 ERR_add_error_data(1, handler->name);
600             } else {
601                 if (matching_handlers)
602                     matching_handlers[*matchcount] = handler;
603
604                 if (handler_ctx)
605                     handler->destroy_ctx(&handler_ctx);
606                 handler_ctx = tmp_handler_ctx;
607
608                 if (++*matchcount == 1) {
609                     result = tmp_result;
610                     tmp_result = NULL;
611                 } else {
612                     /* more than one match => ambiguous, kill any result */
613                     OSSL_STORE_INFO_free(result);
614                     OSSL_STORE_INFO_free(tmp_result);
615                     if (handler->destroy_ctx != NULL)
616                         handler->destroy_ctx(&handler_ctx);
617                     handler_ctx = NULL;
618                     result = NULL;
619                 }
620             }
621         }
622
623         if (*matchcount > 1)
624             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
625                           OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
626         if (*matchcount == 0)
627             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
628                           OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
629         else if (matching_handlers[0]->repeatable) {
630             if (ctx == NULL) {
631                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
632                               OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
633                 OSSL_STORE_INFO_free(result);
634                 result = NULL;
635             } else {
636                 ctx->last_handler = matching_handlers[0];
637                 ctx->last_handler_ctx = handler_ctx;
638             }
639         }
640
641         OPENSSL_free(matching_handlers);
642     }
643
644  err:
645     OPENSSL_free(new_pem_name);
646     BUF_MEM_free(new_mem);
647
648     if (result != NULL
649         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
650         pem_name = new_pem_name =
651             ossl_store_info_get0_EMBEDDED_pem_name(result);
652         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
653         data = (unsigned char *)new_mem->data;
654         len = new_mem->length;
655         OPENSSL_free(result);
656         result = NULL;
657         goto again;
658     }
659
660     if (result != NULL)
661         ERR_clear_error();
662
663     return result;
664 }
665
666 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
667                                              const UI_METHOD *ui_method,
668                                              void *ui_data)
669 {
670     OSSL_STORE_INFO *result = NULL;
671
672     if (ctx->last_handler != NULL) {
673         result = ctx->last_handler->try_decode(NULL, NULL, NULL, 0,
674                                                &ctx->last_handler_ctx,
675                                                ui_method, ui_data);
676
677         if (result == NULL) {
678             ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
679             ctx->last_handler_ctx = NULL;
680             ctx->last_handler = NULL;
681         }
682     }
683     return result;
684 }
685
686 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
687                          unsigned char **data, long *len,
688                          const UI_METHOD *ui_method,
689                          void *ui_data)
690 {
691     int i = PEM_read_bio(bp, pem_name, pem_header, data, len);
692
693     if (i <= 0)
694         return 0;
695
696     /*
697      * 10 is the number of characters in "Proc-Type:", which
698      * PEM_get_EVP_CIPHER_INFO() requires to be present.
699      * If the PEM header has less characters than that, it's
700      * not worth spending cycles on it.
701      */
702     if (strlen(*pem_header) > 10) {
703         EVP_CIPHER_INFO cipher;
704         struct pem_pass_data pass_data;
705
706         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
707             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
708             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
709                               &pass_data)) {
710             return 0;
711         }
712     }
713     return 1;
714 }
715
716 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
717 {
718     BUF_MEM *mem = NULL;
719
720     if (asn1_d2i_read_bio(bp, &mem) < 0)
721         return 0;
722
723     *data = (unsigned char *)mem->data;
724     *len = (long)mem->length;
725     OPENSSL_free(mem);
726
727     return 1;
728 }
729
730 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
731 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
732 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
733                                   const UI_METHOD *ui_method, void *ui_data)
734 {
735     OSSL_STORE_INFO *result = NULL;
736     int matchcount = -1;
737
738     result = file_load_try_repeat(ctx, ui_method, ui_data);
739     if (result != NULL)
740         return result;
741
742     if (file_error(ctx))
743         return NULL;
744
745     do {
746         char *pem_name = NULL;      /* PEM record name */
747         char *pem_header = NULL;    /* PEM record header */
748         unsigned char *data = NULL; /* DER encoded data */
749         long len = 0;               /* DER encoded data length */
750
751         if (ctx->is_pem) {
752             if (!file_read_pem(ctx->file, &pem_name, &pem_header, &data, &len,
753                                ui_method, ui_data)) {
754                 if (!file_eof(ctx))
755                     ctx->errcnt++;
756                 goto err;
757             }
758         } else {
759             if (!file_read_asn1(ctx->file, &data, &len)) {
760                 if (!file_eof(ctx))
761                     ctx->errcnt++;
762                 goto err;
763             }
764         }
765
766         matchcount = -1;
767         result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
768                                       ui_method, ui_data, &matchcount);
769
770      err:
771         OPENSSL_free(pem_name);
772         OPENSSL_free(pem_header);
773         OPENSSL_free(data);
774     } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
775
776     /* We bail out on ambiguity */
777     if (matchcount > 1)
778         return NULL;
779
780     return result;
781 }
782
783 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
784 {
785     return ctx->errcnt > 0;
786 }
787
788 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
789 {
790     if (ctx->last_handler != NULL
791         && !ctx->last_handler->eof(ctx->last_handler_ctx))
792         return 0;
793     return BIO_eof(ctx->file);
794 }
795
796 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
797 {
798     if (ctx->last_handler != NULL) {
799         ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
800         ctx->last_handler_ctx = NULL;
801         ctx->last_handler = NULL;
802     }
803     BIO_free_all(ctx->file);
804     OPENSSL_free(ctx);
805     return 1;
806 }
807
808 static OSSL_STORE_LOADER file_loader =
809     {
810         "file",
811         file_open,
812         NULL,
813         file_load,
814         file_eof,
815         file_error,
816         file_close
817     };
818
819 static void store_file_loader_deinit(void)
820 {
821     ossl_store_unregister_loader_int(file_loader.scheme);
822 }
823
824 int ossl_store_file_loader_init(void)
825 {
826     int ret = ossl_store_register_loader_int(&file_loader);
827
828     OPENSSL_atexit(store_file_loader_deinit);
829     return ret;
830 }