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