27af75249764e8b7af01669bb98cfba0599d0288
[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  *    ui_method:    Application UI method for getting a password, pin
129  *                  or any other interactive data.
130  *    ui_data:      Application data to be passed to ui_method when
131  *                  it's called.
132  * Output:
133  *    a OSSL_STORE_INFO
134  */
135 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
136                                                const char *pem_header,
137                                                const unsigned char *blob,
138                                                size_t len, void **handler_ctx,
139                                                const UI_METHOD *ui_method,
140                                                void *ui_data);
141 /*
142  * The eof function should return 1 if there's no more data to be found
143  * with the handler_ctx, otherwise 0.  This is only used when the handler is
144  * marked repeatable.
145  */
146 typedef int (*file_eof_fn)(void *handler_ctx);
147 /*
148  * The destroy_ctx function is used to destroy the handler_ctx that was
149  * intiated by a repeatable try_decode fuction.  This is only used when
150  * the handler is marked repeatable.
151  */
152 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
153
154 typedef struct file_handler_st {
155     const char *name;
156     file_try_decode_fn try_decode;
157     file_eof_fn eof;
158     file_destroy_ctx_fn destroy_ctx;
159
160     /* flags */
161     int repeatable;
162 } FILE_HANDLER;
163
164 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
165                                           const char *pem_header,
166                                           const unsigned char *blob,
167                                           size_t len, void **pctx,
168                                           const UI_METHOD *ui_method,
169                                           void *ui_data)
170 {
171     OSSL_STORE_INFO *store_info = NULL;
172     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
173
174     if (ctx == NULL) {
175         /* Initial parsing */
176         PKCS12 *p12;
177         int ok = 0;
178
179         if (pem_name != NULL)
180             /* No match, there is no PEM PKCS12 tag */
181             return NULL;
182
183         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
184             char *pass = NULL;
185             char tpass[PEM_BUFSIZE];
186             EVP_PKEY *pkey = NULL;
187             X509 *cert = NULL;
188             STACK_OF(X509) *chain = NULL;
189
190             if (PKCS12_verify_mac(p12, "", 0)
191                 || PKCS12_verify_mac(p12, NULL, 0)) {
192                 pass = "";
193             } else {
194                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
195                                           "PKCS12 import password",
196                                           ui_data)) == NULL) {
197                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
198                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
199                     goto p12_end;
200                 }
201                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
202                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
203                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
204                     goto p12_end;
205                 }
206             }
207
208             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
209                 OSSL_STORE_INFO *si_pkey = NULL;
210                 OSSL_STORE_INFO *si_cert = NULL;
211                 OSSL_STORE_INFO *si_ca = NULL;
212
213                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
214                     && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
215                     && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0
216                     && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
217                     && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) {
218                     ok = 1;
219                     si_pkey = NULL;
220                     si_cert = NULL;
221
222                     while(sk_X509_num(chain) > 0) {
223                         X509 *ca = sk_X509_value(chain, 0);
224
225                         if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
226                             || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) {
227                             ok = 0;
228                             break;
229                         }
230                         si_ca = NULL;
231                         (void)sk_X509_shift(chain);
232                     }
233                 }
234                 if (!ok) {
235                     OSSL_STORE_INFO_free(si_ca);
236                     OSSL_STORE_INFO_free(si_cert);
237                     OSSL_STORE_INFO_free(si_pkey);
238                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
239                     EVP_PKEY_free(pkey);
240                     X509_free(cert);
241                     sk_X509_pop_free(chain, X509_free);
242                     ctx = NULL;
243                 }
244                 *pctx = ctx;
245             }
246         }
247      p12_end:
248         PKCS12_free(p12);
249         if (!ok)
250             return NULL;
251     }
252
253     if (ctx != NULL)
254         store_info = sk_OSSL_STORE_INFO_shift(ctx);
255
256     return store_info;
257 }
258 static int eof_PKCS12(void *ctx_)
259 {
260     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
261
262     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
263 }
264 static void destroy_ctx_PKCS12(void **pctx)
265 {
266     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
267
268     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
269     *pctx = NULL;
270 }
271 static FILE_HANDLER PKCS12_handler = {
272     "PKCS12",
273     try_decode_PKCS12,
274     eof_PKCS12,
275     destroy_ctx_PKCS12,
276     1                            /* repeatable */
277 };
278
279 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
280                                                   const char *pem_header,
281                                                   const unsigned char *blob,
282                                                   size_t len, void **pctx,
283                                                   const UI_METHOD *ui_method,
284                                                   void *ui_data)
285 {
286     X509_SIG *p8 = NULL;
287     char kbuf[PEM_BUFSIZE];
288     char *pass = NULL;
289     const X509_ALGOR *dalg = NULL;
290     const ASN1_OCTET_STRING *doct = NULL;
291     OSSL_STORE_INFO *store_info = NULL;
292     BUF_MEM *mem = NULL;
293     unsigned char *new_data = NULL;
294     int new_data_len;
295
296     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PKCS8) != 0)
297         return NULL;
298
299     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
300         return NULL;
301
302     if ((mem = BUF_MEM_new()) == NULL) {
303         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
304                       ERR_R_MALLOC_FAILURE);
305         goto nop8;
306     }
307
308     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
309                               "PKCS8 decrypt password", ui_data)) == NULL) {
310         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
311                       OSSL_STORE_R_BAD_PASSWORD_READ);
312         goto nop8;
313     }
314
315     X509_SIG_get0(p8, &dalg, &doct);
316     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
317                           &new_data, &new_data_len, 0))
318         goto nop8;
319
320     mem->data = (char *)new_data;
321     mem->max = mem->length = (size_t)new_data_len;
322     X509_SIG_free(p8);
323
324     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
325     if (store_info == NULL) {
326         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
327                       ERR_R_MALLOC_FAILURE);
328         goto nop8;
329     }
330
331     return store_info;
332  nop8:
333     X509_SIG_free(p8);
334     BUF_MEM_free(mem);
335     return NULL;
336 }
337 static FILE_HANDLER PKCS8Encrypted_handler = {
338     "PKCS8Encrypted",
339     try_decode_PKCS8Encrypted
340 };
341
342 int pem_check_suffix(const char *pem_str, const char *suffix);
343 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
344                                               const char *pem_header,
345                                               const unsigned char *blob,
346                                               size_t len, void **pctx,
347                                               const UI_METHOD *ui_method,
348                                               void *ui_data)
349 {
350     OSSL_STORE_INFO *store_info = NULL;
351     EVP_PKEY *pkey = NULL;
352     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
353
354     if (pem_name != NULL) {
355         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
356             PKCS8_PRIV_KEY_INFO *p8inf =
357                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
358
359             if (p8inf != NULL)
360                 pkey = EVP_PKCS82PKEY(p8inf);
361             PKCS8_PRIV_KEY_INFO_free(p8inf);
362         } else {
363             int slen;
364
365             if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
366                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
367                                                    slen)) != NULL)
368                 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
369         }
370     } else {
371         int i;
372
373         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
374             ameth = EVP_PKEY_asn1_get0(i);
375             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
376                 continue;
377             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
378             if (pkey != NULL)
379                 break;
380         }
381     }
382     if (pkey == NULL)
383         /* No match */
384         return NULL;
385
386     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
387     if (store_info == NULL)
388         EVP_PKEY_free(pkey);
389
390     return store_info;
391 }
392 static FILE_HANDLER PrivateKey_handler = {
393     "PrivateKey",
394     try_decode_PrivateKey
395 };
396
397 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
398                                           const char *pem_header,
399                                           const unsigned char *blob,
400                                           size_t len, void **pctx,
401                                           const UI_METHOD *ui_method,
402                                           void *ui_data)
403 {
404     OSSL_STORE_INFO *store_info = NULL;
405     EVP_PKEY *pkey = NULL;
406
407     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
408         /* No match */
409         return NULL;
410
411     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL)
412         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
413
414     return store_info;
415 }
416 static FILE_HANDLER PUBKEY_handler = {
417     "PUBKEY",
418     try_decode_PUBKEY
419 };
420
421 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
422                                           const char *pem_header,
423                                           const unsigned char *blob,
424                                           size_t len, void **pctx,
425                                           const UI_METHOD *ui_method,
426                                           void *ui_data)
427 {
428     OSSL_STORE_INFO *store_info = NULL;
429     EVP_PKEY *pkey = EVP_PKEY_new();
430     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
431     int ok = 0;
432
433     if (pkey == NULL) {
434         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
435         return NULL;
436     }
437
438     if (pem_name != NULL) {
439         int slen;
440
441         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) > 0
442             && EVP_PKEY_set_type_str(pkey, pem_name, slen)
443             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
444             && ameth->param_decode != NULL
445             && ameth->param_decode(pkey, &blob, len))
446             ok = 1;
447     } else {
448         int i;
449
450         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
451             ameth = EVP_PKEY_asn1_get0(i);
452             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
453                 continue;
454             if (EVP_PKEY_set_type(pkey, ameth->pkey_id)
455                 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
456                 && ameth->param_decode != NULL
457                 && ameth->param_decode(pkey, &blob, len)) {
458                 ok = 1;
459                 break;
460             }
461         }
462     }
463
464     if (ok)
465         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
466     if (store_info == NULL)
467         EVP_PKEY_free(pkey);
468
469     return store_info;
470 }
471 static FILE_HANDLER params_handler = {
472     "params",
473     try_decode_params
474 };
475
476 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
477                                                    const char *pem_header,
478                                                    const unsigned char *blob,
479                                                    size_t len, void **pctx,
480                                                    const UI_METHOD *ui_method,
481                                                    void *ui_data)
482 {
483     OSSL_STORE_INFO *store_info = NULL;
484     X509 *cert = NULL;
485
486     /*
487      * In most cases, we can try to interpret the serialized data as a trusted
488      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
489      * (just X509), but if the PEM name specifically declares it as a trusted
490      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
491      * the fallback can be used (1) or not (0).
492      */
493     int ignore_trusted = 1;
494
495     if (pem_name != NULL) {
496         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
497             ignore_trusted = 0;
498         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
499                  && strcmp(pem_name, PEM_STRING_X509) != 0)
500             /* No match */
501             return NULL;
502     }
503
504     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
505         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL))
506         store_info = OSSL_STORE_INFO_new_CERT(cert);
507
508     if (store_info == NULL)
509         X509_free(cert);
510
511     return store_info;
512 }
513 static FILE_HANDLER X509Certificate_handler = {
514     "X509Certificate",
515     try_decode_X509Certificate
516 };
517
518 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
519                                            const char *pem_header,
520                                            const unsigned char *blob,
521                                            size_t len, void **pctx,
522                                            const UI_METHOD *ui_method,
523                                            void *ui_data)
524 {
525     OSSL_STORE_INFO *store_info = NULL;
526     X509_CRL *crl = NULL;
527
528     if (pem_name != NULL
529         && strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
530         /* No match */
531         return NULL;
532
533     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL)
534         store_info = OSSL_STORE_INFO_new_CRL(crl);
535
536     if (store_info == NULL)
537         X509_CRL_free(crl);
538
539     return store_info;
540 }
541 static FILE_HANDLER X509CRL_handler = {
542     "X509CRL",
543     try_decode_X509CRL
544 };
545
546 static const FILE_HANDLER *file_handlers[] = {
547     &PKCS12_handler,
548     &PKCS8Encrypted_handler,
549     &X509Certificate_handler,
550     &X509CRL_handler,
551     &params_handler,
552     &PUBKEY_handler,
553     &PrivateKey_handler,
554 };
555
556
557 /*
558  *  The loader itself
559  */
560
561 struct ossl_store_loader_ctx_st {
562     enum {
563         is_raw = 0,
564         is_pem,
565         is_dir
566     } type;
567     int errcnt;
568     union {
569         struct {                 /* Used with is_raw and is_pem */
570             BIO *file;
571
572             /*
573              * The following are used when the handler is marked as
574              * repeatable
575              */
576             const FILE_HANDLER *last_handler;
577             void *last_handler_ctx;
578         } file;
579         struct {                 /* Used with is_dir */
580             OPENSSL_DIR_CTX *ctx;
581             int end_reached;
582             char *uri;
583
584             /*
585              * The directory reading utility we have combines opening with
586              * reading the first name.  To make sure we can detect the end
587              * at the right time, we read early and cache the name.
588              */
589             const char *last_entry;
590             int last_errno;
591         } dir;
592     } _;
593 };
594
595 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
596 {
597     if (ctx->type == is_dir) {
598         OPENSSL_free(ctx->_.dir.uri);
599     } else {
600         if (ctx->_.file.last_handler != NULL) {
601             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
602             ctx->_.file.last_handler_ctx = NULL;
603             ctx->_.file.last_handler = NULL;
604         }
605     }
606     OPENSSL_free(ctx);
607 }
608
609 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
610                                         const char *uri,
611                                         const UI_METHOD *ui_method,
612                                         void *ui_data)
613 {
614     OSSL_STORE_LOADER_CTX *ctx = NULL;
615     struct stat st;
616     const char *path = NULL;
617
618     if (strncasecmp(uri, "file:", 5) == 0) {
619         if (strncmp(&uri[5], "//localhost/", 12) == 0) {
620             path = &uri[16];
621         } else if (strncmp(&uri[5], "///", 3) == 0) {
622             path = &uri[7];
623         } else if (strncmp(&uri[5], "//", 2) != 0) {
624             path = &uri[5];
625         } else {
626             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
627                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
628             return NULL;
629         }
630
631         /*
632          * If the scheme "file" was an explicit part of the URI, the path must
633          * be absolute.  So says RFC 8089
634          */
635         if (path[0] != '/') {
636             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
637                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
638             return NULL;
639         }
640
641 #ifdef _WIN32
642         /* Windows file: URIs with a drive letter start with a / */
643         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
644             path++;
645 #endif
646     } else {
647         path = uri;
648     }
649
650
651     if (stat(path, &st) < 0) {
652         SYSerr(SYS_F_STAT, errno);
653         ERR_add_error_data(1, path);
654         return NULL;
655     }
656
657     ctx = OPENSSL_zalloc(sizeof(*ctx));
658     if (ctx == NULL) {
659         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
660         return NULL;
661     }
662
663     if ((st.st_mode & S_IFDIR) == S_IFDIR) {
664         /*
665          * Try to copy everything, even if we know that some of them must be
666          * NULL for the moment.  This prevents errors in the future, when more
667          * components may be used.
668          */
669         ctx->_.dir.uri = OPENSSL_strdup(uri);
670         ctx->type = is_dir;
671
672         if (ctx->_.dir.uri == NULL)
673             goto err;
674
675         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
676         ctx->_.dir.last_errno = errno;
677         if (ctx->_.dir.last_entry == NULL) {
678             if (ctx->_.dir.last_errno != 0) {
679                 char errbuf[256];
680                 errno = ctx->_.dir.last_errno;
681                 openssl_strerror_r(errno, errbuf, sizeof(errbuf));
682                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
683                 ERR_add_error_data(1, errbuf);
684                 goto err;
685             }
686             ctx->_.dir.end_reached = 1;
687         }
688     } else {
689         BIO *buff = NULL;
690         char peekbuf[4096];
691
692         if ((buff = BIO_new(BIO_f_buffer())) == NULL
693             || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
694             BIO_free_all(buff);
695             goto err;
696         }
697
698         ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
699         if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf)-1) > 0) {
700             peekbuf[sizeof(peekbuf)-1] = '\0';
701             if (strstr(peekbuf, "-----BEGIN ") != NULL)
702                 ctx->type = is_pem;
703         }
704     }
705
706     return ctx;
707  err:
708     OSSL_STORE_LOADER_CTX_free(ctx);
709     return NULL;
710 }
711
712 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
713                                              const char *pem_name,
714                                              const char *pem_header,
715                                              unsigned char *data, size_t len,
716                                              const UI_METHOD *ui_method,
717                                              void *ui_data, int *matchcount)
718 {
719     OSSL_STORE_INFO *result = NULL;
720     BUF_MEM *new_mem = NULL;
721     char *new_pem_name = NULL;
722     int t = 0;
723
724  again:
725     {
726         size_t i = 0;
727         void *handler_ctx = NULL;
728         const FILE_HANDLER **matching_handlers =
729             OPENSSL_zalloc(sizeof(*matching_handlers)
730                            * OSSL_NELEM(file_handlers));
731
732         if (matching_handlers == NULL) {
733             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
734                           ERR_R_MALLOC_FAILURE);
735             goto err;
736         }
737
738         *matchcount = 0;
739         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
740             const FILE_HANDLER *handler = file_handlers[i];
741             void *tmp_handler_ctx = NULL;
742             OSSL_STORE_INFO *tmp_result =
743                 handler->try_decode(pem_name, pem_header, data, len,
744                                     &tmp_handler_ctx, ui_method, ui_data);
745
746             if (tmp_result == NULL) {
747                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
748                               OSSL_STORE_R_IS_NOT_A);
749                 ERR_add_error_data(1, handler->name);
750             } else {
751                 if (matching_handlers)
752                     matching_handlers[*matchcount] = handler;
753
754                 if (handler_ctx)
755                     handler->destroy_ctx(&handler_ctx);
756                 handler_ctx = tmp_handler_ctx;
757
758                 if (++*matchcount == 1) {
759                     result = tmp_result;
760                     tmp_result = NULL;
761                 } else {
762                     /* more than one match => ambiguous, kill any result */
763                     OSSL_STORE_INFO_free(result);
764                     OSSL_STORE_INFO_free(tmp_result);
765                     if (handler->destroy_ctx != NULL)
766                         handler->destroy_ctx(&handler_ctx);
767                     handler_ctx = NULL;
768                     result = NULL;
769                 }
770             }
771         }
772
773         if (*matchcount > 1)
774             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
775                           OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
776         if (*matchcount == 0)
777             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
778                           OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
779         else if (matching_handlers[0]->repeatable) {
780             if (ctx == NULL) {
781                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
782                               OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
783                 OSSL_STORE_INFO_free(result);
784                 result = NULL;
785             } else {
786                 ctx->_.file.last_handler = matching_handlers[0];
787                 ctx->_.file.last_handler_ctx = handler_ctx;
788             }
789         }
790
791         OPENSSL_free(matching_handlers);
792     }
793
794  err:
795     OPENSSL_free(new_pem_name);
796     BUF_MEM_free(new_mem);
797
798     if (result != NULL
799         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
800         pem_name = new_pem_name =
801             ossl_store_info_get0_EMBEDDED_pem_name(result);
802         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
803         data = (unsigned char *)new_mem->data;
804         len = new_mem->length;
805         OPENSSL_free(result);
806         result = NULL;
807         goto again;
808     }
809
810     if (result != NULL)
811         ERR_clear_error();
812
813     return result;
814 }
815
816 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
817                                              const UI_METHOD *ui_method,
818                                              void *ui_data)
819 {
820     OSSL_STORE_INFO *result = NULL;
821
822     if (ctx->_.file.last_handler != NULL) {
823         result =
824             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
825                                                  &ctx->_.file.last_handler_ctx,
826                                                  ui_method, ui_data);
827
828         if (result == NULL) {
829             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
830             ctx->_.file.last_handler_ctx = NULL;
831             ctx->_.file.last_handler = NULL;
832         }
833     }
834     return result;
835 }
836
837 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
838                          unsigned char **data, long *len,
839                          const UI_METHOD *ui_method,
840                          void *ui_data)
841 {
842     int i = PEM_read_bio(bp, pem_name, pem_header, data, len);
843
844     if (i <= 0)
845         return 0;
846
847     /*
848      * 10 is the number of characters in "Proc-Type:", which
849      * PEM_get_EVP_CIPHER_INFO() requires to be present.
850      * If the PEM header has less characters than that, it's
851      * not worth spending cycles on it.
852      */
853     if (strlen(*pem_header) > 10) {
854         EVP_CIPHER_INFO cipher;
855         struct pem_pass_data pass_data;
856
857         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
858             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
859             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
860                               &pass_data)) {
861             return 0;
862         }
863     }
864     return 1;
865 }
866
867 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
868 {
869     BUF_MEM *mem = NULL;
870
871     if (asn1_d2i_read_bio(bp, &mem) < 0)
872         return 0;
873
874     *data = (unsigned char *)mem->data;
875     *len = (long)mem->length;
876     OPENSSL_free(mem);
877
878     return 1;
879 }
880
881 static int ends_with_dirsep(const char *uri)
882 {
883     if (*uri != '\0')
884         uri += strlen(uri) - 1;
885 #if defined __VMS
886     if (*uri == ']' || *uri == '>' || *uri == ':')
887         return 1;
888 #elif defined _WIN32
889     if (*uri == '\\')
890         return 1;
891 #endif
892     return *uri == '/';
893 }
894
895 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
896                             char **data)
897 {
898     assert(name != NULL);
899     assert(data != NULL);
900     {
901         const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
902         long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
903             + strlen(name) + 1 /* \0 */;
904
905         *data = OPENSSL_zalloc(calculated_length);
906         if (*data == NULL) {
907             OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
908             return 0;
909         }
910
911         OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
912         OPENSSL_strlcat(*data, pathsep, calculated_length);
913         OPENSSL_strlcat(*data, name, calculated_length);
914     }
915     return 1;
916 }
917
918 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
919 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
920 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
921                                   const UI_METHOD *ui_method, void *ui_data)
922 {
923     OSSL_STORE_INFO *result = NULL;
924
925     if (ctx->type == is_dir) {
926         do {
927             char *newname = NULL;
928
929             if (ctx->_.dir.last_entry == NULL) {
930                 if (!ctx->_.dir.end_reached) {
931                     char errbuf[256];
932                     assert(ctx->_.dir.last_errno != 0);
933                     errno = ctx->_.dir.last_errno;
934                     ctx->errcnt++;
935                     openssl_strerror_r(errno, errbuf, sizeof(errbuf));
936                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
937                     ERR_add_error_data(1, errbuf);
938                 }
939                 return NULL;
940             }
941
942             if (ctx->_.dir.last_entry[0] != '.'
943                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
944                 return NULL;
945
946             /*
947              * On the first call (with a NULL context), OPENSSL_DIR_read()
948              * cares about the second argument.  On the following calls, it
949              * only cares that it isn't NULL.  Therefore, we can safely give
950              * it our URI here.
951              */
952             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
953                                                      ctx->_.dir.uri);
954             ctx->_.dir.last_errno = errno;
955             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
956                 ctx->_.dir.end_reached = 1;
957
958             if (newname != NULL
959                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
960                 OPENSSL_free(newname);
961                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
962                 return NULL;
963             }
964         } while (result == NULL && !file_eof(ctx));
965     } else {
966         int matchcount = -1;
967
968         result = file_load_try_repeat(ctx, ui_method, ui_data);
969         if (result != NULL)
970             return result;
971
972         if (file_error(ctx))
973             return NULL;
974
975         do {
976             char *pem_name = NULL;      /* PEM record name */
977             char *pem_header = NULL;    /* PEM record header */
978             unsigned char *data = NULL; /* DER encoded data */
979             long len = 0;               /* DER encoded data length */
980
981             matchcount = -1;
982             if (ctx->type == is_pem) {
983                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
984                                    &data, &len, ui_method, ui_data)) {
985                     if (!file_eof(ctx))
986                         ctx->errcnt++;
987                     goto err;
988                 }
989             } else {
990                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
991                     if (!file_eof(ctx))
992                         ctx->errcnt++;
993                     goto err;
994                 }
995             }
996
997             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
998                                           ui_method, ui_data, &matchcount);
999
1000          err:
1001             OPENSSL_free(pem_name);
1002             OPENSSL_free(pem_header);
1003             OPENSSL_free(data);
1004         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1005
1006         /* We bail out on ambiguity */
1007         if (matchcount > 1)
1008             return NULL;
1009     }
1010
1011     return result;
1012 }
1013
1014 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1015 {
1016     return ctx->errcnt > 0;
1017 }
1018
1019 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1020 {
1021     if (ctx->type == is_dir)
1022         return ctx->_.dir.end_reached;
1023
1024     if (ctx->_.file.last_handler != NULL
1025         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1026         return 0;
1027     return BIO_eof(ctx->_.file.file);
1028 }
1029
1030 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1031 {
1032     if (ctx->type == is_dir) {
1033         OPENSSL_DIR_end(&ctx->_.dir.ctx);
1034     } else {
1035         BIO_free_all(ctx->_.file.file);
1036     }
1037     OSSL_STORE_LOADER_CTX_free(ctx);
1038     return 1;
1039 }
1040
1041 static OSSL_STORE_LOADER file_loader =
1042     {
1043         "file",
1044         file_open,
1045         NULL,
1046         file_load,
1047         file_eof,
1048         file_error,
1049         file_close
1050     };
1051
1052 static void store_file_loader_deinit(void)
1053 {
1054     ossl_store_unregister_loader_int(file_loader.scheme);
1055 }
1056
1057 int ossl_store_file_loader_init(void)
1058 {
1059     int ret = ossl_store_register_loader_int(&file_loader);
1060
1061     OPENSSL_atexit(store_file_loader_deinit);
1062     return ret;
1063 }