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