Make it possible to tell the file loader to use secure memory
[openssl.git] / crypto / store / loader_file.c
1 /*
2  * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <string.h>
11 #include <sys/stat.h>
12 #include <assert.h>
13
14 #include <openssl/bio.h>
15 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
19 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
20 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
21 #include <openssl/safestack.h>
22 #include <openssl/store.h>
23 #include <openssl/ui.h>
24 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
25 #include "internal/asn1_int.h"
26 #include "internal/o_dir.h"
27 #include "internal/cryptlib.h"
28 #include "store_locl.h"
29
30 #include "e_os.h"
31
32 /*
33  *  Password prompting
34  */
35
36 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
37                            size_t maxsize, const char *prompt_info, void *data)
38 {
39     UI *ui = UI_new();
40     char *prompt = NULL;
41
42     if (ui == NULL) {
43         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
44         return NULL;
45     }
46
47     if (ui_method != NULL)
48         UI_set_method(ui, ui_method);
49     UI_add_user_data(ui, data);
50
51     if ((prompt = UI_construct_prompt(ui, "pass phrase",
52                                       prompt_info)) == NULL) {
53         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
54         pass = NULL;
55     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
56                                     pass, 0, maxsize - 1)) {
57         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
58         pass = NULL;
59     } else {
60         switch (UI_process(ui)) {
61         case -2:
62             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
63                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
64             pass = NULL;
65             break;
66         case -1:
67             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
68             pass = NULL;
69             break;
70         default:
71             break;
72         }
73     }
74
75     OPENSSL_free(prompt);
76     UI_free(ui);
77     return pass;
78 }
79
80 struct pem_pass_data {
81     const UI_METHOD *ui_method;
82     void *data;
83     const char *prompt_info;
84 };
85 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
86                                    const char *prompt_info,
87                                    const UI_METHOD *ui_method, void *ui_data)
88 {
89     if (pass_data == NULL)
90         return 0;
91     pass_data->ui_method = ui_method;
92     pass_data->data = ui_data;
93     pass_data->prompt_info = prompt_info;
94     return 1;
95 }
96 static int file_get_pem_pass(char *buf, int num, int w, void *data)
97 {
98     struct pem_pass_data *pass_data = data;
99     char *pass = file_get_pass(pass_data->ui_method, buf, num,
100                                pass_data->prompt_info, pass_data->data);
101
102     return pass == NULL ? 0 : strlen(pass);
103 }
104
105 /*
106  *  The file scheme handlers
107  */
108
109 /*-
110  * The try_decode function is called to check if the blob of data can
111  * be used by this handler, and if it can, decodes it into a supported
112  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
113  * Input:
114  *    pem_name:     If this blob comes from a PEM file, this holds
115  *                  the PEM name.  If it comes from another type of
116  *                  file, this is NULL.
117  *    pem_header:   If this blob comes from a PEM file, this holds
118  *                  the PEM headers.  If it comes from another type of
119  *                  file, this is NULL.
120  *    blob:         The blob of data to match with what this handler
121  *                  can use.
122  *    len:          The length of the blob.
123  *    handler_ctx:  For a handler marked repeatable, this pointer can
124  *                  be used to create a context for the handler.  IT IS
125  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
126  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
127  *                  and destroy when about to return NULL.
128  *    matchcount:   A pointer to an int to count matches for this data.
129  *                  Usually becomes 0 (no match) or 1 (match!), but may
130  *                  be higher in the (unlikely) event that the data matches
131  *                  more than one possibility.  The int will always be
132  *                  zero when the function is called.
133  *    ui_method:    Application UI method for getting a password, pin
134  *                  or any other interactive data.
135  *    ui_data:      Application data to be passed to ui_method when
136  *                  it's called.
137  * Output:
138  *    a OSSL_STORE_INFO
139  */
140 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
141                                                const char *pem_header,
142                                                const unsigned char *blob,
143                                                size_t len, void **handler_ctx,
144                                                int *matchcount,
145                                                const UI_METHOD *ui_method,
146                                                void *ui_data);
147 /*
148  * The eof function should return 1 if there's no more data to be found
149  * with the handler_ctx, otherwise 0.  This is only used when the handler is
150  * marked repeatable.
151  */
152 typedef int (*file_eof_fn)(void *handler_ctx);
153 /*
154  * The destroy_ctx function is used to destroy the handler_ctx that was
155  * intiated by a repeatable try_decode fuction.  This is only used when
156  * the handler is marked repeatable.
157  */
158 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
159
160 typedef struct file_handler_st {
161     const char *name;
162     file_try_decode_fn try_decode;
163     file_eof_fn eof;
164     file_destroy_ctx_fn destroy_ctx;
165
166     /* flags */
167     int repeatable;
168 } FILE_HANDLER;
169
170 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
171                                           const char *pem_header,
172                                           const unsigned char *blob,
173                                           size_t len, void **pctx,
174                                           int *matchcount,
175                                           const UI_METHOD *ui_method,
176                                           void *ui_data)
177 {
178     OSSL_STORE_INFO *store_info = NULL;
179     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
180
181     if (ctx == NULL) {
182         /* Initial parsing */
183         PKCS12 *p12;
184         int ok = 0;
185
186         if (pem_name != NULL)
187             /* No match, there is no PEM PKCS12 tag */
188             return NULL;
189
190         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
191             char *pass = NULL;
192             char tpass[PEM_BUFSIZE];
193             EVP_PKEY *pkey = NULL;
194             X509 *cert = NULL;
195             STACK_OF(X509) *chain = NULL;
196
197             *matchcount = 1;
198
199             if (PKCS12_verify_mac(p12, "", 0)
200                 || PKCS12_verify_mac(p12, NULL, 0)) {
201                 pass = "";
202             } else {
203                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
204                                           "PKCS12 import password",
205                                           ui_data)) == NULL) {
206                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
207                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
208                     goto p12_end;
209                 }
210                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
211                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
212                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
213                     goto p12_end;
214                 }
215             }
216
217             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
218                 OSSL_STORE_INFO *si_pkey = NULL;
219                 OSSL_STORE_INFO *si_cert = NULL;
220                 OSSL_STORE_INFO *si_ca = NULL;
221
222                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
223                     && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
224                     && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0
225                     && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
226                     && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) {
227                     ok = 1;
228                     si_pkey = NULL;
229                     si_cert = NULL;
230
231                     while(sk_X509_num(chain) > 0) {
232                         X509 *ca = sk_X509_value(chain, 0);
233
234                         if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
235                             || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) {
236                             ok = 0;
237                             break;
238                         }
239                         si_ca = NULL;
240                         (void)sk_X509_shift(chain);
241                     }
242                 }
243                 if (!ok) {
244                     OSSL_STORE_INFO_free(si_ca);
245                     OSSL_STORE_INFO_free(si_cert);
246                     OSSL_STORE_INFO_free(si_pkey);
247                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
248                     EVP_PKEY_free(pkey);
249                     X509_free(cert);
250                     sk_X509_pop_free(chain, X509_free);
251                     ctx = NULL;
252                 }
253                 *pctx = ctx;
254             }
255         }
256      p12_end:
257         PKCS12_free(p12);
258         if (!ok)
259             return NULL;
260     }
261
262     if (ctx != NULL) {
263         *matchcount = 1;
264         store_info = sk_OSSL_STORE_INFO_shift(ctx);
265     }
266
267     return store_info;
268 }
269 static int eof_PKCS12(void *ctx_)
270 {
271     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
272
273     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
274 }
275 static void destroy_ctx_PKCS12(void **pctx)
276 {
277     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
278
279     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
280     *pctx = NULL;
281 }
282 static FILE_HANDLER PKCS12_handler = {
283     "PKCS12",
284     try_decode_PKCS12,
285     eof_PKCS12,
286     destroy_ctx_PKCS12,
287     1                            /* repeatable */
288 };
289
290 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
291                                                   const char *pem_header,
292                                                   const unsigned char *blob,
293                                                   size_t len, void **pctx,
294                                                   int *matchcount,
295                                                   const UI_METHOD *ui_method,
296                                                   void *ui_data)
297 {
298     X509_SIG *p8 = NULL;
299     char kbuf[PEM_BUFSIZE];
300     char *pass = NULL;
301     const X509_ALGOR *dalg = NULL;
302     const ASN1_OCTET_STRING *doct = NULL;
303     OSSL_STORE_INFO *store_info = NULL;
304     BUF_MEM *mem = NULL;
305     unsigned char *new_data = NULL;
306     int new_data_len;
307
308     if (pem_name != NULL) {
309         if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
310             return NULL;
311         *matchcount = 1;
312     }
313
314     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
315         return NULL;
316
317     *matchcount = 1;
318
319     if ((mem = BUF_MEM_new()) == NULL) {
320         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
321                       ERR_R_MALLOC_FAILURE);
322         goto nop8;
323     }
324
325     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
326                               "PKCS8 decrypt password", ui_data)) == NULL) {
327         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
328                       OSSL_STORE_R_BAD_PASSWORD_READ);
329         goto nop8;
330     }
331
332     X509_SIG_get0(p8, &dalg, &doct);
333     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
334                           &new_data, &new_data_len, 0))
335         goto nop8;
336
337     mem->data = (char *)new_data;
338     mem->max = mem->length = (size_t)new_data_len;
339     X509_SIG_free(p8);
340
341     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
342     if (store_info == NULL) {
343         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
344                       ERR_R_MALLOC_FAILURE);
345         goto nop8;
346     }
347
348     return store_info;
349  nop8:
350     X509_SIG_free(p8);
351     BUF_MEM_free(mem);
352     return NULL;
353 }
354 static FILE_HANDLER PKCS8Encrypted_handler = {
355     "PKCS8Encrypted",
356     try_decode_PKCS8Encrypted
357 };
358
359 int pem_check_suffix(const char *pem_str, const char *suffix);
360 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
361                                               const char *pem_header,
362                                               const unsigned char *blob,
363                                               size_t len, void **pctx,
364                                               int *matchcount,
365                                               const UI_METHOD *ui_method,
366                                               void *ui_data)
367 {
368     OSSL_STORE_INFO *store_info = NULL;
369     EVP_PKEY *pkey = NULL;
370     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
371
372     if (pem_name != NULL) {
373         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
374             PKCS8_PRIV_KEY_INFO *p8inf =
375                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
376
377             *matchcount = 1;
378             if (p8inf != NULL)
379                 pkey = EVP_PKCS82PKEY(p8inf);
380             PKCS8_PRIV_KEY_INFO_free(p8inf);
381         } else {
382             int slen;
383
384             if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
385                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
386                                                    slen)) != NULL) {
387                 *matchcount = 1;
388                 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
389             }
390         }
391     } else {
392         int i;
393
394         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
395             EVP_PKEY *tmp_pkey = NULL;
396             const unsigned char *tmp_blob = blob;
397
398             ameth = EVP_PKEY_asn1_get0(i);
399             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
400                 continue;
401
402             tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len);
403             if (tmp_pkey != NULL) {
404                 if (pkey != NULL)
405                     EVP_PKEY_free(tmp_pkey);
406                 else
407                     pkey = tmp_pkey;
408                 (*matchcount)++;
409             }
410         }
411
412         if (*matchcount > 1) {
413             EVP_PKEY_free(pkey);
414             pkey = NULL;
415         }
416     }
417     if (pkey == NULL)
418         /* No match */
419         return NULL;
420
421     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
422     if (store_info == NULL)
423         EVP_PKEY_free(pkey);
424
425     return store_info;
426 }
427 static FILE_HANDLER PrivateKey_handler = {
428     "PrivateKey",
429     try_decode_PrivateKey
430 };
431
432 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
433                                           const char *pem_header,
434                                           const unsigned char *blob,
435                                           size_t len, void **pctx,
436                                           int *matchcount,
437                                           const UI_METHOD *ui_method,
438                                           void *ui_data)
439 {
440     OSSL_STORE_INFO *store_info = NULL;
441     EVP_PKEY *pkey = NULL;
442
443     if (pem_name != NULL) {
444         if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
445             /* No match */
446             return NULL;
447         *matchcount = 1;
448     }
449
450     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
451         *matchcount = 1;
452         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
453     }
454
455     return store_info;
456 }
457 static FILE_HANDLER PUBKEY_handler = {
458     "PUBKEY",
459     try_decode_PUBKEY
460 };
461
462 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
463                                           const char *pem_header,
464                                           const unsigned char *blob,
465                                           size_t len, void **pctx,
466                                           int *matchcount,
467                                           const UI_METHOD *ui_method,
468                                           void *ui_data)
469 {
470     OSSL_STORE_INFO *store_info = NULL;
471     int slen = 0;
472     EVP_PKEY *pkey = NULL;
473     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
474     int ok = 0;
475
476     if (pem_name != NULL) {
477         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
478             return NULL;
479         *matchcount = 1;
480     }
481
482     if ((pkey = EVP_PKEY_new()) == NULL) {
483         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
484         return NULL;
485     }
486
487     if (slen > 0) {
488         if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
489             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
490             && ameth->param_decode != NULL
491             && ameth->param_decode(pkey, &blob, len))
492             ok = 1;
493     } else {
494         int i;
495
496         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
497             const unsigned char *tmp_blob = blob;
498
499             ameth = EVP_PKEY_asn1_get0(i);
500             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
501                 continue;
502             if (EVP_PKEY_set_type(pkey, ameth->pkey_id)
503                 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
504                 && ameth->param_decode != NULL
505                 && ameth->param_decode(pkey, &tmp_blob, len)) {
506                 (*matchcount)++;
507                 ok = 1;
508                 break;
509             }
510         }
511     }
512
513     if (ok)
514         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
515     if (store_info == NULL)
516         EVP_PKEY_free(pkey);
517
518     return store_info;
519 }
520 static FILE_HANDLER params_handler = {
521     "params",
522     try_decode_params
523 };
524
525 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
526                                                    const char *pem_header,
527                                                    const unsigned char *blob,
528                                                    size_t len, void **pctx,
529                                                    int *matchcount,
530                                                    const UI_METHOD *ui_method,
531                                                    void *ui_data)
532 {
533     OSSL_STORE_INFO *store_info = NULL;
534     X509 *cert = NULL;
535
536     /*
537      * In most cases, we can try to interpret the serialized data as a trusted
538      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
539      * (just X509), but if the PEM name specifically declares it as a trusted
540      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
541      * the fallback can be used (1) or not (0).
542      */
543     int ignore_trusted = 1;
544
545     if (pem_name != NULL) {
546         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
547             ignore_trusted = 0;
548         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
549                  && strcmp(pem_name, PEM_STRING_X509) != 0)
550             /* No match */
551             return NULL;
552         *matchcount = 1;
553     }
554
555     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
556         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
557         *matchcount = 1;
558         store_info = OSSL_STORE_INFO_new_CERT(cert);
559     }
560
561     if (store_info == NULL)
562         X509_free(cert);
563
564     return store_info;
565 }
566 static FILE_HANDLER X509Certificate_handler = {
567     "X509Certificate",
568     try_decode_X509Certificate
569 };
570
571 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
572                                            const char *pem_header,
573                                            const unsigned char *blob,
574                                            size_t len, void **pctx,
575                                            int *matchcount,
576                                            const UI_METHOD *ui_method,
577                                            void *ui_data)
578 {
579     OSSL_STORE_INFO *store_info = NULL;
580     X509_CRL *crl = NULL;
581
582     if (pem_name != NULL) {
583         if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
584             /* No match */
585             return NULL;
586         *matchcount = 1;
587     }
588
589     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
590         *matchcount = 1;
591         store_info = OSSL_STORE_INFO_new_CRL(crl);
592     }
593
594     if (store_info == NULL)
595         X509_CRL_free(crl);
596
597     return store_info;
598 }
599 static FILE_HANDLER X509CRL_handler = {
600     "X509CRL",
601     try_decode_X509CRL
602 };
603
604 static const FILE_HANDLER *file_handlers[] = {
605     &PKCS12_handler,
606     &PKCS8Encrypted_handler,
607     &X509Certificate_handler,
608     &X509CRL_handler,
609     &params_handler,
610     &PUBKEY_handler,
611     &PrivateKey_handler,
612 };
613
614
615 /*
616  *  The loader itself
617  */
618
619 struct ossl_store_loader_ctx_st {
620     enum {
621         is_raw = 0,
622         is_pem,
623         is_dir
624     } type;
625     int errcnt;
626 #define FILE_FLAG_SECMEM         (1<<0)
627     unsigned int flags;
628     union {
629         struct {                 /* Used with is_raw and is_pem */
630             BIO *file;
631
632             /*
633              * The following are used when the handler is marked as
634              * repeatable
635              */
636             const FILE_HANDLER *last_handler;
637             void *last_handler_ctx;
638         } file;
639         struct {                 /* Used with is_dir */
640             OPENSSL_DIR_CTX *ctx;
641             int end_reached;
642             char *uri;
643
644             /*
645              * The directory reading utility we have combines opening with
646              * reading the first name.  To make sure we can detect the end
647              * at the right time, we read early and cache the name.
648              */
649             const char *last_entry;
650             int last_errno;
651         } dir;
652     } _;
653 };
654
655 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
656 {
657     if (ctx->type == is_dir) {
658         OPENSSL_free(ctx->_.dir.uri);
659     } else {
660         if (ctx->_.file.last_handler != NULL) {
661             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
662             ctx->_.file.last_handler_ctx = NULL;
663             ctx->_.file.last_handler = NULL;
664         }
665     }
666     OPENSSL_free(ctx);
667 }
668
669 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
670                                         const char *uri,
671                                         const UI_METHOD *ui_method,
672                                         void *ui_data)
673 {
674     OSSL_STORE_LOADER_CTX *ctx = NULL;
675     struct stat st;
676     const char *path = NULL;
677
678     if (strncasecmp(uri, "file:", 5) == 0) {
679         if (strncmp(&uri[5], "//localhost/", 12) == 0) {
680             path = &uri[16];
681         } else if (strncmp(&uri[5], "///", 3) == 0) {
682             path = &uri[7];
683         } else if (strncmp(&uri[5], "//", 2) != 0) {
684             path = &uri[5];
685         } else {
686             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
687                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
688             return NULL;
689         }
690
691         /*
692          * If the scheme "file" was an explicit part of the URI, the path must
693          * be absolute.  So says RFC 8089
694          */
695         if (path[0] != '/') {
696             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
697                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
698             return NULL;
699         }
700
701 #ifdef _WIN32
702         /* Windows file: URIs with a drive letter start with a / */
703         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
704             path++;
705 #endif
706     } else {
707         path = uri;
708     }
709
710
711     if (stat(path, &st) < 0) {
712         SYSerr(SYS_F_STAT, errno);
713         ERR_add_error_data(1, path);
714         return NULL;
715     }
716
717     ctx = OPENSSL_zalloc(sizeof(*ctx));
718     if (ctx == NULL) {
719         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
720         return NULL;
721     }
722
723     if ((st.st_mode & S_IFDIR) == S_IFDIR) {
724         /*
725          * Try to copy everything, even if we know that some of them must be
726          * NULL for the moment.  This prevents errors in the future, when more
727          * components may be used.
728          */
729         ctx->_.dir.uri = OPENSSL_strdup(uri);
730         ctx->type = is_dir;
731
732         if (ctx->_.dir.uri == NULL)
733             goto err;
734
735         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
736         ctx->_.dir.last_errno = errno;
737         if (ctx->_.dir.last_entry == NULL) {
738             if (ctx->_.dir.last_errno != 0) {
739                 char errbuf[256];
740                 errno = ctx->_.dir.last_errno;
741                 openssl_strerror_r(errno, errbuf, sizeof(errbuf));
742                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
743                 ERR_add_error_data(1, errbuf);
744                 goto err;
745             }
746             ctx->_.dir.end_reached = 1;
747         }
748     } else {
749         BIO *buff = NULL;
750         char peekbuf[4096];
751
752         if ((buff = BIO_new(BIO_f_buffer())) == NULL
753             || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
754             BIO_free_all(buff);
755             goto err;
756         }
757
758         ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
759         if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf)-1) > 0) {
760             peekbuf[sizeof(peekbuf)-1] = '\0';
761             if (strstr(peekbuf, "-----BEGIN ") != NULL)
762                 ctx->type = is_pem;
763         }
764     }
765
766     return ctx;
767  err:
768     OSSL_STORE_LOADER_CTX_free(ctx);
769     return NULL;
770 }
771
772 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
773 {
774     int ret = 1;
775
776     switch (cmd) {
777     case OSSL_STORE_C_USE_SECMEM:
778         {
779             int on = *(va_arg(args, int *));
780
781             switch (on) {
782             case 0:
783                 ctx->flags &= ~FILE_FLAG_SECMEM;
784                 break;
785             case 1:
786                 ctx->flags |= FILE_FLAG_SECMEM;
787                 break;
788             default:
789                 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
790                               ERR_R_PASSED_INVALID_ARGUMENT);
791                 ret = 0;
792                 break;
793             }
794         }
795         break;
796     default:
797         break;
798     }
799
800     return ret;
801 }
802
803 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
804                                              const char *pem_name,
805                                              const char *pem_header,
806                                              unsigned char *data, size_t len,
807                                              const UI_METHOD *ui_method,
808                                              void *ui_data, int *matchcount)
809 {
810     OSSL_STORE_INFO *result = NULL;
811     BUF_MEM *new_mem = NULL;
812     char *new_pem_name = NULL;
813     int t = 0;
814
815  again:
816     {
817         size_t i = 0;
818         void *handler_ctx = NULL;
819         const FILE_HANDLER **matching_handlers =
820             OPENSSL_zalloc(sizeof(*matching_handlers)
821                            * OSSL_NELEM(file_handlers));
822
823         if (matching_handlers == NULL) {
824             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
825                           ERR_R_MALLOC_FAILURE);
826             goto err;
827         }
828
829         *matchcount = 0;
830         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
831             const FILE_HANDLER *handler = file_handlers[i];
832             int try_matchcount = 0;
833             void *tmp_handler_ctx = NULL;
834             OSSL_STORE_INFO *tmp_result =
835                 handler->try_decode(pem_name, pem_header, data, len,
836                                     &tmp_handler_ctx, &try_matchcount,
837                                     ui_method, ui_data);
838
839             if (try_matchcount > 0) {
840                 if (matching_handlers)
841                     matching_handlers[*matchcount] = handler;
842
843                 if (handler_ctx)
844                     handler->destroy_ctx(&handler_ctx);
845                 handler_ctx = tmp_handler_ctx;
846
847                 if ((*matchcount += try_matchcount) > 1) {
848                     /* more than one match => ambiguous, kill any result */
849                     OSSL_STORE_INFO_free(result);
850                     OSSL_STORE_INFO_free(tmp_result);
851                     if (handler->destroy_ctx != NULL)
852                         handler->destroy_ctx(&handler_ctx);
853                     handler_ctx = NULL;
854                     tmp_result = NULL;
855                     result = NULL;
856                 }
857                 if (result == NULL)
858                     result = tmp_result;
859             }
860         }
861
862         if (*matchcount == 1 && matching_handlers[0]->repeatable) {
863             ctx->_.file.last_handler = matching_handlers[0];
864             ctx->_.file.last_handler_ctx = handler_ctx;
865         }
866
867         OPENSSL_free(matching_handlers);
868     }
869
870  err:
871     OPENSSL_free(new_pem_name);
872     BUF_MEM_free(new_mem);
873
874     if (result != NULL
875         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
876         pem_name = new_pem_name =
877             ossl_store_info_get0_EMBEDDED_pem_name(result);
878         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
879         data = (unsigned char *)new_mem->data;
880         len = new_mem->length;
881         OPENSSL_free(result);
882         result = NULL;
883         goto again;
884     }
885
886     if (result != NULL)
887         ERR_clear_error();
888
889     return result;
890 }
891
892 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
893                                              const UI_METHOD *ui_method,
894                                              void *ui_data)
895 {
896     OSSL_STORE_INFO *result = NULL;
897     int try_matchcount = 0;
898
899     if (ctx->_.file.last_handler != NULL) {
900         result =
901             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
902                                                  &ctx->_.file.last_handler_ctx,
903                                                  &try_matchcount,
904                                                  ui_method, ui_data);
905
906         if (result == NULL) {
907             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
908             ctx->_.file.last_handler_ctx = NULL;
909             ctx->_.file.last_handler = NULL;
910         }
911     }
912     return result;
913 }
914
915 static void pem_free_flag(void *pem_data, int secure)
916 {
917     if (secure)
918         OPENSSL_secure_free(pem_data);
919     else
920         OPENSSL_free(pem_data);
921 }
922 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
923                          unsigned char **data, long *len,
924                          const UI_METHOD *ui_method,
925                          void *ui_data, int secure)
926 {
927     int i = secure
928         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
929                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
930         : PEM_read_bio(bp, pem_name, pem_header, data, len);
931
932     if (i <= 0)
933         return 0;
934
935     /*
936      * 10 is the number of characters in "Proc-Type:", which
937      * PEM_get_EVP_CIPHER_INFO() requires to be present.
938      * If the PEM header has less characters than that, it's
939      * not worth spending cycles on it.
940      */
941     if (strlen(*pem_header) > 10) {
942         EVP_CIPHER_INFO cipher;
943         struct pem_pass_data pass_data;
944
945         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
946             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
947             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
948                               &pass_data)) {
949             return 0;
950         }
951     }
952     return 1;
953 }
954
955 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
956 {
957     BUF_MEM *mem = NULL;
958
959     if (asn1_d2i_read_bio(bp, &mem) < 0)
960         return 0;
961
962     *data = (unsigned char *)mem->data;
963     *len = (long)mem->length;
964     OPENSSL_free(mem);
965
966     return 1;
967 }
968
969 static int ends_with_dirsep(const char *uri)
970 {
971     if (*uri != '\0')
972         uri += strlen(uri) - 1;
973 #if defined __VMS
974     if (*uri == ']' || *uri == '>' || *uri == ':')
975         return 1;
976 #elif defined _WIN32
977     if (*uri == '\\')
978         return 1;
979 #endif
980     return *uri == '/';
981 }
982
983 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
984                             char **data)
985 {
986     assert(name != NULL);
987     assert(data != NULL);
988     {
989         const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
990         long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
991             + strlen(name) + 1 /* \0 */;
992
993         *data = OPENSSL_zalloc(calculated_length);
994         if (*data == NULL) {
995             OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
996             return 0;
997         }
998
999         OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1000         OPENSSL_strlcat(*data, pathsep, calculated_length);
1001         OPENSSL_strlcat(*data, name, calculated_length);
1002     }
1003     return 1;
1004 }
1005
1006 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1007 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1008 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1009                                   const UI_METHOD *ui_method, void *ui_data)
1010 {
1011     OSSL_STORE_INFO *result = NULL;
1012
1013     ctx->errcnt = 0;
1014     ERR_clear_error();
1015
1016     if (ctx->type == is_dir) {
1017         do {
1018             char *newname = NULL;
1019
1020             if (ctx->_.dir.last_entry == NULL) {
1021                 if (!ctx->_.dir.end_reached) {
1022                     char errbuf[256];
1023                     assert(ctx->_.dir.last_errno != 0);
1024                     errno = ctx->_.dir.last_errno;
1025                     ctx->errcnt++;
1026                     openssl_strerror_r(errno, errbuf, sizeof(errbuf));
1027                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1028                     ERR_add_error_data(1, errbuf);
1029                 }
1030                 return NULL;
1031             }
1032
1033             if (ctx->_.dir.last_entry[0] != '.'
1034                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1035                 return NULL;
1036
1037             /*
1038              * On the first call (with a NULL context), OPENSSL_DIR_read()
1039              * cares about the second argument.  On the following calls, it
1040              * only cares that it isn't NULL.  Therefore, we can safely give
1041              * it our URI here.
1042              */
1043             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1044                                                      ctx->_.dir.uri);
1045             ctx->_.dir.last_errno = errno;
1046             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1047                 ctx->_.dir.end_reached = 1;
1048
1049             if (newname != NULL
1050                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1051                 OPENSSL_free(newname);
1052                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1053                 return NULL;
1054             }
1055         } while (result == NULL && !file_eof(ctx));
1056     } else {
1057         int matchcount = -1;
1058
1059         result = file_load_try_repeat(ctx, ui_method, ui_data);
1060         if (result != NULL)
1061             return result;
1062
1063         if (file_eof(ctx))
1064             return NULL;
1065
1066         do {
1067             char *pem_name = NULL;      /* PEM record name */
1068             char *pem_header = NULL;    /* PEM record header */
1069             unsigned char *data = NULL; /* DER encoded data */
1070             long len = 0;               /* DER encoded data length */
1071
1072             matchcount = -1;
1073             if (ctx->type == is_pem) {
1074                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1075                                    &data, &len, ui_method, ui_data,
1076                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1077                     ctx->errcnt++;
1078                     goto endloop;
1079                 }
1080             } else {
1081                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1082                     ctx->errcnt++;
1083                     goto endloop;
1084                 }
1085             }
1086
1087             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1088                                           ui_method, ui_data, &matchcount);
1089
1090             if (result != NULL)
1091                 goto endloop;
1092
1093             /*
1094              * If a PEM name matches more than one handler, the handlers are
1095              * badly coded.
1096              */
1097             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1098                 ctx->errcnt++;
1099                 goto endloop;
1100             }
1101
1102             if (matchcount > 1) {
1103                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1104                               OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1105             } else if (matchcount == 1) {
1106                 /*
1107                  * If there are other errors on the stack, they already show
1108                  * what the problem is.
1109                  */
1110                 if (ERR_peek_error() == 0) {
1111                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1112                                   OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1113                     if (pem_name != NULL)
1114                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1115                 }
1116             }
1117             if (matchcount > 0)
1118                 ctx->errcnt++;
1119
1120          endloop:
1121             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1122             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1123             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1124         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1125
1126         /* We bail out on ambiguity */
1127         if (matchcount > 1)
1128             return NULL;
1129     }
1130
1131     return result;
1132 }
1133
1134 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1135 {
1136     return ctx->errcnt > 0;
1137 }
1138
1139 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1140 {
1141     if (ctx->type == is_dir)
1142         return ctx->_.dir.end_reached;
1143
1144     if (ctx->_.file.last_handler != NULL
1145         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1146         return 0;
1147     return BIO_eof(ctx->_.file.file);
1148 }
1149
1150 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1151 {
1152     if (ctx->type == is_dir) {
1153         OPENSSL_DIR_end(&ctx->_.dir.ctx);
1154     } else {
1155         BIO_free_all(ctx->_.file.file);
1156     }
1157     OSSL_STORE_LOADER_CTX_free(ctx);
1158     return 1;
1159 }
1160
1161 static OSSL_STORE_LOADER file_loader =
1162     {
1163         "file",
1164         NULL,
1165         file_open,
1166         file_ctrl,
1167         file_load,
1168         file_eof,
1169         file_error,
1170         file_close
1171     };
1172
1173 static void store_file_loader_deinit(void)
1174 {
1175     ossl_store_unregister_loader_int(file_loader.scheme);
1176 }
1177
1178 int ossl_store_file_loader_init(void)
1179 {
1180     int ret = ossl_store_register_loader_int(&file_loader);
1181
1182     OPENSSL_atexit(store_file_loader_deinit);
1183     return ret;
1184 }