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