2 * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
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
16 #include <openssl/bio.h>
17 #include <openssl/dsa.h> /* For d2i_DSAPrivateKey */
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #include <openssl/pem.h>
21 #include <openssl/pkcs12.h> /* For the PKCS8 stuff o.O */
22 #include <openssl/rsa.h> /* For d2i_RSAPrivateKey */
23 #include <openssl/safestack.h>
24 #include <openssl/store.h>
25 #include <openssl/ui.h>
26 #include <openssl/x509.h> /* For the PKCS8 stuff o.O */
27 #include "crypto/asn1.h"
28 #include "crypto/ctype.h"
29 #include "internal/o_dir.h"
30 #include "internal/cryptlib.h"
31 #include "crypto/store.h"
32 #include "store_local.h"
39 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
47 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
48 size_t maxsize, const char *prompt_info, void *data)
54 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
58 if (ui_method != NULL)
59 UI_set_method(ui, ui_method);
60 UI_add_user_data(ui, data);
62 if ((prompt = UI_construct_prompt(ui, "pass phrase",
63 prompt_info)) == NULL) {
64 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
66 } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
67 pass, 0, maxsize - 1)) {
68 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
71 switch (UI_process(ui)) {
73 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
74 OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
78 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
91 struct pem_pass_data {
92 const UI_METHOD *ui_method;
94 const char *prompt_info;
97 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
98 const char *prompt_info,
99 const UI_METHOD *ui_method, void *ui_data)
101 if (pass_data == NULL)
103 pass_data->ui_method = ui_method;
104 pass_data->data = ui_data;
105 pass_data->prompt_info = prompt_info;
109 /* This is used anywhere a pem_password_cb is needed */
110 static int file_get_pem_pass(char *buf, int num, int w, void *data)
112 struct pem_pass_data *pass_data = data;
113 char *pass = file_get_pass(pass_data->ui_method, buf, num,
114 pass_data->prompt_info, pass_data->data);
116 return pass == NULL ? 0 : strlen(pass);
120 * The file scheme decoders
121 * ------------------------
123 * Each possible data type has its own decoder, which either operates
124 * through a given PEM name, or attempts to decode to see if the blob
125 * it's given is decodable for its data type. The assumption is that
126 * only the correct data type will match the content.
130 * The try_decode function is called to check if the blob of data can
131 * be used by this handler, and if it can, decodes it into a supported
132 * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
134 * pem_name: If this blob comes from a PEM file, this holds
135 * the PEM name. If it comes from another type of
136 * file, this is NULL.
137 * pem_header: If this blob comes from a PEM file, this holds
138 * the PEM headers. If it comes from another type of
139 * file, this is NULL.
140 * blob: The blob of data to match with what this handler
142 * len: The length of the blob.
143 * handler_ctx: For a handler marked repeatable, this pointer can
144 * be used to create a context for the handler. IT IS
145 * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
146 * THIS CONTEXT APPROPRIATELY, i.e. create on first call
147 * and destroy when about to return NULL.
148 * matchcount: A pointer to an int to count matches for this data.
149 * Usually becomes 0 (no match) or 1 (match!), but may
150 * be higher in the (unlikely) event that the data matches
151 * more than one possibility. The int will always be
152 * zero when the function is called.
153 * ui_method: Application UI method for getting a password, pin
154 * or any other interactive data.
155 * ui_data: Application data to be passed to ui_method when
160 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
161 const char *pem_header,
162 const unsigned char *blob,
163 size_t len, void **handler_ctx,
165 const UI_METHOD *ui_method,
168 * The eof function should return 1 if there's no more data to be found
169 * with the handler_ctx, otherwise 0. This is only used when the handler is
172 typedef int (*file_eof_fn)(void *handler_ctx);
174 * The destroy_ctx function is used to destroy the handler_ctx that was
175 * initiated by a repeatable try_decode function. This is only used when
176 * the handler is marked repeatable.
178 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
180 typedef struct file_handler_st {
182 file_try_decode_fn try_decode;
184 file_destroy_ctx_fn destroy_ctx;
191 * PKCS#12 decoder. It operates by decoding all of the blob content,
192 * extracting all the interesting data from it and storing them internally,
193 * then serving them one piece at a time.
195 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
196 const char *pem_header,
197 const unsigned char *blob,
198 size_t len, void **pctx,
200 const UI_METHOD *ui_method,
203 OSSL_STORE_INFO *store_info = NULL;
204 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
207 /* Initial parsing */
211 if (pem_name != NULL)
212 /* No match, there is no PEM PKCS12 tag */
215 if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
217 char tpass[PEM_BUFSIZE];
218 EVP_PKEY *pkey = NULL;
220 STACK_OF(X509) *chain = NULL;
224 if (PKCS12_verify_mac(p12, "", 0)
225 || PKCS12_verify_mac(p12, NULL, 0)) {
228 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
229 "PKCS12 import password",
231 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
232 OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
235 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
236 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
237 OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
242 if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
243 OSSL_STORE_INFO *osi_pkey = NULL;
244 OSSL_STORE_INFO *osi_cert = NULL;
245 OSSL_STORE_INFO *osi_ca = NULL;
247 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
248 && (osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
249 && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0
250 && (osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
251 && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0) {
256 while(sk_X509_num(chain) > 0) {
257 X509 *ca = sk_X509_value(chain, 0);
259 if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
260 || sk_OSSL_STORE_INFO_push(ctx, osi_ca) == 0) {
265 (void)sk_X509_shift(chain);
269 OSSL_STORE_INFO_free(osi_ca);
270 OSSL_STORE_INFO_free(osi_cert);
271 OSSL_STORE_INFO_free(osi_pkey);
272 sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
275 sk_X509_pop_free(chain, X509_free);
289 store_info = sk_OSSL_STORE_INFO_shift(ctx);
295 static int eof_PKCS12(void *ctx_)
297 STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
299 return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
302 static void destroy_ctx_PKCS12(void **pctx)
304 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
306 sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
310 static FILE_HANDLER PKCS12_handler = {
319 * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
320 * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
321 * decoding process will then start over with the new blob.
323 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
324 const char *pem_header,
325 const unsigned char *blob,
326 size_t len, void **pctx,
328 const UI_METHOD *ui_method,
332 char kbuf[PEM_BUFSIZE];
334 const X509_ALGOR *dalg = NULL;
335 const ASN1_OCTET_STRING *doct = NULL;
336 OSSL_STORE_INFO *store_info = NULL;
338 unsigned char *new_data = NULL;
341 if (pem_name != NULL) {
342 if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
347 if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
352 if ((mem = BUF_MEM_new()) == NULL) {
353 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
354 ERR_R_MALLOC_FAILURE);
358 if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
359 "PKCS8 decrypt password", ui_data)) == NULL) {
360 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
361 OSSL_STORE_R_BAD_PASSWORD_READ);
365 X509_SIG_get0(p8, &dalg, &doct);
366 if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
367 &new_data, &new_data_len, 0))
370 mem->data = (char *)new_data;
371 mem->max = mem->length = (size_t)new_data_len;
375 store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
376 if (store_info == NULL) {
377 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
378 ERR_R_MALLOC_FAILURE);
389 static FILE_HANDLER PKCS8Encrypted_handler = {
391 try_decode_PKCS8Encrypted
395 * Private key decoder. Decodes all sorts of private keys, both PKCS#8
396 * encoded ones and old style PEM ones (with the key type is encoded into
399 int pem_check_suffix(const char *pem_str, const char *suffix);
400 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
401 const char *pem_header,
402 const unsigned char *blob,
403 size_t len, void **pctx,
405 const UI_METHOD *ui_method,
408 OSSL_STORE_INFO *store_info = NULL;
409 EVP_PKEY *pkey = NULL;
410 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
412 if (pem_name != NULL) {
413 if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
414 PKCS8_PRIV_KEY_INFO *p8inf =
415 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
419 pkey = EVP_PKCS82PKEY(p8inf);
420 PKCS8_PRIV_KEY_INFO_free(p8inf);
424 if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
425 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
428 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
433 #ifndef OPENSSL_NO_ENGINE
434 ENGINE *curengine = ENGINE_get_first();
436 while (curengine != NULL) {
437 ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
438 ENGINE_get_pkey_asn1_meths(curengine);
440 if (asn1meths != NULL) {
441 const int *nids = NULL;
442 int nids_n = asn1meths(curengine, NULL, &nids, 0);
444 for (i = 0; i < nids_n; i++) {
445 EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
446 EVP_PKEY *tmp_pkey = NULL;
447 const unsigned char *tmp_blob = blob;
449 if (!asn1meths(curengine, &ameth2, NULL, nids[i]))
452 || ameth2->pkey_flags & ASN1_PKEY_ALIAS)
455 tmp_pkey = d2i_PrivateKey(ameth2->pkey_id, NULL,
457 if (tmp_pkey != NULL) {
459 EVP_PKEY_free(tmp_pkey);
466 curengine = ENGINE_get_next(curengine);
470 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
471 EVP_PKEY *tmp_pkey = NULL;
472 const unsigned char *tmp_blob = blob;
474 ameth = EVP_PKEY_asn1_get0(i);
475 if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
478 tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len);
479 if (tmp_pkey != NULL) {
481 EVP_PKEY_free(tmp_pkey);
488 if (*matchcount > 1) {
497 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
498 if (store_info == NULL)
504 static FILE_HANDLER PrivateKey_handler = {
506 try_decode_PrivateKey
510 * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
512 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
513 const char *pem_header,
514 const unsigned char *blob,
515 size_t len, void **pctx,
517 const UI_METHOD *ui_method,
520 OSSL_STORE_INFO *store_info = NULL;
521 EVP_PKEY *pkey = NULL;
523 if (pem_name != NULL) {
524 if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
530 if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
532 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
538 static FILE_HANDLER PUBKEY_handler = {
544 * Key parameter decoder.
546 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
547 const char *pem_header,
548 const unsigned char *blob,
549 size_t len, void **pctx,
551 const UI_METHOD *ui_method,
554 OSSL_STORE_INFO *store_info = NULL;
556 EVP_PKEY *pkey = NULL;
557 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
560 if (pem_name != NULL) {
561 if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
567 if ((pkey = EVP_PKEY_new()) == NULL) {
568 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
573 if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
574 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
575 && ameth->param_decode != NULL
576 && ameth->param_decode(pkey, &blob, len))
580 EVP_PKEY *tmp_pkey = NULL;
582 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
583 const unsigned char *tmp_blob = blob;
585 if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) {
586 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
590 ameth = EVP_PKEY_asn1_get0(i);
591 if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
594 if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id)
595 && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL
596 && ameth->param_decode != NULL
597 && ameth->param_decode(tmp_pkey, &tmp_blob, len)) {
599 EVP_PKEY_free(tmp_pkey);
607 EVP_PKEY_free(tmp_pkey);
608 if (*matchcount == 1) {
614 store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
615 if (store_info == NULL)
621 static FILE_HANDLER params_handler = {
627 * X.509 certificate decoder.
629 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
630 const char *pem_header,
631 const unsigned char *blob,
632 size_t len, void **pctx,
634 const UI_METHOD *ui_method,
637 OSSL_STORE_INFO *store_info = NULL;
641 * In most cases, we can try to interpret the serialized data as a trusted
642 * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
643 * (just X509), but if the PEM name specifically declares it as a trusted
644 * cert, then no fallback should be engaged. |ignore_trusted| tells if
645 * the fallback can be used (1) or not (0).
647 int ignore_trusted = 1;
649 if (pem_name != NULL) {
650 if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
652 else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
653 && strcmp(pem_name, PEM_STRING_X509) != 0)
659 if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
660 || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
662 store_info = OSSL_STORE_INFO_new_CERT(cert);
665 if (store_info == NULL)
671 static FILE_HANDLER X509Certificate_handler = {
673 try_decode_X509Certificate
679 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
680 const char *pem_header,
681 const unsigned char *blob,
682 size_t len, void **pctx,
684 const UI_METHOD *ui_method,
687 OSSL_STORE_INFO *store_info = NULL;
688 X509_CRL *crl = NULL;
690 if (pem_name != NULL) {
691 if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
697 if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
699 store_info = OSSL_STORE_INFO_new_CRL(crl);
702 if (store_info == NULL)
708 static FILE_HANDLER X509CRL_handler = {
714 * To finish it all off, we collect all the handlers.
716 static const FILE_HANDLER *file_handlers[] = {
718 &PKCS8Encrypted_handler,
719 &X509Certificate_handler,
732 struct ossl_store_loader_ctx_st {
739 #define FILE_FLAG_SECMEM (1<<0)
742 struct { /* Used with is_raw and is_pem */
746 * The following are used when the handler is marked as
749 const FILE_HANDLER *last_handler;
750 void *last_handler_ctx;
752 struct { /* Used with is_dir */
753 OPENSSL_DIR_CTX *ctx;
758 * When a search expression is given, these are filled in.
759 * |search_name| contains the file basename to look for.
760 * The string is exactly 8 characters long.
765 * The directory reading utility we have combines opening with
766 * reading the first name. To make sure we can detect the end
767 * at the right time, we read early and cache the name.
769 const char *last_entry;
774 /* Expected object type. May be unspecified */
778 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
780 if (ctx->type == is_dir) {
781 OPENSSL_free(ctx->_.dir.uri);
783 if (ctx->_.file.last_handler != NULL) {
784 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
785 ctx->_.file.last_handler_ctx = NULL;
786 ctx->_.file.last_handler = NULL;
792 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
794 const UI_METHOD *ui_method,
797 OSSL_STORE_LOADER_CTX *ctx = NULL;
801 unsigned int check_absolute:1;
803 size_t path_data_n = 0, i;
807 * First step, just take the URI as is.
809 path_data[path_data_n].check_absolute = 0;
810 path_data[path_data_n++].path = uri;
813 * Second step, if the URI appears to start with the 'file' scheme,
814 * extract the path and make that the second path to check.
815 * There's a special case if the URI also contains an authority, then
816 * the full URI shouldn't be used as a path anywhere.
818 if (strncasecmp(uri, "file:", 5) == 0) {
819 const char *p = &uri[5];
821 if (strncmp(&uri[5], "//", 2) == 0) {
822 path_data_n--; /* Invalidate using the full URI */
823 if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
825 } else if (uri[7] == '/') {
828 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
829 OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED);
834 path_data[path_data_n].check_absolute = 1;
836 /* Windows file: URIs with a drive letter start with a / */
837 if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
838 char c = ossl_tolower(p[1]);
840 if (c >= 'a' && c <= 'z') {
842 /* We know it's absolute, so no need to check */
843 path_data[path_data_n].check_absolute = 0;
847 path_data[path_data_n++].path = p;
851 for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
853 * If the scheme "file" was an explicit part of the URI, the path must
854 * be absolute. So says RFC 8089
856 if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
857 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
858 OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
859 ERR_add_error_data(1, path_data[i].path);
863 if (stat(path_data[i].path, &st) < 0) {
864 SYSerr(SYS_F_STAT, errno);
865 ERR_add_error_data(1, path_data[i].path);
867 path = path_data[i].path;
874 /* Successfully found a working path, clear possible collected errors */
877 ctx = OPENSSL_zalloc(sizeof(*ctx));
879 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
883 if (S_ISDIR(st.st_mode)) {
885 * Try to copy everything, even if we know that some of them must be
886 * NULL for the moment. This prevents errors in the future, when more
887 * components may be used.
889 ctx->_.dir.uri = OPENSSL_strdup(uri);
892 if (ctx->_.dir.uri == NULL)
895 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
896 ctx->_.dir.last_errno = errno;
897 if (ctx->_.dir.last_entry == NULL) {
898 if (ctx->_.dir.last_errno != 0) {
900 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
901 errno = ctx->_.dir.last_errno;
902 if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
903 ERR_add_error_data(1, errbuf);
906 ctx->_.dir.end_reached = 1;
910 char peekbuf[4096] = { 0, };
912 if ((buff = BIO_new(BIO_f_buffer())) == NULL
913 || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
918 ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
919 if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
920 peekbuf[sizeof(peekbuf) - 1] = '\0';
921 if (strstr(peekbuf, "-----BEGIN ") != NULL)
928 OSSL_STORE_LOADER_CTX_free(ctx);
932 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
937 case OSSL_STORE_C_USE_SECMEM:
939 int on = *(va_arg(args, int *));
943 ctx->flags &= ~FILE_FLAG_SECMEM;
946 ctx->flags |= FILE_FLAG_SECMEM;
949 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
950 ERR_R_PASSED_INVALID_ARGUMENT);
963 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
965 ctx->expected_type = expected;
969 static int file_find(OSSL_STORE_LOADER_CTX *ctx, OSSL_STORE_SEARCH *search)
972 * If ctx == NULL, the library is looking to know if this loader supports
973 * the given search type.
976 if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
977 unsigned long hash = 0;
982 if (ctx->type != is_dir) {
983 OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
984 OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
988 hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
989 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
995 OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
996 OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE);
1000 /* Internal function to decode an already opened PEM file */
1001 OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp)
1003 OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1006 OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
1007 ERR_R_MALLOC_FAILURE);
1011 ctx->_.file.file = bp;
1017 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1018 const char *pem_name,
1019 const char *pem_header,
1020 unsigned char *data, size_t len,
1021 const UI_METHOD *ui_method,
1022 void *ui_data, int *matchcount)
1024 OSSL_STORE_INFO *result = NULL;
1025 BUF_MEM *new_mem = NULL;
1026 char *new_pem_name = NULL;
1032 void *handler_ctx = NULL;
1033 const FILE_HANDLER **matching_handlers =
1034 OPENSSL_zalloc(sizeof(*matching_handlers)
1035 * OSSL_NELEM(file_handlers));
1037 if (matching_handlers == NULL) {
1038 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
1039 ERR_R_MALLOC_FAILURE);
1044 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1045 const FILE_HANDLER *handler = file_handlers[i];
1046 int try_matchcount = 0;
1047 void *tmp_handler_ctx = NULL;
1048 OSSL_STORE_INFO *tmp_result =
1049 handler->try_decode(pem_name, pem_header, data, len,
1050 &tmp_handler_ctx, &try_matchcount,
1051 ui_method, ui_data);
1053 if (try_matchcount > 0) {
1055 matching_handlers[*matchcount] = handler;
1058 handler->destroy_ctx(&handler_ctx);
1059 handler_ctx = tmp_handler_ctx;
1061 if ((*matchcount += try_matchcount) > 1) {
1062 /* more than one match => ambiguous, kill any result */
1063 OSSL_STORE_INFO_free(result);
1064 OSSL_STORE_INFO_free(tmp_result);
1065 if (handler->destroy_ctx != NULL)
1066 handler->destroy_ctx(&handler_ctx);
1072 result = tmp_result;
1076 if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1077 ctx->_.file.last_handler = matching_handlers[0];
1078 ctx->_.file.last_handler_ctx = handler_ctx;
1081 OPENSSL_free(matching_handlers);
1085 OPENSSL_free(new_pem_name);
1086 BUF_MEM_free(new_mem);
1089 && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
1090 pem_name = new_pem_name =
1091 ossl_store_info_get0_EMBEDDED_pem_name(result);
1092 new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
1093 data = (unsigned char *)new_mem->data;
1094 len = new_mem->length;
1095 OPENSSL_free(result);
1106 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1107 const UI_METHOD *ui_method,
1110 OSSL_STORE_INFO *result = NULL;
1111 int try_matchcount = 0;
1113 if (ctx->_.file.last_handler != NULL) {
1115 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1116 &ctx->_.file.last_handler_ctx,
1118 ui_method, ui_data);
1120 if (result == NULL) {
1121 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1122 ctx->_.file.last_handler_ctx = NULL;
1123 ctx->_.file.last_handler = NULL;
1129 static void pem_free_flag(void *pem_data, int secure, size_t num)
1132 OPENSSL_secure_clear_free(pem_data, num);
1134 OPENSSL_free(pem_data);
1136 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1137 unsigned char **data, long *len,
1138 const UI_METHOD *ui_method,
1139 void *ui_data, int secure)
1142 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1143 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1144 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1150 * 10 is the number of characters in "Proc-Type:", which
1151 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1152 * If the PEM header has less characters than that, it's
1153 * not worth spending cycles on it.
1155 if (strlen(*pem_header) > 10) {
1156 EVP_CIPHER_INFO cipher;
1157 struct pem_pass_data pass_data;
1159 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1160 || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
1161 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1169 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1171 BUF_MEM *mem = NULL;
1173 if (asn1_d2i_read_bio(bp, &mem) < 0)
1176 *data = (unsigned char *)mem->data;
1177 *len = (long)mem->length;
1183 static int ends_with_dirsep(const char *uri)
1186 uri += strlen(uri) - 1;
1188 if (*uri == ']' || *uri == '>' || *uri == ':')
1190 #elif defined _WIN32
1197 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1200 assert(name != NULL);
1201 assert(data != NULL);
1203 const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
1204 long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
1205 + strlen(name) + 1 /* \0 */;
1207 *data = OPENSSL_zalloc(calculated_length);
1208 if (*data == NULL) {
1209 OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1213 OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1214 OPENSSL_strlcat(*data, pathsep, calculated_length);
1215 OPENSSL_strlcat(*data, name, calculated_length);
1220 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1222 const char *p = NULL;
1224 /* If there are no search criteria, all names are accepted */
1225 if (ctx->_.dir.search_name[0] == '\0')
1228 /* If the expected type isn't supported, no name is accepted */
1229 if (ctx->expected_type != 0
1230 && ctx->expected_type != OSSL_STORE_INFO_CERT
1231 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1235 * First, check the basename
1237 if (strncasecmp(name, ctx->_.dir.search_name,
1238 sizeof(ctx->_.dir.search_name) - 1) != 0
1239 || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1241 p = &name[sizeof(ctx->_.dir.search_name)];
1244 * Then, if the expected type is a CRL, check that the extension starts
1249 if (ctx->expected_type != 0
1250 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1252 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1257 * Last, check that the rest of the extension is a decimal number, at
1258 * least one digit long.
1260 if (!ossl_isdigit(*p))
1262 while (ossl_isdigit(*p))
1267 * One extra step here, check for a possible generation number.
1270 for (p++; *p != '\0'; p++)
1271 if (!ossl_isdigit(*p))
1276 * If we've reached the end of the string at this point, we've successfully
1277 * found a fitting file name.
1282 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1283 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1284 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1285 const UI_METHOD *ui_method, void *ui_data)
1287 OSSL_STORE_INFO *result = NULL;
1292 if (ctx->type == is_dir) {
1294 char *newname = NULL;
1296 if (ctx->_.dir.last_entry == NULL) {
1297 if (!ctx->_.dir.end_reached) {
1299 assert(ctx->_.dir.last_errno != 0);
1300 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1301 errno = ctx->_.dir.last_errno;
1303 if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
1304 ERR_add_error_data(1, errbuf);
1309 if (ctx->_.dir.last_entry[0] != '.'
1310 && file_name_check(ctx, ctx->_.dir.last_entry)
1311 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1315 * On the first call (with a NULL context), OPENSSL_DIR_read()
1316 * cares about the second argument. On the following calls, it
1317 * only cares that it isn't NULL. Therefore, we can safely give
1320 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1322 ctx->_.dir.last_errno = errno;
1323 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1324 ctx->_.dir.end_reached = 1;
1327 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1328 OPENSSL_free(newname);
1329 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1332 } while (result == NULL && !file_eof(ctx));
1334 int matchcount = -1;
1337 result = file_load_try_repeat(ctx, ui_method, ui_data);
1345 char *pem_name = NULL; /* PEM record name */
1346 char *pem_header = NULL; /* PEM record header */
1347 unsigned char *data = NULL; /* DER encoded data */
1348 long len = 0; /* DER encoded data length */
1351 if (ctx->type == is_pem) {
1352 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1353 &data, &len, ui_method, ui_data,
1354 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1359 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1365 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1366 ui_method, ui_data, &matchcount);
1372 * If a PEM name matches more than one handler, the handlers are
1375 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1380 if (matchcount > 1) {
1381 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1382 OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1383 } else if (matchcount == 1) {
1385 * If there are other errors on the stack, they already show
1386 * what the problem is.
1388 if (ERR_peek_error() == 0) {
1389 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1390 OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1391 if (pem_name != NULL)
1392 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1399 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1400 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1401 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1402 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1404 /* We bail out on ambiguity */
1409 && ctx->expected_type != 0
1410 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1411 OSSL_STORE_INFO_free(result);
1419 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1421 return ctx->errcnt > 0;
1424 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1426 if (ctx->type == is_dir)
1427 return ctx->_.dir.end_reached;
1429 if (ctx->_.file.last_handler != NULL
1430 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1432 return BIO_eof(ctx->_.file.file);
1435 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1437 if (ctx->type == is_dir) {
1438 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1440 BIO_free_all(ctx->_.file.file);
1442 OSSL_STORE_LOADER_CTX_free(ctx);
1446 int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx)
1448 OSSL_STORE_LOADER_CTX_free(ctx);
1452 static OSSL_STORE_LOADER file_loader =
1466 static void store_file_loader_deinit(void)
1468 ossl_store_unregister_loader_int(file_loader.scheme);
1471 int ossl_store_file_loader_init(void)
1473 int ret = ossl_store_register_loader_int(&file_loader);
1475 OPENSSL_atexit(store_file_loader_deinit);