xref: /freebsd/crypto/openssl/providers/implementations/storemgmt/file_store.c (revision 10a428653ee7216475f1ddce3fb4cbf1200319f8)
1 /*
2  * Copyright 2020-2026 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 /* This file has quite some overlap with engines/e_loader_attic.c */
11 
12 #include <string.h>
13 #include <sys/stat.h>
14 #include <ctype.h> /* isdigit */
15 #include <assert.h>
16 
17 #include <openssl/core_dispatch.h>
18 #include <openssl/core_names.h>
19 #include <openssl/core_object.h>
20 #include <openssl/bio.h>
21 #include <openssl/err.h>
22 #include <openssl/params.h>
23 #include <openssl/decoder.h>
24 #include <openssl/proverr.h>
25 #include <openssl/store.h> /* The OSSL_STORE_INFO type numbers */
26 #include "internal/cryptlib.h"
27 #include "internal/o_dir.h"
28 #include "crypto/decoder.h"
29 #include "crypto/ctype.h" /* ossl_isdigit() */
30 #include "prov/implementations.h"
31 #include "prov/bio.h"
32 #include "prov/providercommon.h"
33 #include "file_store_local.h"
34 
35 DEFINE_STACK_OF(OSSL_STORE_INFO)
36 
37 #ifdef _WIN32
38 #define stat _stat
39 #endif
40 
41 #ifndef S_ISDIR
42 #define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
43 #endif
44 
45 static OSSL_FUNC_store_open_fn file_open;
46 static OSSL_FUNC_store_attach_fn file_attach;
47 static OSSL_FUNC_store_settable_ctx_params_fn file_settable_ctx_params;
48 static OSSL_FUNC_store_set_ctx_params_fn file_set_ctx_params;
49 static OSSL_FUNC_store_load_fn file_load;
50 static OSSL_FUNC_store_eof_fn file_eof;
51 static OSSL_FUNC_store_close_fn file_close;
52 
53 /*
54  * This implementation makes full use of OSSL_DECODER, and then some.
55  * It uses its own internal decoder implementation that reads DER and
56  * passes that on to the data callback; this decoder is created with
57  * internal OpenSSL functions, thereby bypassing the need for a surrounding
58  * provider.  This is ok, since this is a local decoder, not meant for
59  * public consumption.
60  * Finally, it sets up its own construct and cleanup functions.
61  *
62  * Essentially, that makes this implementation a kind of glorified decoder.
63  */
64 
65 struct file_ctx_st {
66     void *provctx;
67     char *uri; /* The URI we currently try to load */
68     enum {
69         IS_FILE = 0, /* Read file and pass results */
70         IS_DIR /* Pass directory entry names */
71     } type;
72 
73     union {
74         /* Used with |IS_FILE| */
75         struct {
76             BIO *file;
77 
78             OSSL_DECODER_CTX *decoderctx;
79             char *input_type;
80             char *propq; /* The properties we got as a parameter */
81         } file;
82 
83         /* Used with |IS_DIR| */
84         struct {
85             OPENSSL_DIR_CTX *ctx;
86             int end_reached;
87 
88             /*
89              * When a search expression is given, these are filled in.
90              * |search_name| contains the file basename to look for.
91              * The string is exactly 8 characters long.
92              */
93             char search_name[9];
94 
95             /*
96              * The directory reading utility we have combines opening with
97              * reading the first name.  To make sure we can detect the end
98              * at the right time, we read early and cache the name.
99              */
100             const char *last_entry;
101             int last_errno;
102         } dir;
103     } _;
104 
105     /* Expected object type.  May be unspecified */
106     int expected_type;
107     /* Fatal error occurred. We should indicate EOF. */
108     int fatal_error;
109 };
110 
free_file_ctx(struct file_ctx_st * ctx)111 static void free_file_ctx(struct file_ctx_st *ctx)
112 {
113     if (ctx == NULL)
114         return;
115 
116     OPENSSL_free(ctx->uri);
117     if (ctx->type != IS_DIR) {
118         OSSL_DECODER_CTX_free(ctx->_.file.decoderctx);
119         OPENSSL_free(ctx->_.file.propq);
120         OPENSSL_free(ctx->_.file.input_type);
121     }
122     OPENSSL_free(ctx);
123 }
124 
new_file_ctx(int type,const char * uri,void * provctx)125 static struct file_ctx_st *new_file_ctx(int type, const char *uri,
126     void *provctx)
127 {
128     struct file_ctx_st *ctx = NULL;
129 
130     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL
131         && (uri == NULL || (ctx->uri = OPENSSL_strdup(uri)) != NULL)) {
132         ctx->type = type;
133         ctx->provctx = provctx;
134         return ctx;
135     }
136     free_file_ctx(ctx);
137     return NULL;
138 }
139 
140 static OSSL_DECODER_CONSTRUCT file_load_construct;
141 static OSSL_DECODER_CLEANUP file_load_cleanup;
142 
143 /*-
144  *  Opening / attaching streams and directories
145  *  -------------------------------------------
146  */
147 
148 /*
149  * Function to service both file_open() and file_attach()
150  *
151  *
152  */
file_open_stream(BIO * source,const char * uri,void * provctx)153 static struct file_ctx_st *file_open_stream(BIO *source, const char *uri,
154     void *provctx)
155 {
156     struct file_ctx_st *ctx;
157 
158     if ((ctx = new_file_ctx(IS_FILE, uri, provctx)) == NULL) {
159         ERR_raise(ERR_LIB_PROV, ERR_R_PROV_LIB);
160         goto err;
161     }
162 
163     ctx->_.file.file = source;
164 
165     return ctx;
166 err:
167     free_file_ctx(ctx);
168     return NULL;
169 }
170 
file_open_dir(const char * path,const char * uri,void * provctx)171 static void *file_open_dir(const char *path, const char *uri, void *provctx)
172 {
173     struct file_ctx_st *ctx;
174 
175     if ((ctx = new_file_ctx(IS_DIR, uri, provctx)) == NULL) {
176         ERR_raise(ERR_LIB_PROV, ERR_R_PROV_LIB);
177         return NULL;
178     }
179 
180     ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
181     ctx->_.dir.last_errno = errno;
182     if (ctx->_.dir.last_entry == NULL) {
183         if (ctx->_.dir.last_errno != 0) {
184             ERR_raise_data(ERR_LIB_SYS, ctx->_.dir.last_errno,
185                 "Calling OPENSSL_DIR_read(\"%s\")", path);
186             goto err;
187         }
188         ctx->_.dir.end_reached = 1;
189     }
190     return ctx;
191 err:
192     file_close(ctx);
193     return NULL;
194 }
195 
file_open(void * provctx,const char * uri)196 static void *file_open(void *provctx, const char *uri)
197 {
198     struct file_ctx_st *ctx = NULL;
199     struct stat st;
200     struct {
201         const char *path;
202         unsigned int check_absolute : 1;
203     } path_data[2];
204     size_t path_data_n = 0, i;
205     const char *path, *p = uri, *q;
206     BIO *bio;
207 
208     ERR_set_mark();
209 
210     /*
211      * First step, just take the URI as is.
212      */
213     path_data[path_data_n].check_absolute = 0;
214     path_data[path_data_n++].path = uri;
215 
216     /*
217      * Second step, if the URI appears to start with the "file" scheme,
218      * extract the path and make that the second path to check.
219      * There's a special case if the URI also contains an authority, then
220      * the full URI shouldn't be used as a path anywhere.
221      */
222     if (CHECK_AND_SKIP_CASE_PREFIX(p, "file:")) {
223         q = p;
224         if (CHECK_AND_SKIP_CASE_PREFIX(q, "//")) {
225             path_data_n--; /* Invalidate using the full URI */
226             if (CHECK_AND_SKIP_CASE_PREFIX(q, "localhost/")
227                 || CHECK_AND_SKIP_CASE_PREFIX(q, "/")) {
228                 p = q - 1;
229             } else {
230                 ERR_clear_last_mark();
231                 ERR_raise(ERR_LIB_PROV, PROV_R_URI_AUTHORITY_UNSUPPORTED);
232                 return NULL;
233             }
234         }
235 
236         path_data[path_data_n].check_absolute = 1;
237 #ifdef _WIN32
238         /* Windows "file:" URIs with a drive letter start with a '/' */
239         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
240             char c = tolower((unsigned char)p[1]);
241 
242             if (c >= 'a' && c <= 'z') {
243                 p++;
244                 /* We know it's absolute, so no need to check */
245                 path_data[path_data_n].check_absolute = 0;
246             }
247         }
248 #endif
249         path_data[path_data_n++].path = p;
250     }
251 
252     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
253         /*
254          * If the scheme "file" was an explicit part of the URI, the path must
255          * be absolute.  So says RFC 8089
256          */
257         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
258             ERR_clear_last_mark();
259             ERR_raise_data(ERR_LIB_PROV, PROV_R_PATH_MUST_BE_ABSOLUTE,
260                 "Given path=%s", path_data[i].path);
261             return NULL;
262         }
263 
264         if (stat(path_data[i].path, &st) < 0) {
265             ERR_raise_data(ERR_LIB_SYS, errno,
266                 "calling stat(%s)",
267                 path_data[i].path);
268         } else {
269             path = path_data[i].path;
270         }
271     }
272     if (path == NULL) {
273         ERR_clear_last_mark();
274         return NULL;
275     }
276 
277     /* Successfully found a working path, clear possible collected errors */
278     ERR_pop_to_mark();
279 
280     if (S_ISDIR(st.st_mode))
281         ctx = file_open_dir(path, uri, provctx);
282     else if ((bio = BIO_new_file(path, "rb")) == NULL
283         || (ctx = file_open_stream(bio, uri, provctx)) == NULL)
284         BIO_free_all(bio);
285 
286     return ctx;
287 }
288 
file_attach(void * provctx,OSSL_CORE_BIO * cin)289 void *file_attach(void *provctx, OSSL_CORE_BIO *cin)
290 {
291     struct file_ctx_st *ctx;
292     BIO *new_bio = ossl_bio_new_from_core_bio(provctx, cin);
293 
294     if (new_bio == NULL)
295         return NULL;
296 
297     ctx = file_open_stream(new_bio, NULL, provctx);
298     if (ctx == NULL)
299         BIO_free(new_bio);
300     return ctx;
301 }
302 
303 /*-
304  *  Setting parameters
305  *  ------------------
306  */
307 
file_settable_ctx_params(void * provctx)308 static const OSSL_PARAM *file_settable_ctx_params(void *provctx)
309 {
310     static const OSSL_PARAM known_settable_ctx_params[] = {
311         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
312         OSSL_PARAM_int(OSSL_STORE_PARAM_EXPECT, NULL),
313         OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
314         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, NULL, 0),
315         OSSL_PARAM_END
316     };
317     return known_settable_ctx_params;
318 }
319 
file_set_ctx_params(void * loaderctx,const OSSL_PARAM params[])320 static int file_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
321 {
322     struct file_ctx_st *ctx = loaderctx;
323     const OSSL_PARAM *p;
324 
325     if (ossl_param_is_empty(params))
326         return 1;
327 
328     if (ctx->type != IS_DIR) {
329         /* these parameters are ignored for directories */
330         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
331         if (p != NULL) {
332             OPENSSL_free(ctx->_.file.propq);
333             ctx->_.file.propq = NULL;
334             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.propq, 0))
335                 return 0;
336         }
337         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_INPUT_TYPE);
338         if (p != NULL) {
339             OPENSSL_free(ctx->_.file.input_type);
340             ctx->_.file.input_type = NULL;
341             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.input_type, 0))
342                 return 0;
343         }
344     }
345     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_EXPECT);
346     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->expected_type))
347         return 0;
348     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
349     if (p != NULL) {
350         const unsigned char *der = NULL;
351         size_t der_len = 0;
352         X509_NAME *x509_name;
353         unsigned long hash;
354         int ok;
355 
356         if (ctx->type != IS_DIR) {
357             ERR_raise(ERR_LIB_PROV,
358                 PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
359             return 0;
360         }
361 
362         if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len)
363             || (x509_name = d2i_X509_NAME(NULL, &der, der_len)) == NULL)
364             return 0;
365         hash = X509_NAME_hash_ex(x509_name,
366             ossl_prov_ctx_get0_libctx(ctx->provctx), NULL,
367             &ok);
368         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
369             "%08lx", hash);
370         X509_NAME_free(x509_name);
371         if (ok == 0)
372             return 0;
373     }
374     return 1;
375 }
376 
377 /*-
378  *  Loading an object from a stream
379  *  -------------------------------
380  */
381 
382 struct file_load_data_st {
383     OSSL_CALLBACK *object_cb;
384     void *object_cbarg;
385 };
386 
file_load_construct(OSSL_DECODER_INSTANCE * decoder_inst,const OSSL_PARAM * params,void * construct_data)387 static int file_load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
388     const OSSL_PARAM *params, void *construct_data)
389 {
390     struct file_load_data_st *data = construct_data;
391 
392     /*
393      * At some point, we may find it justifiable to recognise PKCS#12 and
394      * handle it specially here, making |file_load()| return pass its
395      * contents one piece at ta time, like |e_loader_attic.c| does.
396      *
397      * However, that currently means parsing them out, which converts the
398      * DER encoded PKCS#12 into a bunch of EVP_PKEYs and X509s, just to
399      * have to re-encode them into DER to create an object abstraction for
400      * each of them.
401      * It's much simpler (less churn) to pass on the object abstraction we
402      * get to the load_result callback and leave it to that one to do the
403      * work.  If that's libcrypto code, we know that it has much better
404      * possibilities to handle the EVP_PKEYs and X509s without the extra
405      * churn.
406      */
407 
408     return data->object_cb(params, data->object_cbarg);
409 }
410 
file_load_cleanup(void * construct_data)411 void file_load_cleanup(void *construct_data)
412 {
413     /* Nothing to do */
414 }
415 
file_setup_decoders(struct file_ctx_st * ctx)416 static int file_setup_decoders(struct file_ctx_st *ctx)
417 {
418     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
419     const OSSL_ALGORITHM *to_algo = NULL;
420     const char *input_structure = NULL;
421     int ok = 0;
422 
423     /* Setup for this session, so only if not already done */
424     if (ctx->_.file.decoderctx == NULL) {
425         if ((ctx->_.file.decoderctx = OSSL_DECODER_CTX_new()) == NULL) {
426             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
427             goto err;
428         }
429 
430         /* Make sure the input type is set */
431         if (!OSSL_DECODER_CTX_set_input_type(ctx->_.file.decoderctx,
432                 ctx->_.file.input_type)) {
433             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
434             goto err;
435         }
436 
437         /*
438          * Where applicable, set the outermost structure name.
439          * The goal is to avoid the STORE object types that are
440          * potentially password protected but aren't interesting
441          * for this load.
442          */
443         switch (ctx->expected_type) {
444         case OSSL_STORE_INFO_PUBKEY:
445             input_structure = "SubjectPublicKeyInfo";
446             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
447                     input_structure)) {
448                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
449                 goto err;
450             }
451             break;
452         case OSSL_STORE_INFO_PKEY:
453             /*
454              * The user's OSSL_STORE_INFO_PKEY covers PKCS#8, whether encrypted
455              * or not.  The decoder will figure out whether decryption is
456              * applicable and fall back as necessary.  We just need to indicate
457              * that it is OK to try and encrypt, which may involve a password
458              * prompt, so not done unless the data type is explicit, as we
459              * might then get a password prompt for a key when reading only
460              * certs from a file.
461              */
462             input_structure = "EncryptedPrivateKeyInfo";
463             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
464                     input_structure)) {
465                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
466                 goto err;
467             }
468             break;
469         case OSSL_STORE_INFO_CERT:
470             input_structure = "Certificate";
471             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
472                     input_structure)) {
473                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
474                 goto err;
475             }
476             break;
477         case OSSL_STORE_INFO_CRL:
478             input_structure = "CertificateList";
479             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
480                     input_structure)) {
481                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
482                 goto err;
483             }
484             break;
485         default:
486             break;
487         }
488 
489         for (to_algo = ossl_any_to_obj_algorithm;
490             to_algo->algorithm_names != NULL;
491             to_algo++) {
492             OSSL_DECODER *to_obj = NULL;
493             OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
494             const char *input_type;
495 
496             /*
497              * Create the internal last resort decoder implementation
498              * together with a "decoder instance".
499              * The decoder doesn't need any identification or to be
500              * attached to any provider, since it's only used locally.
501              */
502             to_obj = ossl_decoder_from_algorithm(0, to_algo, NULL);
503             if (to_obj != NULL)
504                 to_obj_inst = ossl_decoder_instance_new_forprov(to_obj, ctx->provctx,
505                     input_structure);
506             OSSL_DECODER_free(to_obj);
507             if (to_obj_inst == NULL)
508                 goto err;
509             /*
510              * The input type has to match unless, the input type is PEM
511              * and the decoder input type is DER, in which case we'll pick
512              * up additional decoders.
513              */
514             input_type = OSSL_DECODER_INSTANCE_get_input_type(to_obj_inst);
515             if (ctx->_.file.input_type != NULL
516                 && OPENSSL_strcasecmp(input_type, ctx->_.file.input_type) != 0
517                 && (OPENSSL_strcasecmp(ctx->_.file.input_type, "PEM") != 0
518                     || OPENSSL_strcasecmp(input_type, "der") != 0)) {
519                 ossl_decoder_instance_free(to_obj_inst);
520                 continue;
521             }
522 
523             if (!ossl_decoder_ctx_add_decoder_inst(ctx->_.file.decoderctx,
524                     to_obj_inst)) {
525                 ossl_decoder_instance_free(to_obj_inst);
526                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
527                 goto err;
528             }
529         }
530         /* Add on the usual extra decoders */
531         if (!OSSL_DECODER_CTX_add_extra(ctx->_.file.decoderctx,
532                 libctx, ctx->_.file.propq)) {
533             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
534             goto err;
535         }
536 
537         /*
538          * Then install our constructor hooks, which just passes decoded
539          * data to the load callback
540          */
541         if (!OSSL_DECODER_CTX_set_construct(ctx->_.file.decoderctx,
542                 file_load_construct)
543             || !OSSL_DECODER_CTX_set_cleanup(ctx->_.file.decoderctx,
544                 file_load_cleanup)) {
545             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
546             goto err;
547         }
548     }
549 
550     ok = 1;
551 err:
552     return ok;
553 }
554 
file_load_file(struct file_ctx_st * ctx,OSSL_CALLBACK * object_cb,void * object_cbarg,OSSL_PASSPHRASE_CALLBACK * pw_cb,void * pw_cbarg)555 static int file_load_file(struct file_ctx_st *ctx,
556     OSSL_CALLBACK *object_cb, void *object_cbarg,
557     OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
558 {
559     struct file_load_data_st data;
560     int ret, err;
561 
562     /* Setup the decoders (one time shot per session */
563 
564     if (!file_setup_decoders(ctx)) {
565         ctx->fatal_error = 1;
566         return 0;
567     }
568 
569     /* Setup for this object */
570 
571     data.object_cb = object_cb;
572     data.object_cbarg = object_cbarg;
573     OSSL_DECODER_CTX_set_construct_data(ctx->_.file.decoderctx, &data);
574     OSSL_DECODER_CTX_set_passphrase_cb(ctx->_.file.decoderctx, pw_cb, pw_cbarg);
575 
576     /* Launch */
577 
578     ERR_set_mark();
579     ret = OSSL_DECODER_from_bio(ctx->_.file.decoderctx, ctx->_.file.file);
580     if (BIO_eof(ctx->_.file.file)
581         && ((err = ERR_peek_last_error()) != 0)
582         && ERR_GET_LIB(err) == ERR_LIB_OSSL_DECODER
583         && ERR_GET_REASON(err) == ERR_R_UNSUPPORTED)
584         ERR_pop_to_mark();
585     else
586         ERR_clear_last_mark();
587     return ret;
588 }
589 
590 /*-
591  *  Loading a name object from a directory
592  *  --------------------------------------
593  */
594 
file_name_to_uri(struct file_ctx_st * ctx,const char * name)595 static char *file_name_to_uri(struct file_ctx_st *ctx, const char *name)
596 {
597     char *data = NULL;
598 
599     assert(name != NULL);
600     {
601         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
602         long calculated_length = strlen(ctx->uri) + strlen(pathsep)
603             + strlen(name) + 1 /* \0 */;
604 
605         data = OPENSSL_zalloc(calculated_length);
606         if (data == NULL)
607             return NULL;
608 
609         OPENSSL_strlcat(data, ctx->uri, calculated_length);
610         OPENSSL_strlcat(data, pathsep, calculated_length);
611         OPENSSL_strlcat(data, name, calculated_length);
612     }
613     return data;
614 }
615 
file_name_check(struct file_ctx_st * ctx,const char * name)616 static int file_name_check(struct file_ctx_st *ctx, const char *name)
617 {
618     const char *p = NULL;
619     size_t len = strlen(ctx->_.dir.search_name);
620 
621     /* If there are no search criteria, all names are accepted */
622     if (ctx->_.dir.search_name[0] == '\0')
623         return 1;
624 
625     /* If the expected type isn't supported, no name is accepted */
626     if (ctx->expected_type != 0
627         && ctx->expected_type != OSSL_STORE_INFO_CERT
628         && ctx->expected_type != OSSL_STORE_INFO_CRL)
629         return 0;
630 
631     /*
632      * First, check the basename
633      */
634     if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
635         || name[len] != '.')
636         return 0;
637     p = &name[len + 1];
638 
639     /*
640      * Then, if the expected type is a CRL, check that the extension starts
641      * with 'r'
642      */
643     if (*p == 'r') {
644         p++;
645         if (ctx->expected_type != 0
646             && ctx->expected_type != OSSL_STORE_INFO_CRL)
647             return 0;
648     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
649         return 0;
650     }
651 
652     /*
653      * Last, check that the rest of the extension is a decimal number, at
654      * least one digit long.
655      */
656     if (!isdigit((unsigned char)*p))
657         return 0;
658     while (isdigit((unsigned char)*p))
659         p++;
660 
661 #ifdef __VMS
662     /*
663      * One extra step here, check for a possible generation number.
664      */
665     if (*p == ';')
666         for (p++; *p != '\0'; p++)
667             if (!ossl_isdigit((unsigned char)*p))
668                 break;
669 #endif
670 
671     /*
672      * If we've reached the end of the string at this point, we've successfully
673      * found a fitting file name.
674      */
675     return *p == '\0';
676 }
677 
file_load_dir_entry(struct file_ctx_st * ctx,OSSL_CALLBACK * object_cb,void * object_cbarg,OSSL_PASSPHRASE_CALLBACK * pw_cb,void * pw_cbarg)678 static int file_load_dir_entry(struct file_ctx_st *ctx,
679     OSSL_CALLBACK *object_cb, void *object_cbarg,
680     OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
681 {
682     /* Prepare as much as possible in advance */
683     static const int object_type = OSSL_OBJECT_NAME;
684     OSSL_PARAM object[] = {
685         OSSL_PARAM_int(OSSL_OBJECT_PARAM_TYPE, (int *)&object_type),
686         OSSL_PARAM_utf8_string(OSSL_OBJECT_PARAM_DATA, NULL, 0),
687         OSSL_PARAM_END
688     };
689     char *newname = NULL;
690     int ok;
691 
692     /* Loop until we get an error or until we have a suitable name */
693     do {
694         if (ctx->_.dir.last_entry == NULL) {
695             if (!ctx->_.dir.end_reached) {
696                 assert(ctx->_.dir.last_errno != 0);
697                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
698             }
699             /* file_eof() will tell if EOF was reached */
700             return 0;
701         }
702 
703         /* flag acceptable names */
704         if (ctx->_.dir.last_entry[0] != '.'
705             && file_name_check(ctx, ctx->_.dir.last_entry)) {
706 
707             /* If we can't allocate the new name, we fail */
708             if ((newname = file_name_to_uri(ctx, ctx->_.dir.last_entry)) == NULL)
709                 return 0;
710         }
711 
712         /*
713          * On the first call (with a NULL context), OPENSSL_DIR_read()
714          * cares about the second argument.  On the following calls, it
715          * only cares that it isn't NULL.  Therefore, we can safely give
716          * it our URI here.
717          */
718         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
719         ctx->_.dir.last_errno = errno;
720         if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
721             ctx->_.dir.end_reached = 1;
722     } while (newname == NULL);
723 
724     object[1].data = newname;
725     object[1].data_size = strlen(newname);
726     ok = object_cb(object, object_cbarg);
727     OPENSSL_free(newname);
728     return ok;
729 }
730 
731 /*-
732  *  Loading, local dispatcher
733  *  -------------------------
734  */
735 
file_load(void * loaderctx,OSSL_CALLBACK * object_cb,void * object_cbarg,OSSL_PASSPHRASE_CALLBACK * pw_cb,void * pw_cbarg)736 static int file_load(void *loaderctx,
737     OSSL_CALLBACK *object_cb, void *object_cbarg,
738     OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
739 {
740     struct file_ctx_st *ctx = loaderctx;
741 
742     switch (ctx->type) {
743     case IS_FILE:
744         return file_load_file(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
745     case IS_DIR:
746         return file_load_dir_entry(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
747     default:
748         break;
749     }
750 
751     /* ctx->type has an unexpected value */
752     assert(0);
753     return 0;
754 }
755 
756 /*-
757  *  Eof detection and closing
758  *  -------------------------
759  */
760 
file_eof(void * loaderctx)761 static int file_eof(void *loaderctx)
762 {
763     struct file_ctx_st *ctx = loaderctx;
764 
765     if (ctx->fatal_error)
766         return 1;
767 
768     switch (ctx->type) {
769     case IS_DIR:
770         return ctx->_.dir.end_reached;
771     case IS_FILE:
772         /*
773          * BIO_pending() checks any filter BIO.
774          * BIO_eof() checks the source BIO.
775          */
776         return !BIO_pending(ctx->_.file.file)
777             && BIO_eof(ctx->_.file.file);
778     }
779 
780     /* ctx->type has an unexpected value */
781     assert(0);
782     return 1;
783 }
784 
file_close_dir(struct file_ctx_st * ctx)785 static int file_close_dir(struct file_ctx_st *ctx)
786 {
787     if (ctx->_.dir.ctx != NULL)
788         OPENSSL_DIR_end(&ctx->_.dir.ctx);
789     free_file_ctx(ctx);
790     return 1;
791 }
792 
file_close_stream(struct file_ctx_st * ctx)793 static int file_close_stream(struct file_ctx_st *ctx)
794 {
795     /*
796      * This frees either the provider BIO filter (for file_attach()) OR
797      * the allocated file BIO (for file_open()).
798      */
799     BIO_free(ctx->_.file.file);
800     ctx->_.file.file = NULL;
801 
802     free_file_ctx(ctx);
803     return 1;
804 }
805 
file_close(void * loaderctx)806 static int file_close(void *loaderctx)
807 {
808     struct file_ctx_st *ctx = loaderctx;
809 
810     switch (ctx->type) {
811     case IS_DIR:
812         return file_close_dir(ctx);
813     case IS_FILE:
814         return file_close_stream(ctx);
815     }
816 
817     /* ctx->type has an unexpected value */
818     assert(0);
819     return 1;
820 }
821 
822 const OSSL_DISPATCH ossl_file_store_functions[] = {
823     { OSSL_FUNC_STORE_OPEN, (void (*)(void))file_open },
824     { OSSL_FUNC_STORE_ATTACH, (void (*)(void))file_attach },
825     { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
826         (void (*)(void))file_settable_ctx_params },
827     { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))file_set_ctx_params },
828     { OSSL_FUNC_STORE_LOAD, (void (*)(void))file_load },
829     { OSSL_FUNC_STORE_EOF, (void (*)(void))file_eof },
830     { OSSL_FUNC_STORE_CLOSE, (void (*)(void))file_close },
831     OSSL_DISPATCH_END,
832 };
833