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