Add X509_NAME_hash_ex() to be able to check if it failed due to unsupported SHA1
[openssl.git] / providers / implementations / storemgmt / file_store.c
1 /*
2  * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"                /* To get strncasecmp() on Windows */
11 #include <string.h>
12 #include <sys/stat.h>
13 #include <ctype.h>
14 #include <assert.h>
15
16 #include <openssl/core.h>
17 #include <openssl/core_dispatch.h>
18 #include <openssl/core_names.h>
19 #include <openssl/core_object.h>
20 #include <openssl/crypto.h>
21 #include <openssl/bio.h>
22 #include <openssl/err.h>
23 #include <openssl/buffer.h>
24 #include <openssl/params.h>
25 #include <openssl/decoder.h>
26 #include <openssl/store.h>       /* The OSSL_STORE_INFO type numbers */
27 #include "internal/cryptlib.h"
28 #include "internal/o_dir.h"
29 #include "crypto/pem.h"          /* For PVK and "blob" PEM headers */
30 #include "crypto/decoder.h"
31 #include "prov/implementations.h"
32 #include "prov/bio.h"
33 #include "prov/provider_ctx.h"
34 #include "prov/providercommonerr.h"
35 #include "file_store_local.h"
36
37 DEFINE_STACK_OF(OSSL_STORE_INFO)
38
39 #ifdef _WIN32
40 # define stat _stat
41 #endif
42
43 #ifndef S_ISDIR
44 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
45 #endif
46
47 static OSSL_FUNC_store_open_fn file_open;
48 static OSSL_FUNC_store_attach_fn file_attach;
49 static OSSL_FUNC_store_settable_ctx_params_fn file_settable_ctx_params;
50 static OSSL_FUNC_store_set_ctx_params_fn file_set_ctx_params;
51 static OSSL_FUNC_store_load_fn file_load;
52 static OSSL_FUNC_store_eof_fn file_eof;
53 static OSSL_FUNC_store_close_fn file_close;
54
55 /*
56  * This implementation makes full use of OSSL_DECODER, and then some.
57  * It uses its own internal decoder implementation that reads DER and
58  * passes that on to the data callback; this decoder is created with
59  * internal OpenSSL functions, thereby bypassing the need for a surrounding
60  * provider.  This is ok, since this is a local decoder, not meant for
61  * public consumption.  It also uses the libcrypto internal decoder
62  * setup function ossl_decoder_ctx_setup_for_EVP_PKEY(), to allow the
63  * last resort decoder to be added first (and thereby be executed last).
64  * Finally, it sets up its own construct and cleanup functions.
65  *
66  * Essentially, that makes this implementation a kind of glorified decoder.
67  */
68
69 struct file_ctx_st {
70     void *provctx;
71     char *uri;                   /* The URI we currently try to load */
72     enum {
73         IS_FILE = 0,             /* Read file and pass results */
74         IS_DIR                   /* Pass directory entry names */
75     } type;
76
77     /* Flag bits */
78     unsigned int flag_attached:1;
79     unsigned int flag_buffered:1;
80
81     union {
82         /* Used with |IS_FILE| */
83         struct {
84             BIO *file;
85
86             OSSL_DECODER_CTX *decoderctx;
87             char *input_type;
88             char *propq;    /* The properties we got as a parameter */
89         } file;
90
91         /* Used with |IS_DIR| */
92         struct {
93             OPENSSL_DIR_CTX *ctx;
94             int end_reached;
95
96             /*
97              * When a search expression is given, these are filled in.
98              * |search_name| contains the file basename to look for.
99              * The string is exactly 8 characters long.
100              */
101             char search_name[9];
102
103             /*
104              * The directory reading utility we have combines opening with
105              * reading the first name.  To make sure we can detect the end
106              * at the right time, we read early and cache the name.
107              */
108             const char *last_entry;
109             int last_errno;
110         } dir;
111     } _;
112
113     /* Expected object type.  May be unspecified */
114     int expected_type;
115 };
116
117 static void free_file_ctx(struct file_ctx_st *ctx)
118 {
119     if (ctx == NULL)
120         return;
121
122     OPENSSL_free(ctx->uri);
123     if (ctx->type != IS_DIR) {
124         OSSL_DECODER_CTX_free(ctx->_.file.decoderctx);
125         OPENSSL_free(ctx->_.file.propq);
126         OPENSSL_free(ctx->_.file.input_type);
127     }
128     OPENSSL_free(ctx);
129 }
130
131 static struct file_ctx_st *new_file_ctx(int type, const char *uri,
132                                         void *provctx)
133 {
134     struct file_ctx_st *ctx = NULL;
135
136     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL
137         && (uri == NULL || (ctx->uri = OPENSSL_strdup(uri)) != NULL)) {
138         ctx->type = type;
139         ctx->provctx = provctx;
140         return ctx;
141     }
142     free_file_ctx(ctx);
143     return NULL;
144 }
145
146 static OSSL_DECODER_CONSTRUCT file_load_construct;
147 static OSSL_DECODER_CLEANUP file_load_cleanup;
148
149 /*-
150  *  Opening / attaching streams and directories
151  *  -------------------------------------------
152  */
153
154 /*
155  * Function to service both file_open() and file_attach()
156  *
157  *
158  */
159 static struct file_ctx_st *file_open_stream(BIO *source, const char *uri,
160                                             const char *input_type,
161                                             void *provctx)
162 {
163     struct file_ctx_st *ctx;
164
165     if ((ctx = new_file_ctx(IS_FILE, uri, provctx)) == NULL
166         || (input_type != NULL
167             && (ctx->_.file.input_type =
168                 OPENSSL_strdup(input_type)) == NULL)) {
169         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
170         goto err;
171     }
172
173     ctx->_.file.file = source;
174
175     return ctx;
176  err:
177     free_file_ctx(ctx);
178     return NULL;
179 }
180
181 static void *file_open_dir(const char *path, const char *uri, void *provctx)
182 {
183     struct file_ctx_st *ctx;
184
185     if ((ctx = new_file_ctx(IS_DIR, uri, provctx)) == NULL) {
186         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
187         goto err;
188     }
189
190     ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
191     ctx->_.dir.last_errno = errno;
192     if (ctx->_.dir.last_entry == NULL) {
193         if (ctx->_.dir.last_errno != 0) {
194             ERR_raise_data(ERR_LIB_SYS, ctx->_.dir.last_errno,
195                            "Calling OPENSSL_DIR_read(\"%s\")", path);
196             goto err;
197         }
198         ctx->_.dir.end_reached = 1;
199     }
200     return ctx;
201  err:
202     file_close(ctx);
203     return NULL;
204 }
205
206 static void *file_open(void *provctx, const char *uri)
207 {
208     struct file_ctx_st *ctx = NULL;
209     struct stat st;
210     struct {
211         const char *path;
212         unsigned int check_absolute:1;
213     } path_data[2];
214     size_t path_data_n = 0, i;
215     const char *path;
216     BIO *bio;
217
218     ERR_set_mark();
219
220     /*
221      * First step, just take the URI as is.
222      */
223     path_data[path_data_n].check_absolute = 0;
224     path_data[path_data_n++].path = uri;
225
226     /*
227      * Second step, if the URI appears to start with the 'file' scheme,
228      * extract the path and make that the second path to check.
229      * There's a special case if the URI also contains an authority, then
230      * the full URI shouldn't be used as a path anywhere.
231      */
232     if (strncasecmp(uri, "file:", 5) == 0) {
233         const char *p = &uri[5];
234
235         if (strncmp(&uri[5], "//", 2) == 0) {
236             path_data_n--;           /* Invalidate using the full URI */
237             if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
238                 p = &uri[16];
239             } else if (uri[7] == '/') {
240                 p = &uri[7];
241             } else {
242                 ERR_clear_last_mark();
243                 ERR_raise(ERR_LIB_PROV, PROV_R_URI_AUTHORITY_UNSUPPORTED);
244                 return NULL;
245             }
246         }
247
248         path_data[path_data_n].check_absolute = 1;
249 #ifdef _WIN32
250         /* Windows file: URIs with a drive letter start with a / */
251         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
252             char c = tolower(p[1]);
253
254             if (c >= 'a' && c <= 'z') {
255                 p++;
256                 /* We know it's absolute, so no need to check */
257                 path_data[path_data_n].check_absolute = 0;
258             }
259         }
260 #endif
261         path_data[path_data_n++].path = p;
262     }
263
264
265     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
266         /*
267          * If the scheme "file" was an explicit part of the URI, the path must
268          * be absolute.  So says RFC 8089
269          */
270         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
271             ERR_clear_last_mark();
272             ERR_raise_data(ERR_LIB_PROV, PROV_R_PATH_MUST_BE_ABSOLUTE,
273                            "Given path=%s", path_data[i].path);
274             return NULL;
275         }
276
277         if (stat(path_data[i].path, &st) < 0) {
278             ERR_raise_data(ERR_LIB_SYS, errno,
279                            "calling stat(%s)",
280                            path_data[i].path);
281         } else {
282             path = path_data[i].path;
283         }
284     }
285     if (path == NULL) {
286         ERR_clear_last_mark();
287         return NULL;
288     }
289
290     /* Successfully found a working path, clear possible collected errors */
291     ERR_pop_to_mark();
292
293     if (S_ISDIR(st.st_mode))
294         ctx = file_open_dir(path, uri, provctx);
295     else if ((bio = BIO_new_file(path, "rb")) == NULL
296              || (ctx = file_open_stream(bio, uri, NULL, provctx)) == NULL)
297         BIO_free_all(bio);
298
299     return ctx;
300 }
301
302 /*
303  * Attached input streams must be treated very very carefully to avoid
304  * nasty surprises.
305  *
306  * This implementation tries to support input streams that can't be reset,
307  * such as standard input.  However, OSSL_DECODER assumes resettable streams,
308  * and because the PEM decoder may read quite a bit of the input file to skip
309  * past any non-PEM text that precedes the PEM block, we may need to detect
310  * if the input stream is a PEM file early.
311  *
312  * If the input stream supports BIO_tell(), we assume that it also supports
313  * BIO_seek(), making it a resettable stream and therefore safe to fully
314  * unleash OSSL_DECODER.
315  *
316  * If the input stream doesn't support BIO_tell(), we must assume that we
317  * have a non-resettable stream, and must tread carefully.  We do so by
318  * trying to detect if the input is PEM, MSBLOB or PVK, and if not, we
319  * assume that it's DER.
320  *
321  * To detect if an input stream is PEM, MSBLOB or PVK, we use the buffer BIO
322  * filter, which allows us a 4KiB resettable read-ahead.  We *hope* that 4KiB
323  * will be enough to find the start of the PEM block.
324  *
325  * It should be possible to use this same technique to detect other file
326  * types as well.
327  *
328  * An alternative technique would be to have an endlessly caching BIO filter.
329  * That would take away the need for all the detection here, and simply leave
330  * it for OSSL_DECODER to find out on its own while supporting its demand for
331  * resettable input streams.
332  * That's a possible future development.
333  */
334
335 # define INPUT_TYPE_ANY         NULL
336 # define INPUT_TYPE_DER         "DER"
337 # define INPUT_TYPE_PEM         "PEM"
338 # define INPUT_TYPE_MSBLOB      "MSBLOB"
339 # define INPUT_TYPE_PVK         "PVK"
340
341 void *file_attach(void *provctx, OSSL_CORE_BIO *cin)
342 {
343     BIO *new_bio = bio_new_from_core_bio(provctx, cin);
344     BIO *new_bio_tmp = NULL;
345     BIO *buff = NULL;
346     char peekbuf[4096] = { 0, };
347     int loc;
348     const char *input_type = NULL;
349     unsigned int flag_attached = 1;
350     unsigned int flag_buffered = 0;
351     struct file_ctx_st *ctx = NULL;
352
353     if (new_bio == NULL)
354         return 0;
355
356     /* Try to get the current position */
357     loc = BIO_tell(new_bio);
358
359     if ((buff = BIO_new(BIO_f_buffer())) == NULL
360         || (new_bio_tmp = BIO_push(buff, new_bio)) == NULL)
361         goto err;
362
363     /* Assumption, if we can't detect PEM */
364     input_type = INPUT_TYPE_DER;
365     flag_buffered = 1;
366     new_bio = new_bio_tmp;
367
368     if (BIO_buffer_peek(new_bio, peekbuf, sizeof(peekbuf) - 1) > 0) {
369 #ifndef OPENSSL_NO_DSA
370         const unsigned char *p = NULL;
371         unsigned int magic = 0, bitlen = 0;
372         int isdss = 0, ispub = -1;
373 # ifndef OPENSSL_NO_RC4
374         unsigned int saltlen = 0, keylen = 0;
375 # endif
376 #endif
377
378         peekbuf[sizeof(peekbuf) - 1] = '\0';
379         if (strstr(peekbuf, "-----BEGIN ") != NULL)
380             input_type = INPUT_TYPE_PEM;
381 #ifndef OPENSSL_NO_DSA
382         else if (p = (unsigned char *)peekbuf,
383                  ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
384                                      &isdss, &ispub))
385             input_type = INPUT_TYPE_MSBLOB;
386 # ifndef OPENSSL_NO_RC4
387         else if (p = (unsigned char *)peekbuf,
388                  ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
389             input_type = INPUT_TYPE_PVK;
390 # endif
391 #endif
392     }
393
394     /*
395      * After peeking, we know that the underlying source BIO has moved ahead
396      * from its earlier position and that if it supports BIO_tell(), that
397      * should be a number that differs from |loc|.  Otherwise, we will get
398      * the same value, which may one of:
399      *
400      * -   zero (the source BIO doesn't support BIO_tell() / BIO_seek() /
401      *     BIO_reset())
402      * -   -1 (the underlying operating system / C library routines do not
403      *     support BIO_tell() / BIO_seek() / BIO_reset())
404      *
405      * If it turns out that the source BIO does support BIO_tell(), we pop
406      * the buffer BIO filter and mark this input as |INPUT_TYPE_ANY|, which
407      * fully unleashes OSSL_DECODER to do its thing.
408      */
409     if (BIO_tell(new_bio) != loc) {
410         /* In this case, anything goes */
411         input_type = INPUT_TYPE_ANY;
412
413         /* Restore the source BIO like it was when entering this function */
414         new_bio = BIO_pop(buff);
415         BIO_free(buff);
416         (void)BIO_seek(new_bio, loc);
417
418         flag_buffered = 0;
419     }
420
421     if ((ctx = file_open_stream(new_bio, NULL, input_type, provctx)) == NULL)
422         goto err;
423
424     ctx->flag_attached = flag_attached;
425     ctx->flag_buffered = flag_buffered;
426
427     return ctx;
428  err:
429     if (flag_buffered) {
430         new_bio = BIO_pop(buff);
431         BIO_free(buff);
432     }
433     BIO_free(new_bio);           /* Removes the provider BIO filter */
434     return NULL;
435 }
436
437 /*-
438  *  Setting parameters
439  *  ------------------
440  */
441
442 static const OSSL_PARAM *file_settable_ctx_params(void *provctx)
443 {
444     static const OSSL_PARAM known_settable_ctx_params[] = {
445         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
446         OSSL_PARAM_int(OSSL_STORE_PARAM_EXPECT, NULL),
447         OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
448         OSSL_PARAM_END
449     };
450     return known_settable_ctx_params;
451 }
452
453 static int file_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
454 {
455     struct file_ctx_st *ctx = loaderctx;
456     const OSSL_PARAM *p;
457
458     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
459     if (p != NULL) {
460         OPENSSL_free(ctx->_.file.propq);
461         ctx->_.file.propq = NULL;
462         if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.propq, 0))
463             return 0;
464     }
465     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_EXPECT);
466     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->expected_type))
467         return 0;
468     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
469     if (p != NULL) {
470         const unsigned char *der = NULL;
471         size_t der_len = 0;
472         X509_NAME *x509_name;
473         unsigned long hash;
474         int ok;
475
476         if (ctx->type != IS_DIR) {
477             ERR_raise(ERR_LIB_PROV,
478                       PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
479             return 0;
480         }
481
482         if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len)
483             || (x509_name = d2i_X509_NAME(NULL, &der, der_len)) == NULL)
484             return 0;
485         hash = X509_NAME_hash_ex(x509_name,
486                                  ossl_prov_ctx_get0_libctx(ctx->provctx), NULL,
487                                  &ok);
488         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
489                      "%08lx", hash);
490         X509_NAME_free(x509_name);
491         if (ok == 0)
492             return 0;
493     }
494     return 1;
495 }
496
497 /*-
498  *  Loading an object from a stream
499  *  -------------------------------
500  */
501
502 struct file_load_data_st {
503     OSSL_CALLBACK *object_cb;
504     void *object_cbarg;
505 };
506
507 static int file_load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
508                                const OSSL_PARAM *params, void *construct_data)
509 {
510     struct file_load_data_st *data = construct_data;
511
512     /*
513      * At some point, we may find it justifiable to recognise PKCS#12 and
514      * handle it specially here, making |file_load()| return pass its
515      * contents one piece at ta time, like |e_loader_attic.c| does.
516      *
517      * However, that currently means parsing them out, which converts the
518      * DER encoded PKCS#12 into a bunch of EVP_PKEYs and X509s, just to
519      * have to re-encode them into DER to create an object abstraction for
520      * each of them.
521      * It's much simpler (less churn) to pass on the object abstraction we
522      * get to the load_result callback and leave it to that one to do the
523      * work.  If that's libcrypto code, we know that it has much better
524      * possibilities to handle the EVP_PKEYs and X509s without the extra
525      * churn.
526      */
527
528     return data->object_cb(params, data->object_cbarg);
529 }
530
531 void file_load_cleanup(void *construct_data)
532 {
533     /* Nothing to do */
534 }
535
536 static int file_setup_decoders(struct file_ctx_st *ctx)
537 {
538     EVP_PKEY *dummy; /* for OSSL_DECODER_CTX_new_by_EVP_PKEY() */
539     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
540     OSSL_DECODER *to_obj = NULL; /* Last resort decoder */
541     OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
542     OSSL_DECODER_CLEANUP *old_cleanup = NULL;
543     void *old_construct_data = NULL;
544     int ok = 0;
545
546     /* Setup for this session, so only if not already done */
547     if (ctx->_.file.decoderctx == NULL) {
548         if ((ctx->_.file.decoderctx = OSSL_DECODER_CTX_new()) == NULL) {
549             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
550             goto err;
551         }
552
553         /* Make sure the input type is set */
554         if (!OSSL_DECODER_CTX_set_input_type(ctx->_.file.decoderctx,
555                                              ctx->_.file.input_type)) {
556             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
557             goto err;
558         }
559
560         /*
561          * Create the internal last resort decoder implementation together
562          * with a "decoder instance".
563          * The decoder doesn't need any identification or to be attached to
564          * any provider, since it's only used locally.
565          */
566         to_obj = ossl_decoder_from_dispatch(0, &ossl_der_to_obj_algorithm,
567                                             NULL);
568         if (to_obj == NULL)
569             goto err;
570         to_obj_inst = ossl_decoder_instance_new(to_obj, ctx->provctx);
571         if (to_obj_inst == NULL)
572             goto err;
573
574         if (!ossl_decoder_ctx_add_decoder_inst(ctx->_.file.decoderctx,
575                                                to_obj_inst)) {
576             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
577             goto err;
578         }
579
580         /*
581          * OSSL_DECODER_INSTANCE shouldn't be freed from this point on.
582          * That's going to happen whenever the OSSL_DECODER_CTX is freed.
583          */
584         to_obj_inst = NULL;
585
586         /*
587          * Add on the usual decoder context for keys, with a dummy object.
588          * Since we're setting up our own constructor, we don't need to care
589          * more than that...
590          */
591         if (!ossl_decoder_ctx_setup_for_EVP_PKEY(ctx->_.file.decoderctx,
592                                                  &dummy, NULL,
593                                                  libctx, ctx->_.file.propq)
594             || !OSSL_DECODER_CTX_add_extra(ctx->_.file.decoderctx,
595                                            libctx, ctx->_.file.propq)) {
596             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
597             goto err;
598         }
599
600         /*
601          * Then we throw away the installed finalizer data, and install our
602          * own instead.
603          */
604         old_cleanup = OSSL_DECODER_CTX_get_cleanup(ctx->_.file.decoderctx);
605         old_construct_data =
606             OSSL_DECODER_CTX_get_construct_data(ctx->_.file.decoderctx);
607         if (old_cleanup != NULL)
608             old_cleanup(old_construct_data);
609
610         /*
611          * Set the hooks.
612          */
613         if (!OSSL_DECODER_CTX_set_construct(ctx->_.file.decoderctx,
614                                             file_load_construct)
615             || !OSSL_DECODER_CTX_set_cleanup(ctx->_.file.decoderctx,
616                                              file_load_cleanup)) {
617             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
618             goto err;
619         }
620     }
621
622     ok = 1;
623  err:
624     OSSL_DECODER_free(to_obj);
625     return ok;
626 }
627
628 static int file_load_file(struct file_ctx_st *ctx,
629                           OSSL_CALLBACK *object_cb, void *object_cbarg,
630                           OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
631 {
632     struct file_load_data_st data;
633
634     /* Setup the decoders (one time shot per session */
635
636     if (!file_setup_decoders(ctx))
637         return 0;
638
639     /* Setup for this object */
640
641     data.object_cb = object_cb;
642     data.object_cbarg = object_cbarg;
643     OSSL_DECODER_CTX_set_construct_data(ctx->_.file.decoderctx, &data);
644     OSSL_DECODER_CTX_set_passphrase_cb(ctx->_.file.decoderctx, pw_cb, pw_cbarg);
645
646     /* Launch */
647
648     return OSSL_DECODER_from_bio(ctx->_.file.decoderctx, ctx->_.file.file);
649 }
650
651 /*-
652  *  Loading a name object from a directory
653  *  --------------------------------------
654  */
655
656 static char *file_name_to_uri(struct file_ctx_st *ctx, const char *name)
657 {
658     char *data = NULL;
659
660     assert(name != NULL);
661     {
662         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
663         long calculated_length = strlen(ctx->uri) + strlen(pathsep)
664             + strlen(name) + 1 /* \0 */;
665
666         data = OPENSSL_zalloc(calculated_length);
667         if (data == NULL) {
668             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
669             return NULL;
670         }
671
672         OPENSSL_strlcat(data, ctx->uri, calculated_length);
673         OPENSSL_strlcat(data, pathsep, calculated_length);
674         OPENSSL_strlcat(data, name, calculated_length);
675     }
676     return data;
677 }
678
679 static int file_name_check(struct file_ctx_st *ctx, const char *name)
680 {
681     const char *p = NULL;
682
683     /* If there are no search criteria, all names are accepted */
684     if (ctx->_.dir.search_name[0] == '\0')
685         return 1;
686
687     /* If the expected type isn't supported, no name is accepted */
688     if (ctx->expected_type != 0
689         && ctx->expected_type != OSSL_STORE_INFO_CERT
690         && ctx->expected_type != OSSL_STORE_INFO_CRL)
691         return 0;
692
693     /*
694      * First, check the basename
695      */
696     if (strncasecmp(name, ctx->_.dir.search_name,
697                     sizeof(ctx->_.dir.search_name) - 1) != 0
698         || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
699         return 0;
700     p = &name[sizeof(ctx->_.dir.search_name)];
701
702     /*
703      * Then, if the expected type is a CRL, check that the extension starts
704      * with 'r'
705      */
706     if (*p == 'r') {
707         p++;
708         if (ctx->expected_type != 0
709             && ctx->expected_type != OSSL_STORE_INFO_CRL)
710             return 0;
711     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
712         return 0;
713     }
714
715     /*
716      * Last, check that the rest of the extension is a decimal number, at
717      * least one digit long.
718      */
719     if (!isdigit(*p))
720         return 0;
721     while (isdigit(*p))
722         p++;
723
724 #ifdef __VMS
725     /*
726      * One extra step here, check for a possible generation number.
727      */
728     if (*p == ';')
729         for (p++; *p != '\0'; p++)
730             if (!ossl_isdigit(*p))
731                 break;
732 #endif
733
734     /*
735      * If we've reached the end of the string at this point, we've successfully
736      * found a fitting file name.
737      */
738     return *p == '\0';
739 }
740
741 static int file_load_dir_entry(struct file_ctx_st *ctx,
742                                OSSL_CALLBACK *object_cb, void *object_cbarg,
743                                OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
744 {
745     /* Prepare as much as possible in advance */
746     static const int object_type = OSSL_OBJECT_NAME;
747     OSSL_PARAM object[] = {
748         OSSL_PARAM_int(OSSL_OBJECT_PARAM_TYPE, (int *)&object_type),
749         OSSL_PARAM_utf8_string(OSSL_OBJECT_PARAM_DATA, NULL, 0),
750         OSSL_PARAM_END
751     };
752     char *newname = NULL;
753     int ok;
754
755     /* Loop until we get an error or until we have a suitable name */
756     do {
757         if (ctx->_.dir.last_entry == NULL) {
758             if (!ctx->_.dir.end_reached) {
759                 assert(ctx->_.dir.last_errno != 0);
760                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
761             }
762             /* file_eof() will tell if EOF was reached */
763             return 0;
764         }
765
766         /* flag acceptable names */
767         if (ctx->_.dir.last_entry[0] != '.'
768             && file_name_check(ctx, ctx->_.dir.last_entry)) {
769
770             /* If we can't allocate the new name, we fail */
771             if ((newname =
772                  file_name_to_uri(ctx, ctx->_.dir.last_entry)) == NULL)
773                 return 0;
774         }
775
776         /*
777          * On the first call (with a NULL context), OPENSSL_DIR_read()
778          * cares about the second argument.  On the following calls, it
779          * only cares that it isn't NULL.  Therefore, we can safely give
780          * it our URI here.
781          */
782         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
783         ctx->_.dir.last_errno = errno;
784         if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
785             ctx->_.dir.end_reached = 1;
786     } while (newname == NULL);
787
788     object[1].data = newname;
789     object[1].data_size = strlen(newname);
790     ok = object_cb(object, object_cbarg);
791     OPENSSL_free(newname);
792     return ok;
793 }
794
795 /*-
796  *  Loading, local dispatcher
797  *  -------------------------
798  */
799
800 static int file_load(void *loaderctx,
801                      OSSL_CALLBACK *object_cb, void *object_cbarg,
802                      OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
803 {
804     struct file_ctx_st *ctx = loaderctx;
805
806     switch (ctx->type) {
807     case IS_FILE:
808         return file_load_file(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
809     case IS_DIR:
810         return
811             file_load_dir_entry(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
812     default:
813         break;
814     }
815
816     /* ctx->type has an unexpected value */
817     assert(0);
818     return 0;
819 }
820
821 /*-
822  *  Eof detection and closing
823  *  -------------------------
824  */
825
826 static int file_eof(void *loaderctx)
827 {
828     struct file_ctx_st *ctx = loaderctx;
829
830     switch (ctx->type) {
831     case IS_DIR:
832         return ctx->_.dir.end_reached;
833     case IS_FILE:
834         /*
835          * BIO_pending() checks any filter BIO.
836          * BIO_eof() checks the source BIO.
837          */
838         return !BIO_pending(ctx->_.file.file)
839             && BIO_eof(ctx->_.file.file);
840     }
841
842     /* ctx->type has an unexpected value */
843     assert(0);
844     return 1;
845 }
846
847 static int file_close_dir(struct file_ctx_st *ctx)
848 {
849     if (ctx->_.dir.ctx != NULL)
850         OPENSSL_DIR_end(&ctx->_.dir.ctx);
851     free_file_ctx(ctx);
852     return 1;
853 }
854
855 static int file_close_stream(struct file_ctx_st *ctx)
856 {
857     if (ctx->flag_buffered) {
858         /*
859          * file_attach() pushed a BIO_f_buffer() on top of the regular BIO.
860          * Drop it.
861          */
862         BIO *buff = ctx->_.file.file;
863
864         /* Detach buff */
865         ctx->_.file.file = BIO_pop(ctx->_.file.file);
866
867         BIO_free(buff);
868     }
869
870     /*
871      * If it was attached, we only free the top, as that's the provider BIO
872      * filter.  Otherwise, it was entirely allocated by this implementation,
873      * and can safely be completely freed.
874      */
875     if (ctx->flag_attached)
876         BIO_free(ctx->_.file.file);
877     else
878         BIO_free_all(ctx->_.file.file);
879
880     /* To avoid double free */
881     ctx->_.file.file = NULL;
882
883     free_file_ctx(ctx);
884     return 1;
885 }
886
887 static int file_close(void *loaderctx)
888 {
889     struct file_ctx_st *ctx = loaderctx;
890
891     switch (ctx->type) {
892     case IS_DIR:
893         return file_close_dir(ctx);
894     case IS_FILE:
895         return file_close_stream(ctx);
896     }
897
898     /* ctx->type has an unexpected value */
899     assert(0);
900     return 1;
901 }
902
903 const OSSL_DISPATCH ossl_file_store_functions[] = {
904     { OSSL_FUNC_STORE_OPEN, (void (*)(void))file_open },
905     { OSSL_FUNC_STORE_ATTACH, (void (*)(void))file_attach },
906     { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
907       (void (*)(void))file_settable_ctx_params },
908     { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))file_set_ctx_params },
909     { OSSL_FUNC_STORE_LOAD, (void (*)(void))file_load },
910     { OSSL_FUNC_STORE_EOF, (void (*)(void))file_eof },
911     { OSSL_FUNC_STORE_CLOSE, (void (*)(void))file_close },
912     { 0, NULL },
913 };