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