25ada817210c1baa91cf3a9389b1454580f502b7
[openssl.git] / crypto / store / loader_file.c
1 /*
2  * Copyright 2016-2018 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 "e_os.h"
11 #include <string.h>
12 #include <sys/stat.h>
13 #include <ctype.h>
14 #include <assert.h>
15
16 #include <openssl/bio.h>
17 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #include <openssl/pem.h>
21 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
22 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
23 #include <openssl/safestack.h>
24 #include <openssl/store.h>
25 #include <openssl/ui.h>
26 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
27 #include "internal/asn1_int.h"
28 #include "internal/ctype.h"
29 #include "internal/o_dir.h"
30 #include "internal/cryptlib.h"
31 #include "internal/store_int.h"
32 #include "store_locl.h"
33
34 #ifdef _WIN32
35 # define stat    _stat
36 #endif
37
38 /*-
39  *  Password prompting
40  *  ------------------
41  */
42
43 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
44                            size_t maxsize, const char *prompt_info, void *data)
45 {
46     UI *ui = UI_new();
47     char *prompt = NULL;
48
49     if (ui == NULL) {
50         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
51         return NULL;
52     }
53
54     if (ui_method != NULL)
55         UI_set_method(ui, ui_method);
56     UI_add_user_data(ui, data);
57
58     if ((prompt = UI_construct_prompt(ui, "pass phrase",
59                                       prompt_info)) == NULL) {
60         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
61         pass = NULL;
62     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
63                                     pass, 0, maxsize - 1)) {
64         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
65         pass = NULL;
66     } else {
67         switch (UI_process(ui)) {
68         case -2:
69             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
70                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
71             pass = NULL;
72             break;
73         case -1:
74             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
75             pass = NULL;
76             break;
77         default:
78             break;
79         }
80     }
81
82     OPENSSL_free(prompt);
83     UI_free(ui);
84     return pass;
85 }
86
87 struct pem_pass_data {
88     const UI_METHOD *ui_method;
89     void *data;
90     const char *prompt_info;
91 };
92
93 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
94                                    const char *prompt_info,
95                                    const UI_METHOD *ui_method, void *ui_data)
96 {
97     if (pass_data == NULL)
98         return 0;
99     pass_data->ui_method = ui_method;
100     pass_data->data = ui_data;
101     pass_data->prompt_info = prompt_info;
102     return 1;
103 }
104
105 /* This is used anywhere a pem_password_cb is needed */
106 static int file_get_pem_pass(char *buf, int num, int w, void *data)
107 {
108     struct pem_pass_data *pass_data = data;
109     char *pass = file_get_pass(pass_data->ui_method, buf, num,
110                                pass_data->prompt_info, pass_data->data);
111
112     return pass == NULL ? 0 : strlen(pass);
113 }
114
115 /*-
116  *  The file scheme decoders
117  *  ------------------------
118  *
119  *  Each possible data type has its own decoder, which either operates
120  *  through a given PEM name, or attempts to decode to see if the blob
121  *  it's given is decodable for its data type.  The assumption is that
122  *  only the correct data type will match the content.
123  */
124
125 /*-
126  * The try_decode function is called to check if the blob of data can
127  * be used by this handler, and if it can, decodes it into a supported
128  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
129  * Input:
130  *    pem_name:     If this blob comes from a PEM file, this holds
131  *                  the PEM name.  If it comes from another type of
132  *                  file, this is NULL.
133  *    pem_header:   If this blob comes from a PEM file, this holds
134  *                  the PEM headers.  If it comes from another type of
135  *                  file, this is NULL.
136  *    blob:         The blob of data to match with what this handler
137  *                  can use.
138  *    len:          The length of the blob.
139  *    handler_ctx:  For a handler marked repeatable, this pointer can
140  *                  be used to create a context for the handler.  IT IS
141  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
142  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
143  *                  and destroy when about to return NULL.
144  *    matchcount:   A pointer to an int to count matches for this data.
145  *                  Usually becomes 0 (no match) or 1 (match!), but may
146  *                  be higher in the (unlikely) event that the data matches
147  *                  more than one possibility.  The int will always be
148  *                  zero when the function is called.
149  *    ui_method:    Application UI method for getting a password, pin
150  *                  or any other interactive data.
151  *    ui_data:      Application data to be passed to ui_method when
152  *                  it's called.
153  * Output:
154  *    a OSSL_STORE_INFO
155  */
156 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
157                                                const char *pem_header,
158                                                const unsigned char *blob,
159                                                size_t len, void **handler_ctx,
160                                                int *matchcount,
161                                                const UI_METHOD *ui_method,
162                                                void *ui_data);
163 /*
164  * The eof function should return 1 if there's no more data to be found
165  * with the handler_ctx, otherwise 0.  This is only used when the handler is
166  * marked repeatable.
167  */
168 typedef int (*file_eof_fn)(void *handler_ctx);
169 /*
170  * The destroy_ctx function is used to destroy the handler_ctx that was
171  * intiated by a repeatable try_decode fuction.  This is only used when
172  * the handler is marked repeatable.
173  */
174 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
175
176 typedef struct file_handler_st {
177     const char *name;
178     file_try_decode_fn try_decode;
179     file_eof_fn eof;
180     file_destroy_ctx_fn destroy_ctx;
181
182     /* flags */
183     int repeatable;
184 } FILE_HANDLER;
185
186 /*
187  * PKCS#12 decoder.  It operates by decoding all of the blob content,
188  * extracting all the interesting data from it and storing them internally,
189  * then serving them one piece at a time.
190  */
191 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
192                                           const char *pem_header,
193                                           const unsigned char *blob,
194                                           size_t len, void **pctx,
195                                           int *matchcount,
196                                           const UI_METHOD *ui_method,
197                                           void *ui_data)
198 {
199     OSSL_STORE_INFO *store_info = NULL;
200     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
201
202     if (ctx == NULL) {
203         /* Initial parsing */
204         PKCS12 *p12;
205         int ok = 0;
206
207         if (pem_name != NULL)
208             /* No match, there is no PEM PKCS12 tag */
209             return NULL;
210
211         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
212             char *pass = NULL;
213             char tpass[PEM_BUFSIZE];
214             EVP_PKEY *pkey = NULL;
215             X509 *cert = NULL;
216             STACK_OF(X509) *chain = NULL;
217
218             *matchcount = 1;
219
220             if (PKCS12_verify_mac(p12, "", 0)
221                 || PKCS12_verify_mac(p12, NULL, 0)) {
222                 pass = "";
223             } else {
224                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
225                                           "PKCS12 import password",
226                                           ui_data)) == NULL) {
227                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
228                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
229                     goto p12_end;
230                 }
231                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
232                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
233                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
234                     goto p12_end;
235                 }
236             }
237
238             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
239                 OSSL_STORE_INFO *osi_pkey = NULL;
240                 OSSL_STORE_INFO *osi_cert = NULL;
241                 OSSL_STORE_INFO *osi_ca = NULL;
242
243                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
244                     && (osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
245                     && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0
246                     && (osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
247                     && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0) {
248                     ok = 1;
249                     osi_pkey = NULL;
250                     osi_cert = NULL;
251
252                     while(sk_X509_num(chain) > 0) {
253                         X509 *ca = sk_X509_value(chain, 0);
254
255                         if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
256                             || sk_OSSL_STORE_INFO_push(ctx, osi_ca) == 0) {
257                             ok = 0;
258                             break;
259                         }
260                         osi_ca = NULL;
261                         (void)sk_X509_shift(chain);
262                     }
263                 }
264                 if (!ok) {
265                     OSSL_STORE_INFO_free(osi_ca);
266                     OSSL_STORE_INFO_free(osi_cert);
267                     OSSL_STORE_INFO_free(osi_pkey);
268                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
269                     EVP_PKEY_free(pkey);
270                     X509_free(cert);
271                     sk_X509_pop_free(chain, X509_free);
272                     ctx = NULL;
273                 }
274                 *pctx = ctx;
275             }
276         }
277      p12_end:
278         PKCS12_free(p12);
279         if (!ok)
280             return NULL;
281     }
282
283     if (ctx != NULL) {
284         *matchcount = 1;
285         store_info = sk_OSSL_STORE_INFO_shift(ctx);
286     }
287
288     return store_info;
289 }
290
291 static int eof_PKCS12(void *ctx_)
292 {
293     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
294
295     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
296 }
297
298 static void destroy_ctx_PKCS12(void **pctx)
299 {
300     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
301
302     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
303     *pctx = NULL;
304 }
305
306 static FILE_HANDLER PKCS12_handler = {
307     "PKCS12",
308     try_decode_PKCS12,
309     eof_PKCS12,
310     destroy_ctx_PKCS12,
311     1                            /* repeatable */
312 };
313
314 /*
315  * Encrypted PKCS#8 decoder.  It operates by just decrypting the given blob
316  * into a new blob, which is returned as an EMBEDDED STORE_INFO.  The whole
317  * decoding process will then start over with the new blob.
318  */
319 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
320                                                   const char *pem_header,
321                                                   const unsigned char *blob,
322                                                   size_t len, void **pctx,
323                                                   int *matchcount,
324                                                   const UI_METHOD *ui_method,
325                                                   void *ui_data)
326 {
327     X509_SIG *p8 = NULL;
328     char kbuf[PEM_BUFSIZE];
329     char *pass = NULL;
330     const X509_ALGOR *dalg = NULL;
331     const ASN1_OCTET_STRING *doct = NULL;
332     OSSL_STORE_INFO *store_info = NULL;
333     BUF_MEM *mem = NULL;
334     unsigned char *new_data = NULL;
335     int new_data_len;
336
337     if (pem_name != NULL) {
338         if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
339             return NULL;
340         *matchcount = 1;
341     }
342
343     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
344         return NULL;
345
346     *matchcount = 1;
347
348     if ((mem = BUF_MEM_new()) == NULL) {
349         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
350                       ERR_R_MALLOC_FAILURE);
351         goto nop8;
352     }
353
354     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
355                               "PKCS8 decrypt password", ui_data)) == NULL) {
356         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
357                       OSSL_STORE_R_BAD_PASSWORD_READ);
358         goto nop8;
359     }
360
361     X509_SIG_get0(p8, &dalg, &doct);
362     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
363                           &new_data, &new_data_len, 0))
364         goto nop8;
365
366     mem->data = (char *)new_data;
367     mem->max = mem->length = (size_t)new_data_len;
368     X509_SIG_free(p8);
369
370     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
371     if (store_info == NULL) {
372         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
373                       ERR_R_MALLOC_FAILURE);
374         goto nop8;
375     }
376
377     return store_info;
378  nop8:
379     X509_SIG_free(p8);
380     BUF_MEM_free(mem);
381     return NULL;
382 }
383
384 static FILE_HANDLER PKCS8Encrypted_handler = {
385     "PKCS8Encrypted",
386     try_decode_PKCS8Encrypted
387 };
388
389 /*
390  * Private key decoder.  Decodes all sorts of private keys, both PKCS#8
391  * encoded ones and old style PEM ones (with the key type is encoded into
392  * the PEM name).
393  */
394 int pem_check_suffix(const char *pem_str, const char *suffix);
395 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
396                                               const char *pem_header,
397                                               const unsigned char *blob,
398                                               size_t len, void **pctx,
399                                               int *matchcount,
400                                               const UI_METHOD *ui_method,
401                                               void *ui_data)
402 {
403     OSSL_STORE_INFO *store_info = NULL;
404     EVP_PKEY *pkey = NULL;
405     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
406
407     if (pem_name != NULL) {
408         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
409             PKCS8_PRIV_KEY_INFO *p8inf =
410                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
411
412             *matchcount = 1;
413             if (p8inf != NULL)
414                 pkey = EVP_PKCS82PKEY(p8inf);
415             PKCS8_PRIV_KEY_INFO_free(p8inf);
416         } else {
417             int slen;
418
419             if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
420                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
421                                                    slen)) != NULL) {
422                 *matchcount = 1;
423                 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
424             }
425         }
426     } else {
427         int i;
428
429         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
430             EVP_PKEY *tmp_pkey = NULL;
431             const unsigned char *tmp_blob = blob;
432
433             ameth = EVP_PKEY_asn1_get0(i);
434             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
435                 continue;
436
437             tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len);
438             if (tmp_pkey != NULL) {
439                 if (pkey != NULL)
440                     EVP_PKEY_free(tmp_pkey);
441                 else
442                     pkey = tmp_pkey;
443                 (*matchcount)++;
444             }
445         }
446
447         if (*matchcount > 1) {
448             EVP_PKEY_free(pkey);
449             pkey = NULL;
450         }
451     }
452     if (pkey == NULL)
453         /* No match */
454         return NULL;
455
456     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
457     if (store_info == NULL)
458         EVP_PKEY_free(pkey);
459
460     return store_info;
461 }
462
463 static FILE_HANDLER PrivateKey_handler = {
464     "PrivateKey",
465     try_decode_PrivateKey
466 };
467
468 /*
469  * Public key decoder.  Only supports SubjectPublicKeyInfo formated keys.
470  */
471 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
472                                           const char *pem_header,
473                                           const unsigned char *blob,
474                                           size_t len, void **pctx,
475                                           int *matchcount,
476                                           const UI_METHOD *ui_method,
477                                           void *ui_data)
478 {
479     OSSL_STORE_INFO *store_info = NULL;
480     EVP_PKEY *pkey = NULL;
481
482     if (pem_name != NULL) {
483         if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
484             /* No match */
485             return NULL;
486         *matchcount = 1;
487     }
488
489     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
490         *matchcount = 1;
491         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
492     }
493
494     return store_info;
495 }
496
497 static FILE_HANDLER PUBKEY_handler = {
498     "PUBKEY",
499     try_decode_PUBKEY
500 };
501
502 /*
503  * Key parameter decoder.
504  */
505 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
506                                           const char *pem_header,
507                                           const unsigned char *blob,
508                                           size_t len, void **pctx,
509                                           int *matchcount,
510                                           const UI_METHOD *ui_method,
511                                           void *ui_data)
512 {
513     OSSL_STORE_INFO *store_info = NULL;
514     int slen = 0;
515     EVP_PKEY *pkey = NULL;
516     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
517     int ok = 0;
518
519     if (pem_name != NULL) {
520         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
521             return NULL;
522         *matchcount = 1;
523     }
524
525     if (slen > 0) {
526         if ((pkey = EVP_PKEY_new()) == NULL) {
527             OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
528             return NULL;
529         }
530
531
532         if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
533             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
534             && ameth->param_decode != NULL
535             && ameth->param_decode(pkey, &blob, len))
536             ok = 1;
537     } else {
538         int i;
539         EVP_PKEY *tmp_pkey = NULL;
540
541         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
542             const unsigned char *tmp_blob = blob;
543
544             if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) {
545                 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
546                 break;
547             }
548
549             ameth = EVP_PKEY_asn1_get0(i);
550             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
551                 continue;
552
553             if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id)
554                 && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL
555                 && ameth->param_decode != NULL
556                 && ameth->param_decode(tmp_pkey, &tmp_blob, len)) {
557                 if (pkey != NULL)
558                     EVP_PKEY_free(tmp_pkey);
559                 else
560                     pkey = tmp_pkey;
561                 tmp_pkey = NULL;
562                 (*matchcount)++;
563             }
564         }
565
566         EVP_PKEY_free(tmp_pkey);
567         if (*matchcount == 1) {
568             ok = 1;
569         }
570     }
571
572     if (ok)
573         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
574     if (store_info == NULL)
575         EVP_PKEY_free(pkey);
576
577     return store_info;
578 }
579
580 static FILE_HANDLER params_handler = {
581     "params",
582     try_decode_params
583 };
584
585 /*
586  * X.509 certificate decoder.
587  */
588 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
589                                                    const char *pem_header,
590                                                    const unsigned char *blob,
591                                                    size_t len, void **pctx,
592                                                    int *matchcount,
593                                                    const UI_METHOD *ui_method,
594                                                    void *ui_data)
595 {
596     OSSL_STORE_INFO *store_info = NULL;
597     X509 *cert = NULL;
598
599     /*
600      * In most cases, we can try to interpret the serialized data as a trusted
601      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
602      * (just X509), but if the PEM name specifically declares it as a trusted
603      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
604      * the fallback can be used (1) or not (0).
605      */
606     int ignore_trusted = 1;
607
608     if (pem_name != NULL) {
609         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
610             ignore_trusted = 0;
611         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
612                  && strcmp(pem_name, PEM_STRING_X509) != 0)
613             /* No match */
614             return NULL;
615         *matchcount = 1;
616     }
617
618     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
619         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
620         *matchcount = 1;
621         store_info = OSSL_STORE_INFO_new_CERT(cert);
622     }
623
624     if (store_info == NULL)
625         X509_free(cert);
626
627     return store_info;
628 }
629
630 static FILE_HANDLER X509Certificate_handler = {
631     "X509Certificate",
632     try_decode_X509Certificate
633 };
634
635 /*
636  * X.509 CRL decoder.
637  */
638 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
639                                            const char *pem_header,
640                                            const unsigned char *blob,
641                                            size_t len, void **pctx,
642                                            int *matchcount,
643                                            const UI_METHOD *ui_method,
644                                            void *ui_data)
645 {
646     OSSL_STORE_INFO *store_info = NULL;
647     X509_CRL *crl = NULL;
648
649     if (pem_name != NULL) {
650         if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
651             /* No match */
652             return NULL;
653         *matchcount = 1;
654     }
655
656     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
657         *matchcount = 1;
658         store_info = OSSL_STORE_INFO_new_CRL(crl);
659     }
660
661     if (store_info == NULL)
662         X509_CRL_free(crl);
663
664     return store_info;
665 }
666
667 static FILE_HANDLER X509CRL_handler = {
668     "X509CRL",
669     try_decode_X509CRL
670 };
671
672 /*
673  * To finish it all off, we collect all the handlers.
674  */
675 static const FILE_HANDLER *file_handlers[] = {
676     &PKCS12_handler,
677     &PKCS8Encrypted_handler,
678     &X509Certificate_handler,
679     &X509CRL_handler,
680     &params_handler,
681     &PUBKEY_handler,
682     &PrivateKey_handler,
683 };
684
685
686 /*-
687  *  The loader itself
688  *  -----------------
689  */
690
691 struct ossl_store_loader_ctx_st {
692     enum {
693         is_raw = 0,
694         is_pem,
695         is_dir
696     } type;
697     int errcnt;
698 #define FILE_FLAG_SECMEM         (1<<0)
699     unsigned int flags;
700     union {
701         struct {                 /* Used with is_raw and is_pem */
702             BIO *file;
703
704             /*
705              * The following are used when the handler is marked as
706              * repeatable
707              */
708             const FILE_HANDLER *last_handler;
709             void *last_handler_ctx;
710         } file;
711         struct {                 /* Used with is_dir */
712             OPENSSL_DIR_CTX *ctx;
713             int end_reached;
714             char *uri;
715
716             /*
717              * When a search expression is given, these are filled in.
718              * |search_name| contains the file basename to look for.
719              * The string is exactly 8 characters long.
720              */
721             char search_name[9];
722
723             /*
724              * The directory reading utility we have combines opening with
725              * reading the first name.  To make sure we can detect the end
726              * at the right time, we read early and cache the name.
727              */
728             const char *last_entry;
729             int last_errno;
730         } dir;
731     } _;
732
733     /* Expected object type.  May be unspecified */
734     int expected_type;
735 };
736
737 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
738 {
739     if (ctx->type == is_dir) {
740         OPENSSL_free(ctx->_.dir.uri);
741     } else {
742         if (ctx->_.file.last_handler != NULL) {
743             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
744             ctx->_.file.last_handler_ctx = NULL;
745             ctx->_.file.last_handler = NULL;
746         }
747     }
748     OPENSSL_free(ctx);
749 }
750
751 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
752                                         const char *uri,
753                                         const UI_METHOD *ui_method,
754                                         void *ui_data)
755 {
756     OSSL_STORE_LOADER_CTX *ctx = NULL;
757     struct stat st;
758     struct {
759         const char *path;
760         unsigned int check_absolute:1;
761     } path_data[2];
762     size_t path_data_n = 0, i;
763     const char *path;
764
765     /*
766      * First step, just take the URI as is.
767      */
768     path_data[path_data_n].check_absolute = 0;
769     path_data[path_data_n++].path = uri;
770
771     /*
772      * Second step, if the URI appears to start with the 'file' scheme,
773      * extract the path and make that the second path to check.
774      * There's a special case if the URI also contains an authority, then
775      * the full URI shouldn't be used as a path anywhere.
776      */
777     if (strncasecmp(uri, "file:", 5) == 0) {
778         const char *p = &uri[5];
779
780         if (strncmp(&uri[5], "//", 2) == 0) {
781             path_data_n--;           /* Invalidate using the full URI */
782             if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
783                 p = &uri[16];
784             } else if (uri[7] == '/') {
785                 p = &uri[7];
786             } else {
787                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
788                               OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED);
789                 return NULL;
790             }
791         }
792
793         path_data[path_data_n].check_absolute = 1;
794 #ifdef _WIN32
795         /* Windows file: URIs with a drive letter start with a / */
796         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
797             char c = ossl_tolower(p[1]);
798
799             if (c >= 'a' && c <= 'z') {
800                 p++;
801                 /* We know it's absolute, so no need to check */
802                 path_data[path_data_n].check_absolute = 0;
803             }
804         }
805 #endif
806         path_data[path_data_n++].path = p;
807     }
808
809
810     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
811         /*
812          * If the scheme "file" was an explicit part of the URI, the path must
813          * be absolute.  So says RFC 8089
814          */
815         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
816             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
817                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
818             ERR_add_error_data(1, path_data[i].path);
819             return NULL;
820         }
821
822         if (stat(path_data[i].path, &st) < 0) {
823             SYSerr(SYS_F_STAT, errno);
824             ERR_add_error_data(1, path_data[i].path);
825         } else {
826             path = path_data[i].path;
827         }
828     }
829     if (path == NULL) {
830         return NULL;
831     }
832
833     /* Successfully found a working path, clear possible collected errors */
834     ERR_clear_error();
835
836     ctx = OPENSSL_zalloc(sizeof(*ctx));
837     if (ctx == NULL) {
838         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
839         return NULL;
840     }
841
842     if ((st.st_mode & S_IFDIR) == S_IFDIR) {
843         /*
844          * Try to copy everything, even if we know that some of them must be
845          * NULL for the moment.  This prevents errors in the future, when more
846          * components may be used.
847          */
848         ctx->_.dir.uri = OPENSSL_strdup(uri);
849         ctx->type = is_dir;
850
851         if (ctx->_.dir.uri == NULL)
852             goto err;
853
854         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
855         ctx->_.dir.last_errno = errno;
856         if (ctx->_.dir.last_entry == NULL) {
857             if (ctx->_.dir.last_errno != 0) {
858                 char errbuf[256];
859                 errno = ctx->_.dir.last_errno;
860                 openssl_strerror_r(errno, errbuf, sizeof(errbuf));
861                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
862                 ERR_add_error_data(1, errbuf);
863                 goto err;
864             }
865             ctx->_.dir.end_reached = 1;
866         }
867     } else {
868         BIO *buff = NULL;
869         char peekbuf[4096] = { 0, };
870
871         if ((buff = BIO_new(BIO_f_buffer())) == NULL
872             || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
873             BIO_free_all(buff);
874             goto err;
875         }
876
877         ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
878         if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
879             peekbuf[sizeof(peekbuf) - 1] = '\0';
880             if (strstr(peekbuf, "-----BEGIN ") != NULL)
881                 ctx->type = is_pem;
882         }
883     }
884
885     return ctx;
886  err:
887     OSSL_STORE_LOADER_CTX_free(ctx);
888     return NULL;
889 }
890
891 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
892 {
893     int ret = 1;
894
895     switch (cmd) {
896     case OSSL_STORE_C_USE_SECMEM:
897         {
898             int on = *(va_arg(args, int *));
899
900             switch (on) {
901             case 0:
902                 ctx->flags &= ~FILE_FLAG_SECMEM;
903                 break;
904             case 1:
905                 ctx->flags |= FILE_FLAG_SECMEM;
906                 break;
907             default:
908                 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
909                               ERR_R_PASSED_INVALID_ARGUMENT);
910                 ret = 0;
911                 break;
912             }
913         }
914         break;
915     default:
916         break;
917     }
918
919     return ret;
920 }
921
922 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
923 {
924     ctx->expected_type = expected;
925     return 1;
926 }
927
928 static int file_find(OSSL_STORE_LOADER_CTX *ctx, OSSL_STORE_SEARCH *search)
929 {
930     /*
931      * If ctx == NULL, the library is looking to know if this loader supports
932      * the given search type.
933      */
934
935     if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
936         unsigned long hash = 0;
937
938         if (ctx == NULL)
939             return 1;
940
941         if (ctx->type != is_dir) {
942             OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
943                           OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
944             return 0;
945         }
946
947         hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
948         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
949                      "%08lx", hash);
950         return 1;
951     }
952
953     if (ctx != NULL)
954         OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
955                       OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE);
956     return 0;
957 }
958
959 /* Internal function to decode an already opened PEM file */
960 OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp)
961 {
962     OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
963
964     if (ctx == NULL) {
965         OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
966                       ERR_R_MALLOC_FAILURE);
967         return NULL;
968     }
969
970     ctx->_.file.file = bp;
971     ctx->type = is_pem;
972
973     return ctx;
974 }
975
976 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
977                                              const char *pem_name,
978                                              const char *pem_header,
979                                              unsigned char *data, size_t len,
980                                              const UI_METHOD *ui_method,
981                                              void *ui_data, int *matchcount)
982 {
983     OSSL_STORE_INFO *result = NULL;
984     BUF_MEM *new_mem = NULL;
985     char *new_pem_name = NULL;
986     int t = 0;
987
988  again:
989     {
990         size_t i = 0;
991         void *handler_ctx = NULL;
992         const FILE_HANDLER **matching_handlers =
993             OPENSSL_zalloc(sizeof(*matching_handlers)
994                            * OSSL_NELEM(file_handlers));
995
996         if (matching_handlers == NULL) {
997             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
998                           ERR_R_MALLOC_FAILURE);
999             goto err;
1000         }
1001
1002         *matchcount = 0;
1003         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1004             const FILE_HANDLER *handler = file_handlers[i];
1005             int try_matchcount = 0;
1006             void *tmp_handler_ctx = NULL;
1007             OSSL_STORE_INFO *tmp_result =
1008                 handler->try_decode(pem_name, pem_header, data, len,
1009                                     &tmp_handler_ctx, &try_matchcount,
1010                                     ui_method, ui_data);
1011
1012             if (try_matchcount > 0) {
1013
1014                 matching_handlers[*matchcount] = handler;
1015
1016                 if (handler_ctx)
1017                     handler->destroy_ctx(&handler_ctx);
1018                 handler_ctx = tmp_handler_ctx;
1019
1020                 if ((*matchcount += try_matchcount) > 1) {
1021                     /* more than one match => ambiguous, kill any result */
1022                     OSSL_STORE_INFO_free(result);
1023                     OSSL_STORE_INFO_free(tmp_result);
1024                     if (handler->destroy_ctx != NULL)
1025                         handler->destroy_ctx(&handler_ctx);
1026                     handler_ctx = NULL;
1027                     tmp_result = NULL;
1028                     result = NULL;
1029                 }
1030                 if (result == NULL)
1031                     result = tmp_result;
1032             }
1033         }
1034
1035         if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1036             ctx->_.file.last_handler = matching_handlers[0];
1037             ctx->_.file.last_handler_ctx = handler_ctx;
1038         }
1039
1040         OPENSSL_free(matching_handlers);
1041     }
1042
1043  err:
1044     OPENSSL_free(new_pem_name);
1045     BUF_MEM_free(new_mem);
1046
1047     if (result != NULL
1048         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
1049         pem_name = new_pem_name =
1050             ossl_store_info_get0_EMBEDDED_pem_name(result);
1051         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
1052         data = (unsigned char *)new_mem->data;
1053         len = new_mem->length;
1054         OPENSSL_free(result);
1055         result = NULL;
1056         goto again;
1057     }
1058
1059     if (result != NULL)
1060         ERR_clear_error();
1061
1062     return result;
1063 }
1064
1065 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1066                                              const UI_METHOD *ui_method,
1067                                              void *ui_data)
1068 {
1069     OSSL_STORE_INFO *result = NULL;
1070     int try_matchcount = 0;
1071
1072     if (ctx->_.file.last_handler != NULL) {
1073         result =
1074             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1075                                                  &ctx->_.file.last_handler_ctx,
1076                                                  &try_matchcount,
1077                                                  ui_method, ui_data);
1078
1079         if (result == NULL) {
1080             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1081             ctx->_.file.last_handler_ctx = NULL;
1082             ctx->_.file.last_handler = NULL;
1083         }
1084     }
1085     return result;
1086 }
1087
1088 static void pem_free_flag(void *pem_data, int secure, size_t num)
1089 {
1090     if (secure)
1091         OPENSSL_secure_clear_free(pem_data, num);
1092     else
1093         OPENSSL_free(pem_data);
1094 }
1095 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1096                          unsigned char **data, long *len,
1097                          const UI_METHOD *ui_method,
1098                          void *ui_data, int secure)
1099 {
1100     int i = secure
1101         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1102                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1103         : PEM_read_bio(bp, pem_name, pem_header, data, len);
1104
1105     if (i <= 0)
1106         return 0;
1107
1108     /*
1109      * 10 is the number of characters in "Proc-Type:", which
1110      * PEM_get_EVP_CIPHER_INFO() requires to be present.
1111      * If the PEM header has less characters than that, it's
1112      * not worth spending cycles on it.
1113      */
1114     if (strlen(*pem_header) > 10) {
1115         EVP_CIPHER_INFO cipher;
1116         struct pem_pass_data pass_data;
1117
1118         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1119             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
1120             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1121                               &pass_data)) {
1122             return 0;
1123         }
1124     }
1125     return 1;
1126 }
1127
1128 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1129 {
1130     BUF_MEM *mem = NULL;
1131
1132     if (asn1_d2i_read_bio(bp, &mem) < 0)
1133         return 0;
1134
1135     *data = (unsigned char *)mem->data;
1136     *len = (long)mem->length;
1137     OPENSSL_free(mem);
1138
1139     return 1;
1140 }
1141
1142 static int ends_with_dirsep(const char *uri)
1143 {
1144     if (*uri != '\0')
1145         uri += strlen(uri) - 1;
1146 #if defined __VMS
1147     if (*uri == ']' || *uri == '>' || *uri == ':')
1148         return 1;
1149 #elif defined _WIN32
1150     if (*uri == '\\')
1151         return 1;
1152 #endif
1153     return *uri == '/';
1154 }
1155
1156 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1157                             char **data)
1158 {
1159     assert(name != NULL);
1160     assert(data != NULL);
1161     {
1162         const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
1163         long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
1164             + strlen(name) + 1 /* \0 */;
1165
1166         *data = OPENSSL_zalloc(calculated_length);
1167         if (*data == NULL) {
1168             OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1169             return 0;
1170         }
1171
1172         OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1173         OPENSSL_strlcat(*data, pathsep, calculated_length);
1174         OPENSSL_strlcat(*data, name, calculated_length);
1175     }
1176     return 1;
1177 }
1178
1179 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1180 {
1181     const char *p = NULL;
1182
1183     /* If there are no search criteria, all names are accepted */
1184     if (ctx->_.dir.search_name[0] == '\0')
1185         return 1;
1186
1187     /* If the expected type isn't supported, no name is accepted */
1188     if (ctx->expected_type != 0
1189         && ctx->expected_type != OSSL_STORE_INFO_CERT
1190         && ctx->expected_type != OSSL_STORE_INFO_CRL)
1191         return 0;
1192
1193     /*
1194      * First, check the basename
1195      */
1196     if (strncasecmp(name, ctx->_.dir.search_name,
1197                     sizeof(ctx->_.dir.search_name) - 1) != 0
1198         || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1199         return 0;
1200     p = &name[sizeof(ctx->_.dir.search_name)];
1201
1202     /*
1203      * Then, if the expected type is a CRL, check that the extension starts
1204      * with 'r'
1205      */
1206     if (*p == 'r') {
1207         p++;
1208         if (ctx->expected_type != 0
1209             && ctx->expected_type != OSSL_STORE_INFO_CRL)
1210             return 0;
1211     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1212         return 0;
1213     }
1214
1215     /*
1216      * Last, check that the rest of the extension is a decimal number, at
1217      * least one digit long.
1218      */
1219     if (!ossl_isdigit(*p))
1220         return 0;
1221     while (ossl_isdigit(*p))
1222         p++;
1223
1224 # ifdef __VMS
1225     /*
1226      * One extra step here, check for a possible generation number.
1227      */
1228     if (*p == ';')
1229         for (p++; *p != '\0'; p++)
1230             if (!ossl_isdigit(*p))
1231                 break;
1232 # endif
1233
1234     /*
1235      * If we've reached the end of the string at this point, we've successfully
1236      * found a fitting file name.
1237      */
1238     return *p == '\0';
1239 }
1240
1241 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1242 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1243 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1244                                   const UI_METHOD *ui_method, void *ui_data)
1245 {
1246     OSSL_STORE_INFO *result = NULL;
1247
1248     ctx->errcnt = 0;
1249     ERR_clear_error();
1250
1251     if (ctx->type == is_dir) {
1252         do {
1253             char *newname = NULL;
1254
1255             if (ctx->_.dir.last_entry == NULL) {
1256                 if (!ctx->_.dir.end_reached) {
1257                     char errbuf[256];
1258                     assert(ctx->_.dir.last_errno != 0);
1259                     errno = ctx->_.dir.last_errno;
1260                     ctx->errcnt++;
1261                     openssl_strerror_r(errno, errbuf, sizeof(errbuf));
1262                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1263                     ERR_add_error_data(1, errbuf);
1264                 }
1265                 return NULL;
1266             }
1267
1268             if (ctx->_.dir.last_entry[0] != '.'
1269                 && file_name_check(ctx, ctx->_.dir.last_entry)
1270                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1271                 return NULL;
1272
1273             /*
1274              * On the first call (with a NULL context), OPENSSL_DIR_read()
1275              * cares about the second argument.  On the following calls, it
1276              * only cares that it isn't NULL.  Therefore, we can safely give
1277              * it our URI here.
1278              */
1279             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1280                                                      ctx->_.dir.uri);
1281             ctx->_.dir.last_errno = errno;
1282             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1283                 ctx->_.dir.end_reached = 1;
1284
1285             if (newname != NULL
1286                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1287                 OPENSSL_free(newname);
1288                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1289                 return NULL;
1290             }
1291         } while (result == NULL && !file_eof(ctx));
1292     } else {
1293         int matchcount = -1;
1294
1295      again:
1296         result = file_load_try_repeat(ctx, ui_method, ui_data);
1297         if (result != NULL)
1298             return result;
1299
1300         if (file_eof(ctx))
1301             return NULL;
1302
1303         do {
1304             char *pem_name = NULL;      /* PEM record name */
1305             char *pem_header = NULL;    /* PEM record header */
1306             unsigned char *data = NULL; /* DER encoded data */
1307             long len = 0;               /* DER encoded data length */
1308
1309             matchcount = -1;
1310             if (ctx->type == is_pem) {
1311                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1312                                    &data, &len, ui_method, ui_data,
1313                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1314                     ctx->errcnt++;
1315                     goto endloop;
1316                 }
1317             } else {
1318                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1319                     ctx->errcnt++;
1320                     goto endloop;
1321                 }
1322             }
1323
1324             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1325                                           ui_method, ui_data, &matchcount);
1326
1327             if (result != NULL)
1328                 goto endloop;
1329
1330             /*
1331              * If a PEM name matches more than one handler, the handlers are
1332              * badly coded.
1333              */
1334             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1335                 ctx->errcnt++;
1336                 goto endloop;
1337             }
1338
1339             if (matchcount > 1) {
1340                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1341                               OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1342             } else if (matchcount == 1) {
1343                 /*
1344                  * If there are other errors on the stack, they already show
1345                  * what the problem is.
1346                  */
1347                 if (ERR_peek_error() == 0) {
1348                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1349                                   OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1350                     if (pem_name != NULL)
1351                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1352                 }
1353             }
1354             if (matchcount > 0)
1355                 ctx->errcnt++;
1356
1357          endloop:
1358             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1359             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1360             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1361         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1362
1363         /* We bail out on ambiguity */
1364         if (matchcount > 1)
1365             return NULL;
1366
1367         if (result != NULL
1368             && ctx->expected_type != 0
1369             && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1370             OSSL_STORE_INFO_free(result);
1371             goto again;
1372         }
1373     }
1374
1375     return result;
1376 }
1377
1378 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1379 {
1380     return ctx->errcnt > 0;
1381 }
1382
1383 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1384 {
1385     if (ctx->type == is_dir)
1386         return ctx->_.dir.end_reached;
1387
1388     if (ctx->_.file.last_handler != NULL
1389         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1390         return 0;
1391     return BIO_eof(ctx->_.file.file);
1392 }
1393
1394 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1395 {
1396     if (ctx->type == is_dir) {
1397         OPENSSL_DIR_end(&ctx->_.dir.ctx);
1398     } else {
1399         BIO_free_all(ctx->_.file.file);
1400     }
1401     OSSL_STORE_LOADER_CTX_free(ctx);
1402     return 1;
1403 }
1404
1405 int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx)
1406 {
1407     OSSL_STORE_LOADER_CTX_free(ctx);
1408     return 1;
1409 }
1410
1411 static OSSL_STORE_LOADER file_loader =
1412     {
1413         "file",
1414         NULL,
1415         file_open,
1416         file_ctrl,
1417         file_expect,
1418         file_find,
1419         file_load,
1420         file_eof,
1421         file_error,
1422         file_close
1423     };
1424
1425 static void store_file_loader_deinit(void)
1426 {
1427     ossl_store_unregister_loader_int(file_loader.scheme);
1428 }
1429
1430 int ossl_store_file_loader_init(void)
1431 {
1432     int ret = ossl_store_register_loader_int(&file_loader);
1433
1434     OPENSSL_atexit(store_file_loader_deinit);
1435     return ret;
1436 }