558980a591394091145c4b0a155eed33ebbb3619
[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 int file_eof(OSSL_STORE_LOADER_CTX *ctx);
563 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
564 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
565                                   const UI_METHOD *ui_method, void *ui_data)
566 {
567     OSSL_STORE_INFO *result = NULL;
568     int matchcount = -1;
569
570     if (ctx->last_handler != NULL) {
571         result = ctx->last_handler->try_decode(NULL, NULL, NULL, 0,
572                                                &ctx->last_handler_ctx,
573                                                ui_method, ui_data);
574
575         if (result != NULL)
576             return result;
577
578         ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
579         ctx->last_handler_ctx = NULL;
580         ctx->last_handler = NULL;
581     }
582
583     if (file_error(ctx))
584         return NULL;
585
586     do {
587         char *pem_name = NULL;      /* PEM record name */
588         char *pem_header = NULL;    /* PEM record header */
589         unsigned char *data = NULL; /* DER encoded data */
590         BUF_MEM *mem = NULL;
591         long len = 0;               /* DER encoded data length */
592         int r = 0;
593
594         matchcount = -1;
595         if (ctx->is_pem) {
596             r = PEM_read_bio(ctx->file, &pem_name, &pem_header, &data, &len);
597             if (r <= 0) {
598                 if (!file_eof(ctx))
599                     ctx->errcnt++;
600                 goto end;
601             }
602
603             /*
604              * 10 is the number of characters in "Proc-Type:", which
605              * PEM_get_EVP_CIPHER_INFO() requires to be present.
606              * If the PEM header has less characters than that, it's
607              * not worth spending cycles on it.
608              */
609             if (strlen(pem_header) > 10) {
610                 EVP_CIPHER_INFO cipher;
611                 struct pem_pass_data pass_data;
612
613                 if (!PEM_get_EVP_CIPHER_INFO(pem_header, &cipher)
614                     || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method,
615                                                 ui_data)
616                     || !PEM_do_header(&cipher, data, &len, file_get_pem_pass,
617                                       &pass_data)) {
618                     ctx->errcnt++;
619                     goto err;
620                 }
621             }
622         } else {
623             if ((len = asn1_d2i_read_bio(ctx->file, &mem)) < 0) {
624                 if (!file_eof(ctx))
625                     ctx->errcnt++;
626                 goto err;
627             }
628
629             data = (unsigned char *)mem->data;
630             len = (long)mem->length;
631         }
632
633         result = NULL;
634
635         {
636             size_t i = 0;
637             void *handler_ctx = NULL;
638             const FILE_HANDLER **matching_handlers =
639                 OPENSSL_zalloc(sizeof(*matching_handlers)
640                                * OSSL_NELEM(file_handlers));
641
642             if (matching_handlers == NULL) {
643                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_MALLOC_FAILURE);
644                 goto err;
645             }
646
647             matchcount = 0;
648             for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
649                 const FILE_HANDLER *handler = file_handlers[i];
650                 void *tmp_handler_ctx = NULL;
651                 OSSL_STORE_INFO *tmp_result =
652                     handler->try_decode(pem_name, pem_header, data, len,
653                                         &tmp_handler_ctx, ui_method, ui_data);
654
655                 if (tmp_result == NULL) {
656                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, OSSL_STORE_R_IS_NOT_A);
657                     ERR_add_error_data(1, handler->name);
658                 } else {
659                     if (matching_handlers)
660                         matching_handlers[matchcount] = handler;
661
662                     if (handler_ctx)
663                         handler->destroy_ctx(&handler_ctx);
664                     handler_ctx = tmp_handler_ctx;
665
666                     if (++matchcount == 1) {
667                         result = tmp_result;
668                         tmp_result = NULL;
669                     } else {
670                         /* more than one match => ambiguous, kill any result */
671                         OSSL_STORE_INFO_free(result);
672                         OSSL_STORE_INFO_free(tmp_result);
673                         if (handler->destroy_ctx != NULL)
674                             handler->destroy_ctx(&handler_ctx);
675                         handler_ctx = NULL;
676                         result = NULL;
677                     }
678                 }
679             }
680
681             if (matchcount > 1)
682                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
683                               OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
684             if (matchcount == 0)
685                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
686                               OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
687             else if (matching_handlers[0]->repeatable) {
688                 ctx->last_handler = matching_handlers[0];
689                 ctx->last_handler_ctx = handler_ctx;
690                 mem = NULL;
691                 data = NULL;
692             }
693
694             OPENSSL_free(matching_handlers);
695         }
696
697         if (result)
698             ERR_clear_error();
699
700      err:
701         OPENSSL_free(pem_name);
702         OPENSSL_free(pem_header);
703         if (mem == NULL)
704             OPENSSL_free(data);
705         else
706             BUF_MEM_free(mem);
707     } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
708
709     /* We bail out on ambiguity */
710     if (matchcount > 1)
711         return NULL;
712
713  end:
714     return result;
715 }
716
717 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
718 {
719     return ctx->errcnt > 0;
720 }
721
722 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
723 {
724     if (ctx->last_handler != NULL
725         && !ctx->last_handler->eof(ctx->last_handler_ctx))
726         return 0;
727     return BIO_eof(ctx->file);
728 }
729
730 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
731 {
732     if (ctx->last_handler != NULL) {
733         ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
734         ctx->last_handler_ctx = NULL;
735         ctx->last_handler = NULL;
736     }
737     BIO_free_all(ctx->file);
738     OPENSSL_free(ctx);
739     return 1;
740 }
741
742 static OSSL_STORE_LOADER file_loader =
743     {
744         "file",
745         file_open,
746         NULL,
747         file_load,
748         file_eof,
749         file_error,
750         file_close
751     };
752
753 static void store_file_loader_deinit(void)
754 {
755     ossl_store_unregister_loader_int(file_loader.scheme);
756 }
757
758 int ossl_store_file_loader_init(void)
759 {
760     int ret = ossl_store_register_loader_int(&file_loader);
761
762     OPENSSL_atexit(store_file_loader_deinit);
763     return ret;
764 }