02178b29a8dec80e632d3728d72cc195a7415e68
[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     unsigned int flags;
722     union {
723         struct {                 /* Used with is_raw and is_pem */
724             BIO *file;
725
726             /*
727              * The following are used when the handler is marked as
728              * repeatable
729              */
730             const FILE_HANDLER *last_handler;
731             void *last_handler_ctx;
732         } file;
733         struct {                 /* Used with is_dir */
734             OPENSSL_DIR_CTX *ctx;
735             int end_reached;
736             char *uri;
737
738             /*
739              * When a search expression is given, these are filled in.
740              * |search_name| contains the file basename to look for.
741              * The string is exactly 8 characters long.
742              */
743             char search_name[9];
744
745             /*
746              * The directory reading utility we have combines opening with
747              * reading the first name.  To make sure we can detect the end
748              * at the right time, we read early and cache the name.
749              */
750             const char *last_entry;
751             int last_errno;
752         } dir;
753     } _;
754
755     /* Expected object type.  May be unspecified */
756     int expected_type;
757
758     OPENSSL_CTX *libctx;
759     char *propq;
760 };
761
762 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
763 {
764     if (ctx->type == is_dir) {
765         OPENSSL_free(ctx->_.dir.uri);
766     } else {
767         if (ctx->_.file.last_handler != NULL) {
768             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
769             ctx->_.file.last_handler_ctx = NULL;
770             ctx->_.file.last_handler = NULL;
771         }
772     }
773     OPENSSL_free(ctx->propq);
774     OPENSSL_free(ctx);
775 }
776
777 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
778                                         const char *uri,
779                                         const UI_METHOD *ui_method,
780                                         void *ui_data)
781 {
782     OSSL_STORE_LOADER_CTX *ctx = NULL;
783     struct stat st;
784     struct {
785         const char *path;
786         unsigned int check_absolute:1;
787     } path_data[2];
788     size_t path_data_n = 0, i;
789     const char *path;
790
791     /*
792      * First step, just take the URI as is.
793      */
794     path_data[path_data_n].check_absolute = 0;
795     path_data[path_data_n++].path = uri;
796
797     /*
798      * Second step, if the URI appears to start with the 'file' scheme,
799      * extract the path and make that the second path to check.
800      * There's a special case if the URI also contains an authority, then
801      * the full URI shouldn't be used as a path anywhere.
802      */
803     if (strncasecmp(uri, "file:", 5) == 0) {
804         const char *p = &uri[5];
805
806         if (strncmp(&uri[5], "//", 2) == 0) {
807             path_data_n--;           /* Invalidate using the full URI */
808             if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
809                 p = &uri[16];
810             } else if (uri[7] == '/') {
811                 p = &uri[7];
812             } else {
813                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
814                               OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED);
815                 return NULL;
816             }
817         }
818
819         path_data[path_data_n].check_absolute = 1;
820 #ifdef _WIN32
821         /* Windows file: URIs with a drive letter start with a / */
822         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
823             char c = ossl_tolower(p[1]);
824
825             if (c >= 'a' && c <= 'z') {
826                 p++;
827                 /* We know it's absolute, so no need to check */
828                 path_data[path_data_n].check_absolute = 0;
829             }
830         }
831 #endif
832         path_data[path_data_n++].path = p;
833     }
834
835
836     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
837         /*
838          * If the scheme "file" was an explicit part of the URI, the path must
839          * be absolute.  So says RFC 8089
840          */
841         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
842             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
843                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
844             ERR_add_error_data(1, path_data[i].path);
845             return NULL;
846         }
847
848         if (stat(path_data[i].path, &st) < 0) {
849             ERR_raise_data(ERR_LIB_SYS, errno,
850                            "calling stat(%s)",
851                            path_data[i].path);
852         } else {
853             path = path_data[i].path;
854         }
855     }
856     if (path == NULL) {
857         return NULL;
858     }
859
860     /* Successfully found a working path, clear possible collected errors */
861     ERR_clear_error();
862
863     ctx = OPENSSL_zalloc(sizeof(*ctx));
864     if (ctx == NULL) {
865         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
866         return NULL;
867     }
868
869     if (S_ISDIR(st.st_mode)) {
870         /*
871          * Try to copy everything, even if we know that some of them must be
872          * NULL for the moment.  This prevents errors in the future, when more
873          * components may be used.
874          */
875         ctx->_.dir.uri = OPENSSL_strdup(uri);
876         ctx->type = is_dir;
877
878         if (ctx->_.dir.uri == NULL)
879             goto err;
880
881         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
882         ctx->_.dir.last_errno = errno;
883         if (ctx->_.dir.last_entry == NULL) {
884             if (ctx->_.dir.last_errno != 0) {
885                 char errbuf[256];
886                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
887                 errno = ctx->_.dir.last_errno;
888                 if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
889                     ERR_add_error_data(1, errbuf);
890                 goto err;
891             }
892             ctx->_.dir.end_reached = 1;
893         }
894     } else {
895         BIO *buff = NULL;
896         char peekbuf[4096] = { 0, };
897
898         if ((buff = BIO_new(BIO_f_buffer())) == NULL
899             || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
900             BIO_free_all(buff);
901             goto err;
902         }
903
904         ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
905         if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
906             peekbuf[sizeof(peekbuf) - 1] = '\0';
907             if (strstr(peekbuf, "-----BEGIN ") != NULL)
908                 ctx->type = is_pem;
909         }
910     }
911
912     return ctx;
913  err:
914     OSSL_STORE_LOADER_CTX_free(ctx);
915     return NULL;
916 }
917
918 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
919 {
920     int ret = 1;
921
922     switch (cmd) {
923     case OSSL_STORE_C_USE_SECMEM:
924         {
925             int on = *(va_arg(args, int *));
926
927             switch (on) {
928             case 0:
929                 ctx->flags &= ~FILE_FLAG_SECMEM;
930                 break;
931             case 1:
932                 ctx->flags |= FILE_FLAG_SECMEM;
933                 break;
934             default:
935                 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
936                               ERR_R_PASSED_INVALID_ARGUMENT);
937                 ret = 0;
938                 break;
939             }
940         }
941         break;
942     default:
943         break;
944     }
945
946     return ret;
947 }
948
949 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
950 {
951     ctx->expected_type = expected;
952     return 1;
953 }
954
955 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
956                      const OSSL_STORE_SEARCH *search)
957 {
958     /*
959      * If ctx == NULL, the library is looking to know if this loader supports
960      * the given search type.
961      */
962
963     if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
964         unsigned long hash = 0;
965
966         if (ctx == NULL)
967             return 1;
968
969         if (ctx->type != is_dir) {
970             OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
971                           OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
972             return 0;
973         }
974
975         hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
976         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
977                      "%08lx", hash);
978         return 1;
979     }
980
981     if (ctx != NULL)
982         OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
983                       OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE);
984     return 0;
985 }
986
987 /* Internal function to decode an already opened PEM file */
988 OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp,
989                                                           OPENSSL_CTX *libctx,
990                                                           const char *propq)
991 {
992     OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
993
994     if (ctx == NULL) {
995         OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
996                       ERR_R_MALLOC_FAILURE);
997         return NULL;
998     }
999
1000     ctx->_.file.file = bp;
1001     ctx->type = is_pem;
1002
1003     ctx->libctx = libctx;
1004     if (propq != NULL) {
1005         ctx->propq = OPENSSL_strdup(propq);
1006         if (ctx->propq == NULL) {
1007             OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
1008                           ERR_R_MALLOC_FAILURE);
1009             OPENSSL_free(ctx);
1010             return NULL;
1011         }
1012     }
1013
1014     return ctx;
1015 }
1016
1017 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1018                                              const char *pem_name,
1019                                              const char *pem_header,
1020                                              unsigned char *data, size_t len,
1021                                              const UI_METHOD *ui_method,
1022                                              void *ui_data, int *matchcount)
1023 {
1024     OSSL_STORE_INFO *result = NULL;
1025     BUF_MEM *new_mem = NULL;
1026     char *new_pem_name = NULL;
1027     int t = 0;
1028
1029  again:
1030     {
1031         size_t i = 0;
1032         void *handler_ctx = NULL;
1033         const FILE_HANDLER **matching_handlers =
1034             OPENSSL_zalloc(sizeof(*matching_handlers)
1035                            * OSSL_NELEM(file_handlers));
1036
1037         if (matching_handlers == NULL) {
1038             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
1039                           ERR_R_MALLOC_FAILURE);
1040             goto err;
1041         }
1042
1043         *matchcount = 0;
1044         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1045             const FILE_HANDLER *handler = file_handlers[i];
1046             int try_matchcount = 0;
1047             void *tmp_handler_ctx = NULL;
1048             OSSL_STORE_INFO *tmp_result =
1049                 handler->try_decode(pem_name, pem_header, data, len,
1050                                     &tmp_handler_ctx, &try_matchcount,
1051                                     ui_method, ui_data, ctx->libctx, ctx->propq);
1052
1053             if (try_matchcount > 0) {
1054
1055                 matching_handlers[*matchcount] = handler;
1056
1057                 if (handler_ctx)
1058                     handler->destroy_ctx(&handler_ctx);
1059                 handler_ctx = tmp_handler_ctx;
1060
1061                 if ((*matchcount += try_matchcount) > 1) {
1062                     /* more than one match => ambiguous, kill any result */
1063                     OSSL_STORE_INFO_free(result);
1064                     OSSL_STORE_INFO_free(tmp_result);
1065                     if (handler->destroy_ctx != NULL)
1066                         handler->destroy_ctx(&handler_ctx);
1067                     handler_ctx = NULL;
1068                     tmp_result = NULL;
1069                     result = NULL;
1070                 }
1071                 if (result == NULL)
1072                     result = tmp_result;
1073             }
1074         }
1075
1076         if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1077             ctx->_.file.last_handler = matching_handlers[0];
1078             ctx->_.file.last_handler_ctx = handler_ctx;
1079         }
1080
1081         OPENSSL_free(matching_handlers);
1082     }
1083
1084  err:
1085     OPENSSL_free(new_pem_name);
1086     BUF_MEM_free(new_mem);
1087
1088     if (result != NULL
1089         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
1090         pem_name = new_pem_name =
1091             ossl_store_info_get0_EMBEDDED_pem_name(result);
1092         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
1093         data = (unsigned char *)new_mem->data;
1094         len = new_mem->length;
1095         OPENSSL_free(result);
1096         result = NULL;
1097         goto again;
1098     }
1099
1100     if (result != NULL)
1101         ERR_clear_error();
1102
1103     return result;
1104 }
1105
1106 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1107                                              const UI_METHOD *ui_method,
1108                                              void *ui_data)
1109 {
1110     OSSL_STORE_INFO *result = NULL;
1111     int try_matchcount = 0;
1112
1113     if (ctx->_.file.last_handler != NULL) {
1114         result =
1115             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1116                                                  &ctx->_.file.last_handler_ctx,
1117                                                  &try_matchcount,
1118                                                  ui_method, ui_data,
1119                                                  ctx->libctx, ctx->propq);
1120
1121         if (result == NULL) {
1122             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1123             ctx->_.file.last_handler_ctx = NULL;
1124             ctx->_.file.last_handler = NULL;
1125         }
1126     }
1127     return result;
1128 }
1129
1130 static void pem_free_flag(void *pem_data, int secure, size_t num)
1131 {
1132     if (secure)
1133         OPENSSL_secure_clear_free(pem_data, num);
1134     else
1135         OPENSSL_free(pem_data);
1136 }
1137 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1138                          unsigned char **data, long *len,
1139                          const UI_METHOD *ui_method,
1140                          void *ui_data, int secure)
1141 {
1142     int i = secure
1143         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1144                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1145         : PEM_read_bio(bp, pem_name, pem_header, data, len);
1146
1147     if (i <= 0)
1148         return 0;
1149
1150     /*
1151      * 10 is the number of characters in "Proc-Type:", which
1152      * PEM_get_EVP_CIPHER_INFO() requires to be present.
1153      * If the PEM header has less characters than that, it's
1154      * not worth spending cycles on it.
1155      */
1156     if (strlen(*pem_header) > 10) {
1157         EVP_CIPHER_INFO cipher;
1158         struct pem_pass_data pass_data;
1159
1160         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1161             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
1162             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1163                               &pass_data)) {
1164             return 0;
1165         }
1166     }
1167     return 1;
1168 }
1169
1170 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1171 {
1172     BUF_MEM *mem = NULL;
1173
1174     if (asn1_d2i_read_bio(bp, &mem) < 0)
1175         return 0;
1176
1177     *data = (unsigned char *)mem->data;
1178     *len = (long)mem->length;
1179     OPENSSL_free(mem);
1180
1181     return 1;
1182 }
1183
1184 static int ends_with_dirsep(const char *uri)
1185 {
1186     if (*uri != '\0')
1187         uri += strlen(uri) - 1;
1188 #if defined __VMS
1189     if (*uri == ']' || *uri == '>' || *uri == ':')
1190         return 1;
1191 #elif defined _WIN32
1192     if (*uri == '\\')
1193         return 1;
1194 #endif
1195     return *uri == '/';
1196 }
1197
1198 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1199                             char **data)
1200 {
1201     assert(name != NULL);
1202     assert(data != NULL);
1203     {
1204         const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
1205         long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
1206             + strlen(name) + 1 /* \0 */;
1207
1208         *data = OPENSSL_zalloc(calculated_length);
1209         if (*data == NULL) {
1210             OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1211             return 0;
1212         }
1213
1214         OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1215         OPENSSL_strlcat(*data, pathsep, calculated_length);
1216         OPENSSL_strlcat(*data, name, calculated_length);
1217     }
1218     return 1;
1219 }
1220
1221 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1222 {
1223     const char *p = NULL;
1224
1225     /* If there are no search criteria, all names are accepted */
1226     if (ctx->_.dir.search_name[0] == '\0')
1227         return 1;
1228
1229     /* If the expected type isn't supported, no name is accepted */
1230     if (ctx->expected_type != 0
1231         && ctx->expected_type != OSSL_STORE_INFO_CERT
1232         && ctx->expected_type != OSSL_STORE_INFO_CRL)
1233         return 0;
1234
1235     /*
1236      * First, check the basename
1237      */
1238     if (strncasecmp(name, ctx->_.dir.search_name,
1239                     sizeof(ctx->_.dir.search_name) - 1) != 0
1240         || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1241         return 0;
1242     p = &name[sizeof(ctx->_.dir.search_name)];
1243
1244     /*
1245      * Then, if the expected type is a CRL, check that the extension starts
1246      * with 'r'
1247      */
1248     if (*p == 'r') {
1249         p++;
1250         if (ctx->expected_type != 0
1251             && ctx->expected_type != OSSL_STORE_INFO_CRL)
1252             return 0;
1253     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1254         return 0;
1255     }
1256
1257     /*
1258      * Last, check that the rest of the extension is a decimal number, at
1259      * least one digit long.
1260      */
1261     if (!ossl_isdigit(*p))
1262         return 0;
1263     while (ossl_isdigit(*p))
1264         p++;
1265
1266 # ifdef __VMS
1267     /*
1268      * One extra step here, check for a possible generation number.
1269      */
1270     if (*p == ';')
1271         for (p++; *p != '\0'; p++)
1272             if (!ossl_isdigit(*p))
1273                 break;
1274 # endif
1275
1276     /*
1277      * If we've reached the end of the string at this point, we've successfully
1278      * found a fitting file name.
1279      */
1280     return *p == '\0';
1281 }
1282
1283 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1284 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1285 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1286                                   const UI_METHOD *ui_method, void *ui_data)
1287 {
1288     OSSL_STORE_INFO *result = NULL;
1289
1290     ctx->errcnt = 0;
1291     ERR_clear_error();
1292
1293     if (ctx->type == is_dir) {
1294         do {
1295             char *newname = NULL;
1296
1297             if (ctx->_.dir.last_entry == NULL) {
1298                 if (!ctx->_.dir.end_reached) {
1299                     char errbuf[256];
1300                     assert(ctx->_.dir.last_errno != 0);
1301                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1302                     errno = ctx->_.dir.last_errno;
1303                     ctx->errcnt++;
1304                     if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
1305                         ERR_add_error_data(1, errbuf);
1306                 }
1307                 return NULL;
1308             }
1309
1310             if (ctx->_.dir.last_entry[0] != '.'
1311                 && file_name_check(ctx, ctx->_.dir.last_entry)
1312                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1313                 return NULL;
1314
1315             /*
1316              * On the first call (with a NULL context), OPENSSL_DIR_read()
1317              * cares about the second argument.  On the following calls, it
1318              * only cares that it isn't NULL.  Therefore, we can safely give
1319              * it our URI here.
1320              */
1321             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1322                                                      ctx->_.dir.uri);
1323             ctx->_.dir.last_errno = errno;
1324             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1325                 ctx->_.dir.end_reached = 1;
1326
1327             if (newname != NULL
1328                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1329                 OPENSSL_free(newname);
1330                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1331                 return NULL;
1332             }
1333         } while (result == NULL && !file_eof(ctx));
1334     } else {
1335         int matchcount = -1;
1336
1337      again:
1338         result = file_load_try_repeat(ctx, ui_method, ui_data);
1339         if (result != NULL)
1340             return result;
1341
1342         if (file_eof(ctx))
1343             return NULL;
1344
1345         do {
1346             char *pem_name = NULL;      /* PEM record name */
1347             char *pem_header = NULL;    /* PEM record header */
1348             unsigned char *data = NULL; /* DER encoded data */
1349             long len = 0;               /* DER encoded data length */
1350
1351             matchcount = -1;
1352             if (ctx->type == is_pem) {
1353                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1354                                    &data, &len, ui_method, ui_data,
1355                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1356                     ctx->errcnt++;
1357                     goto endloop;
1358                 }
1359             } else {
1360                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1361                     ctx->errcnt++;
1362                     goto endloop;
1363                 }
1364             }
1365
1366             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1367                                           ui_method, ui_data, &matchcount);
1368
1369             if (result != NULL)
1370                 goto endloop;
1371
1372             /*
1373              * If a PEM name matches more than one handler, the handlers are
1374              * badly coded.
1375              */
1376             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1377                 ctx->errcnt++;
1378                 goto endloop;
1379             }
1380
1381             if (matchcount > 1) {
1382                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1383                               OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1384             } else if (matchcount == 1) {
1385                 /*
1386                  * If there are other errors on the stack, they already show
1387                  * what the problem is.
1388                  */
1389                 if (ERR_peek_error() == 0) {
1390                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1391                                   OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1392                     if (pem_name != NULL)
1393                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1394                 }
1395             }
1396             if (matchcount > 0)
1397                 ctx->errcnt++;
1398
1399          endloop:
1400             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1401             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1402             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1403         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1404
1405         /* We bail out on ambiguity */
1406         if (matchcount > 1)
1407             return NULL;
1408
1409         if (result != NULL
1410             && ctx->expected_type != 0
1411             && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1412             OSSL_STORE_INFO_free(result);
1413             goto again;
1414         }
1415     }
1416
1417     return result;
1418 }
1419
1420 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1421 {
1422     return ctx->errcnt > 0;
1423 }
1424
1425 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1426 {
1427     if (ctx->type == is_dir)
1428         return ctx->_.dir.end_reached;
1429
1430     if (ctx->_.file.last_handler != NULL
1431         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1432         return 0;
1433     return BIO_eof(ctx->_.file.file);
1434 }
1435
1436 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1437 {
1438     if (ctx->type == is_dir) {
1439         OPENSSL_DIR_end(&ctx->_.dir.ctx);
1440     } else {
1441         BIO_free_all(ctx->_.file.file);
1442     }
1443     OSSL_STORE_LOADER_CTX_free(ctx);
1444     return 1;
1445 }
1446
1447 int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx)
1448 {
1449     OSSL_STORE_LOADER_CTX_free(ctx);
1450     return 1;
1451 }
1452
1453 static OSSL_STORE_LOADER file_loader =
1454     {
1455         "file",
1456         NULL,
1457         file_open,
1458         file_ctrl,
1459         file_expect,
1460         file_find,
1461         file_load,
1462         file_eof,
1463         file_error,
1464         file_close
1465     };
1466
1467 static void store_file_loader_deinit(void)
1468 {
1469     ossl_store_unregister_loader_int(file_loader.scheme);
1470 }
1471
1472 int ossl_store_file_loader_init(void)
1473 {
1474     int ret = ossl_store_register_loader_int(&file_loader);
1475
1476     OPENSSL_atexit(store_file_loader_deinit);
1477     return ret;
1478 }