2 * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
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
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 "internal/pem_int.h"
22 #include <openssl/pkcs12.h> /* For the PKCS8 stuff o.O */
23 #include <openssl/rsa.h> /* For d2i_RSAPrivateKey */
24 #include <openssl/safestack.h>
25 #include <openssl/store.h>
26 #include <openssl/ui.h>
27 #include <openssl/x509.h> /* For the PKCS8 stuff o.O */
28 #include "crypto/asn1.h"
29 #include "crypto/ctype.h"
30 #include "internal/o_dir.h"
31 #include "internal/cryptlib.h"
32 #include "crypto/store.h"
33 #include "crypto/evp.h"
34 #include "store_local.h"
43 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
51 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
52 size_t maxsize, const char *desc, const char *info,
59 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
63 if (ui_method != NULL)
64 UI_set_method(ui, ui_method);
65 UI_add_user_data(ui, data);
67 if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
68 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
70 } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
71 pass, 0, maxsize - 1)) {
72 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
75 switch (UI_process(ui)) {
77 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
78 OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
82 OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
95 struct pem_pass_data {
96 const UI_METHOD *ui_method;
98 const char *prompt_desc;
99 const char *prompt_info;
102 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
103 const char *desc, const char *info,
104 const UI_METHOD *ui_method, void *ui_data)
106 if (pass_data == NULL)
108 pass_data->ui_method = ui_method;
109 pass_data->data = ui_data;
110 pass_data->prompt_desc = desc;
111 pass_data->prompt_info = info;
115 /* This is used anywhere a pem_password_cb is needed */
116 static int file_get_pem_pass(char *buf, int num, int w, void *data)
118 struct pem_pass_data *pass_data = data;
119 char *pass = file_get_pass(pass_data->ui_method, buf, num,
120 pass_data->prompt_desc, pass_data->prompt_info,
123 return pass == NULL ? 0 : strlen(pass);
127 * The file scheme decoders
128 * ------------------------
130 * Each possible data type has its own decoder, which either operates
131 * through a given PEM name, or attempts to decode to see if the blob
132 * it's given is decodable for its data type. The assumption is that
133 * only the correct data type will match the content.
137 * The try_decode function is called to check if the blob of data can
138 * be used by this handler, and if it can, decodes it into a supported
139 * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
141 * pem_name: If this blob comes from a PEM file, this holds
142 * the PEM name. If it comes from another type of
143 * file, this is NULL.
144 * pem_header: If this blob comes from a PEM file, this holds
145 * the PEM headers. If it comes from another type of
146 * file, this is NULL.
147 * blob: The blob of data to match with what this handler
149 * len: The length of the blob.
150 * handler_ctx: For a handler marked repeatable, this pointer can
151 * be used to create a context for the handler. IT IS
152 * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
153 * THIS CONTEXT APPROPRIATELY, i.e. create on first call
154 * and destroy when about to return NULL.
155 * matchcount: A pointer to an int to count matches for this data.
156 * Usually becomes 0 (no match) or 1 (match!), but may
157 * be higher in the (unlikely) event that the data matches
158 * more than one possibility. The int will always be
159 * zero when the function is called.
160 * ui_method: Application UI method for getting a password, pin
161 * or any other interactive data.
162 * ui_data: Application data to be passed to ui_method when
164 * libctx: The library context to be used if applicable
165 * propq: The property query string for any algorithm fetches
169 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
170 const char *pem_header,
171 const unsigned char *blob,
172 size_t len, void **handler_ctx,
174 const UI_METHOD *ui_method,
175 void *ui_data, const char *uri,
179 * The eof function should return 1 if there's no more data to be found
180 * with the handler_ctx, otherwise 0. This is only used when the handler is
183 typedef int (*file_eof_fn)(void *handler_ctx);
185 * The destroy_ctx function is used to destroy the handler_ctx that was
186 * initiated by a repeatable try_decode function. This is only used when
187 * the handler is marked repeatable.
189 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
191 typedef struct file_handler_st {
193 file_try_decode_fn try_decode;
195 file_destroy_ctx_fn destroy_ctx;
202 * PKCS#12 decoder. It operates by decoding all of the blob content,
203 * extracting all the interesting data from it and storing them internally,
204 * then serving them one piece at a time.
206 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
207 const char *pem_header,
208 const unsigned char *blob,
209 size_t len, void **pctx,
211 const UI_METHOD *ui_method,
212 void *ui_data, const char *uri,
216 OSSL_STORE_INFO *store_info = NULL;
217 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
220 /* Initial parsing */
223 if (pem_name != NULL)
224 /* No match, there is no PEM PKCS12 tag */
227 if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
229 char tpass[PEM_BUFSIZE];
230 EVP_PKEY *pkey = NULL;
232 STACK_OF(X509) *chain = NULL;
236 if (PKCS12_verify_mac(p12, "", 0)
237 || PKCS12_verify_mac(p12, NULL, 0)) {
240 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
241 "PKCS12 import pass phrase", uri,
243 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
244 OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
247 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
248 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
249 OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
254 if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
255 OSSL_STORE_INFO *osi_pkey = NULL;
256 OSSL_STORE_INFO *osi_cert = NULL;
257 OSSL_STORE_INFO *osi_ca = NULL;
260 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
262 if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
263 /* clearing pkey here avoids case distinctions */
264 && (pkey = NULL) == NULL
265 && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
270 if (ok && cert != NULL) {
271 if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
272 /* clearing cert here avoids case distinctions */
273 && (cert = NULL) == NULL
274 && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
279 while (ok && sk_X509_num(chain) > 0) {
280 X509 *ca = sk_X509_value(chain, 0);
282 if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
283 && sk_X509_shift(chain) != NULL
284 && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
292 sk_X509_pop_free(chain, X509_free);
293 OSSL_STORE_INFO_free(osi_pkey);
294 OSSL_STORE_INFO_free(osi_cert);
295 OSSL_STORE_INFO_free(osi_ca);
297 sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
310 store_info = sk_OSSL_STORE_INFO_shift(ctx);
314 static int eof_PKCS12(void *ctx_)
316 STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
318 return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
321 static void destroy_ctx_PKCS12(void **pctx)
323 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
325 sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
329 static FILE_HANDLER PKCS12_handler = {
338 * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
339 * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
340 * decoding process will then start over with the new blob.
342 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
343 const char *pem_header,
344 const unsigned char *blob,
345 size_t len, void **pctx,
347 const UI_METHOD *ui_method,
354 char kbuf[PEM_BUFSIZE];
356 const X509_ALGOR *dalg = NULL;
357 const ASN1_OCTET_STRING *doct = NULL;
358 OSSL_STORE_INFO *store_info = NULL;
360 unsigned char *new_data = NULL;
363 if (pem_name != NULL) {
364 if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
369 if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
374 if ((mem = BUF_MEM_new()) == NULL) {
375 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
376 ERR_R_MALLOC_FAILURE);
380 if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
381 "PKCS8 decrypt pass phrase", uri,
383 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
384 OSSL_STORE_R_BAD_PASSWORD_READ);
388 X509_SIG_get0(p8, &dalg, &doct);
389 if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
390 &new_data, &new_data_len, 0))
393 mem->data = (char *)new_data;
394 mem->max = mem->length = (size_t)new_data_len;
397 store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
398 if (store_info == NULL) {
399 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
400 ERR_R_MALLOC_FAILURE);
411 static FILE_HANDLER PKCS8Encrypted_handler = {
413 try_decode_PKCS8Encrypted
417 * Private key decoder. Decodes all sorts of private keys, both PKCS#8
418 * encoded ones and old style PEM ones (with the key type is encoded into
421 int pem_check_suffix(const char *pem_str, const char *suffix);
422 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
423 const char *pem_header,
424 const unsigned char *blob,
425 size_t len, void **pctx,
427 const UI_METHOD *ui_method,
428 void *ui_data, const char *uri,
432 OSSL_STORE_INFO *store_info = NULL;
433 EVP_PKEY *pkey = NULL;
434 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
436 if (pem_name != NULL) {
437 if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
438 PKCS8_PRIV_KEY_INFO *p8inf =
439 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
443 pkey = evp_pkcs82pkey_int(p8inf, libctx, propq);
444 PKCS8_PRIV_KEY_INFO_free(p8inf);
448 if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
449 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
452 pkey = d2i_PrivateKey_ex(ameth->pkey_id, NULL, &blob, len,
458 #ifndef OPENSSL_NO_ENGINE
459 ENGINE *curengine = ENGINE_get_first();
461 while (curengine != NULL) {
462 ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
463 ENGINE_get_pkey_asn1_meths(curengine);
465 if (asn1meths != NULL) {
466 const int *nids = NULL;
467 int nids_n = asn1meths(curengine, NULL, &nids, 0);
469 for (i = 0; i < nids_n; i++) {
470 EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
471 EVP_PKEY *tmp_pkey = NULL;
472 const unsigned char *tmp_blob = blob;
474 if (!asn1meths(curengine, &ameth2, NULL, nids[i]))
477 || ameth2->pkey_flags & ASN1_PKEY_ALIAS)
481 d2i_PrivateKey_ex(ameth2->pkey_id, NULL,
482 &tmp_blob, len, libctx, propq);
483 if (tmp_pkey != NULL) {
485 EVP_PKEY_free(tmp_pkey);
492 curengine = ENGINE_get_next(curengine);
496 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
497 EVP_PKEY *tmp_pkey = NULL;
498 const unsigned char *tmp_blob = blob;
500 ameth = EVP_PKEY_asn1_get0(i);
501 if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
504 tmp_pkey = d2i_PrivateKey_ex(ameth->pkey_id, NULL, &tmp_blob, len,
506 if (tmp_pkey != NULL) {
508 EVP_PKEY_free(tmp_pkey);
515 if (*matchcount > 1) {
524 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
525 if (store_info == NULL)
531 static FILE_HANDLER PrivateKey_handler = {
533 try_decode_PrivateKey
537 * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
539 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
540 const char *pem_header,
541 const unsigned char *blob,
542 size_t len, void **pctx,
544 const UI_METHOD *ui_method,
545 void *ui_data, const char *uri,
549 OSSL_STORE_INFO *store_info = NULL;
550 EVP_PKEY *pkey = NULL;
552 if (pem_name != NULL) {
553 if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
559 if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
561 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
567 static FILE_HANDLER PUBKEY_handler = {
573 * Key parameter decoder.
575 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
576 const char *pem_header,
577 const unsigned char *blob,
578 size_t len, void **pctx,
580 const UI_METHOD *ui_method,
581 void *ui_data, const char *uri,
585 OSSL_STORE_INFO *store_info = NULL;
587 EVP_PKEY *pkey = NULL;
588 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
591 if (pem_name != NULL) {
592 if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
598 if ((pkey = EVP_PKEY_new()) == NULL) {
599 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
604 if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
605 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
606 && ameth->param_decode != NULL
607 && ameth->param_decode(pkey, &blob, len))
611 EVP_PKEY *tmp_pkey = NULL;
613 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
614 const unsigned char *tmp_blob = blob;
616 if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) {
617 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
621 ameth = EVP_PKEY_asn1_get0(i);
622 if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
625 if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id)
626 && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL
627 && ameth->param_decode != NULL
628 && ameth->param_decode(tmp_pkey, &tmp_blob, len)) {
630 EVP_PKEY_free(tmp_pkey);
638 EVP_PKEY_free(tmp_pkey);
639 if (*matchcount == 1) {
645 store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
646 if (store_info == NULL)
652 static FILE_HANDLER params_handler = {
658 * X.509 certificate decoder.
660 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
661 const char *pem_header,
662 const unsigned char *blob,
663 size_t len, void **pctx,
665 const UI_METHOD *ui_method,
671 OSSL_STORE_INFO *store_info = NULL;
675 * In most cases, we can try to interpret the serialized data as a trusted
676 * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
677 * (just X509), but if the PEM name specifically declares it as a trusted
678 * cert, then no fallback should be engaged. |ignore_trusted| tells if
679 * the fallback can be used (1) or not (0).
681 int ignore_trusted = 1;
683 if (pem_name != NULL) {
684 if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
686 else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
687 && strcmp(pem_name, PEM_STRING_X509) != 0)
693 if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
694 || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
696 store_info = OSSL_STORE_INFO_new_CERT(cert);
699 if (store_info == NULL)
705 static FILE_HANDLER X509Certificate_handler = {
707 try_decode_X509Certificate
713 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
714 const char *pem_header,
715 const unsigned char *blob,
716 size_t len, void **pctx,
718 const UI_METHOD *ui_method,
719 void *ui_data, const char *uri,
723 OSSL_STORE_INFO *store_info = NULL;
724 X509_CRL *crl = NULL;
726 if (pem_name != NULL) {
727 if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
733 if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
735 store_info = OSSL_STORE_INFO_new_CRL(crl);
738 if (store_info == NULL)
744 static FILE_HANDLER X509CRL_handler = {
750 * To finish it all off, we collect all the handlers.
752 static const FILE_HANDLER *file_handlers[] = {
754 &PKCS8Encrypted_handler,
755 &X509Certificate_handler,
768 struct ossl_store_loader_ctx_st {
769 char *uri; /* The URI we currently try to load */
776 #define FILE_FLAG_SECMEM (1<<0)
777 #define FILE_FLAG_ATTACHED (1<<1)
780 struct { /* Used with is_raw and is_pem */
784 * The following are used when the handler is marked as
787 const FILE_HANDLER *last_handler;
788 void *last_handler_ctx;
790 struct { /* Used with is_dir */
791 OPENSSL_DIR_CTX *ctx;
795 * When a search expression is given, these are filled in.
796 * |search_name| contains the file basename to look for.
797 * The string is exactly 8 characters long.
802 * The directory reading utility we have combines opening with
803 * reading the first name. To make sure we can detect the end
804 * at the right time, we read early and cache the name.
806 const char *last_entry;
811 /* Expected object type. May be unspecified */
818 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
823 OPENSSL_free(ctx->uri);
824 if (ctx->type != is_dir) {
825 if (ctx->_.file.last_handler != NULL) {
826 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
827 ctx->_.file.last_handler_ctx = NULL;
828 ctx->_.file.last_handler = NULL;
831 OPENSSL_free(ctx->propq);
835 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
838 char peekbuf[4096] = { 0, };
840 if ((buff = BIO_new(BIO_f_buffer())) == NULL)
843 ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
844 if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
845 peekbuf[sizeof(peekbuf) - 1] = '\0';
846 if (strstr(peekbuf, "-----BEGIN ") != NULL)
852 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
854 const UI_METHOD *ui_method,
857 OSSL_STORE_LOADER_CTX *ctx = NULL;
861 unsigned int check_absolute:1;
863 size_t path_data_n = 0, i;
867 * First step, just take the URI as is.
869 path_data[path_data_n].check_absolute = 0;
870 path_data[path_data_n++].path = uri;
873 * Second step, if the URI appears to start with the 'file' scheme,
874 * extract the path and make that the second path to check.
875 * There's a special case if the URI also contains an authority, then
876 * the full URI shouldn't be used as a path anywhere.
878 if (strncasecmp(uri, "file:", 5) == 0) {
879 const char *p = &uri[5];
881 if (strncmp(&uri[5], "//", 2) == 0) {
882 path_data_n--; /* Invalidate using the full URI */
883 if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
885 } else if (uri[7] == '/') {
888 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
889 OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED);
894 path_data[path_data_n].check_absolute = 1;
896 /* Windows file: URIs with a drive letter start with a / */
897 if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
898 char c = ossl_tolower(p[1]);
900 if (c >= 'a' && c <= 'z') {
902 /* We know it's absolute, so no need to check */
903 path_data[path_data_n].check_absolute = 0;
907 path_data[path_data_n++].path = p;
911 for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
913 * If the scheme "file" was an explicit part of the URI, the path must
914 * be absolute. So says RFC 8089
916 if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
917 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
918 OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
919 ERR_add_error_data(1, path_data[i].path);
923 if (stat(path_data[i].path, &st) < 0) {
924 ERR_raise_data(ERR_LIB_SYS, errno,
928 path = path_data[i].path;
935 /* Successfully found a working path, clear possible collected errors */
938 ctx = OPENSSL_zalloc(sizeof(*ctx));
940 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
943 ctx->uri = OPENSSL_strdup(uri);
944 if (ctx->uri == NULL) {
945 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
949 if (S_ISDIR(st.st_mode)) {
951 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
952 ctx->_.dir.last_errno = errno;
953 if (ctx->_.dir.last_entry == NULL) {
954 if (ctx->_.dir.last_errno != 0) {
956 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
957 errno = ctx->_.dir.last_errno;
958 if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
959 ERR_add_error_data(1, errbuf);
962 ctx->_.dir.end_reached = 1;
964 } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
965 || !file_find_type(ctx)) {
966 BIO_free_all(ctx->_.file.file);
972 OSSL_STORE_LOADER_CTX_free(ctx);
976 static OSSL_STORE_LOADER_CTX *file_attach(const OSSL_STORE_LOADER *loader,
977 BIO *bp, OPENSSL_CTX *libctx,
979 const UI_METHOD *ui_method,
982 OSSL_STORE_LOADER_CTX *ctx;
984 if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
985 || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
986 OSSL_STOREerr(OSSL_STORE_F_FILE_ATTACH, ERR_R_MALLOC_FAILURE);
987 OSSL_STORE_LOADER_CTX_free(ctx);
991 ctx->libctx = libctx;
992 ctx->flags |= FILE_FLAG_ATTACHED;
993 ctx->_.file.file = bp;
994 if (!file_find_type(ctx)) {
996 ctx->_.file.file = NULL;
997 OSSL_STORE_LOADER_CTX_free(ctx);
1004 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1009 case OSSL_STORE_C_USE_SECMEM:
1011 int on = *(va_arg(args, int *));
1015 ctx->flags &= ~FILE_FLAG_SECMEM;
1018 ctx->flags |= FILE_FLAG_SECMEM;
1021 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
1022 ERR_R_PASSED_INVALID_ARGUMENT);
1035 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1037 ctx->expected_type = expected;
1041 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1042 const OSSL_STORE_SEARCH *search)
1045 * If ctx == NULL, the library is looking to know if this loader supports
1046 * the given search type.
1049 if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1050 unsigned long hash = 0;
1055 if (ctx->type != is_dir) {
1056 OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
1057 OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1061 hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
1062 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1068 OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
1069 OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE);
1073 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1074 const char *pem_name,
1075 const char *pem_header,
1076 unsigned char *data, size_t len,
1077 const UI_METHOD *ui_method,
1078 void *ui_data, int *matchcount)
1080 OSSL_STORE_INFO *result = NULL;
1081 BUF_MEM *new_mem = NULL;
1082 char *new_pem_name = NULL;
1088 void *handler_ctx = NULL;
1089 const FILE_HANDLER **matching_handlers =
1090 OPENSSL_zalloc(sizeof(*matching_handlers)
1091 * OSSL_NELEM(file_handlers));
1093 if (matching_handlers == NULL) {
1094 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
1095 ERR_R_MALLOC_FAILURE);
1100 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1101 const FILE_HANDLER *handler = file_handlers[i];
1102 int try_matchcount = 0;
1103 void *tmp_handler_ctx = NULL;
1104 OSSL_STORE_INFO *tmp_result =
1105 handler->try_decode(pem_name, pem_header, data, len,
1106 &tmp_handler_ctx, &try_matchcount,
1107 ui_method, ui_data, ctx->uri,
1108 ctx->libctx, ctx->propq);
1110 if (try_matchcount > 0) {
1112 matching_handlers[*matchcount] = handler;
1115 handler->destroy_ctx(&handler_ctx);
1116 handler_ctx = tmp_handler_ctx;
1118 if ((*matchcount += try_matchcount) > 1) {
1119 /* more than one match => ambiguous, kill any result */
1120 OSSL_STORE_INFO_free(result);
1121 OSSL_STORE_INFO_free(tmp_result);
1122 if (handler->destroy_ctx != NULL)
1123 handler->destroy_ctx(&handler_ctx);
1129 result = tmp_result;
1133 if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1134 ctx->_.file.last_handler = matching_handlers[0];
1135 ctx->_.file.last_handler_ctx = handler_ctx;
1138 OPENSSL_free(matching_handlers);
1142 OPENSSL_free(new_pem_name);
1143 BUF_MEM_free(new_mem);
1146 && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
1147 pem_name = new_pem_name =
1148 ossl_store_info_get0_EMBEDDED_pem_name(result);
1149 new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
1150 data = (unsigned char *)new_mem->data;
1151 len = new_mem->length;
1152 OPENSSL_free(result);
1163 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1164 const UI_METHOD *ui_method,
1167 OSSL_STORE_INFO *result = NULL;
1168 int try_matchcount = 0;
1170 if (ctx->_.file.last_handler != NULL) {
1172 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1173 &ctx->_.file.last_handler_ctx,
1175 ui_method, ui_data, ctx->uri,
1176 ctx->libctx, ctx->propq);
1178 if (result == NULL) {
1179 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1180 ctx->_.file.last_handler_ctx = NULL;
1181 ctx->_.file.last_handler = NULL;
1187 static void pem_free_flag(void *pem_data, int secure, size_t num)
1190 OPENSSL_secure_clear_free(pem_data, num);
1192 OPENSSL_free(pem_data);
1194 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1195 unsigned char **data, long *len,
1196 const UI_METHOD *ui_method, void *ui_data,
1197 const char *uri, int secure)
1200 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1201 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1202 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1208 * 10 is the number of characters in "Proc-Type:", which
1209 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1210 * If the PEM header has less characters than that, it's
1211 * not worth spending cycles on it.
1213 if (strlen(*pem_header) > 10) {
1214 EVP_CIPHER_INFO cipher;
1215 struct pem_pass_data pass_data;
1217 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1218 || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1220 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1228 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1230 #ifdef OPENSSL_NO_DSA
1233 OSSL_STORE_INFO *result = NULL;
1237 unsigned int magic = 0, bitlen = 0;
1239 unsigned char peekbuf[16] = { 0, };
1240 const unsigned char *p = peekbuf;
1242 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1244 if (!ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1252 EVP_PKEY *tmp = ispub
1253 ? b2i_PublicKey_bio(bp)
1254 : b2i_PrivateKey_bio(bp);
1257 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1267 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1268 void *ui_data, const char *uri,
1271 #if defined(OPENSSL_NO_DSA) || defined(OPENSSL_NO_RC4)
1274 OSSL_STORE_INFO *result = NULL;
1277 unsigned int saltlen = 0, keylen = 0;
1278 unsigned char peekbuf[24] = { 0, };
1279 const unsigned char *p = peekbuf;
1281 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1283 if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1290 EVP_PKEY *tmp = NULL;
1291 struct pem_pass_data pass_data;
1293 if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1295 || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1296 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1306 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1308 BUF_MEM *mem = NULL;
1310 if (asn1_d2i_read_bio(bp, &mem) < 0)
1313 *data = (unsigned char *)mem->data;
1314 *len = (long)mem->length;
1320 static int ends_with_dirsep(const char *uri)
1323 uri += strlen(uri) - 1;
1325 if (*uri == ']' || *uri == '>' || *uri == ':')
1327 #elif defined(_WIN32)
1334 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1337 assert(name != NULL);
1338 assert(data != NULL);
1340 const char *pathsep = ends_with_dirsep(ctx->uri) ? "" : "/";
1341 long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1342 + strlen(name) + 1 /* \0 */;
1344 *data = OPENSSL_zalloc(calculated_length);
1345 if (*data == NULL) {
1346 OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1350 OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1351 OPENSSL_strlcat(*data, pathsep, calculated_length);
1352 OPENSSL_strlcat(*data, name, calculated_length);
1357 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1359 const char *p = NULL;
1361 /* If there are no search criteria, all names are accepted */
1362 if (ctx->_.dir.search_name[0] == '\0')
1365 /* If the expected type isn't supported, no name is accepted */
1366 if (ctx->expected_type != 0
1367 && ctx->expected_type != OSSL_STORE_INFO_CERT
1368 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1372 * First, check the basename
1374 if (strncasecmp(name, ctx->_.dir.search_name,
1375 sizeof(ctx->_.dir.search_name) - 1) != 0
1376 || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1378 p = &name[sizeof(ctx->_.dir.search_name)];
1381 * Then, if the expected type is a CRL, check that the extension starts
1386 if (ctx->expected_type != 0
1387 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1389 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1394 * Last, check that the rest of the extension is a decimal number, at
1395 * least one digit long.
1397 if (!ossl_isdigit(*p))
1399 while (ossl_isdigit(*p))
1404 * One extra step here, check for a possible generation number.
1407 for (p++; *p != '\0'; p++)
1408 if (!ossl_isdigit(*p))
1413 * If we've reached the end of the string at this point, we've successfully
1414 * found a fitting file name.
1419 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1420 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1421 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1422 const UI_METHOD *ui_method, void *ui_data)
1424 OSSL_STORE_INFO *result = NULL;
1429 if (ctx->type == is_dir) {
1431 char *newname = NULL;
1433 if (ctx->_.dir.last_entry == NULL) {
1434 if (!ctx->_.dir.end_reached) {
1436 assert(ctx->_.dir.last_errno != 0);
1437 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1438 errno = ctx->_.dir.last_errno;
1440 if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
1441 ERR_add_error_data(1, errbuf);
1446 if (ctx->_.dir.last_entry[0] != '.'
1447 && file_name_check(ctx, ctx->_.dir.last_entry)
1448 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1452 * On the first call (with a NULL context), OPENSSL_DIR_read()
1453 * cares about the second argument. On the following calls, it
1454 * only cares that it isn't NULL. Therefore, we can safely give
1457 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1458 ctx->_.dir.last_errno = errno;
1459 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1460 ctx->_.dir.end_reached = 1;
1463 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1464 OPENSSL_free(newname);
1465 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1468 } while (result == NULL && !file_eof(ctx));
1470 int matchcount = -1;
1473 result = file_load_try_repeat(ctx, ui_method, ui_data);
1481 char *pem_name = NULL; /* PEM record name */
1482 char *pem_header = NULL; /* PEM record header */
1483 unsigned char *data = NULL; /* DER encoded data */
1484 long len = 0; /* DER encoded data length */
1487 if (ctx->type == is_pem) {
1488 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1489 &data, &len, ui_method, ui_data, ctx->uri,
1490 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1495 if ((result = file_try_read_msblob(ctx->_.file.file,
1496 &matchcount)) != NULL
1497 || (result = file_try_read_PVK(ctx->_.file.file,
1498 ui_method, ui_data, ctx->uri,
1499 &matchcount)) != NULL)
1502 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1508 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1509 ui_method, ui_data, &matchcount);
1515 * If a PEM name matches more than one handler, the handlers are
1518 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1523 if (matchcount > 1) {
1524 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1525 OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1526 } else if (matchcount == 1) {
1528 * If there are other errors on the stack, they already show
1529 * what the problem is.
1531 if (ERR_peek_error() == 0) {
1532 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1533 OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1534 if (pem_name != NULL)
1535 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1542 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1543 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1544 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1545 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1547 /* We bail out on ambiguity */
1552 && ctx->expected_type != 0
1553 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1554 OSSL_STORE_INFO_free(result);
1562 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1564 return ctx->errcnt > 0;
1567 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1569 if (ctx->type == is_dir)
1570 return ctx->_.dir.end_reached;
1572 if (ctx->_.file.last_handler != NULL
1573 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1575 return BIO_eof(ctx->_.file.file);
1578 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1580 if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1581 if (ctx->type == is_dir)
1582 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1584 BIO_free_all(ctx->_.file.file);
1587 * Because file_attach() called file_find_type(), we know that a
1588 * BIO_f_buffer() has been pushed on top of the regular BIO.
1590 BIO *buff = ctx->_.file.file;
1593 (void)BIO_pop(ctx->_.file.file);
1594 /* Safety measure */
1595 ctx->_.file.file = NULL;
1599 OSSL_STORE_LOADER_CTX_free(ctx);
1603 static OSSL_STORE_LOADER file_loader =
1618 static void store_file_loader_deinit(void)
1620 ossl_store_unregister_loader_int(file_loader.scheme);
1623 int ossl_store_file_loader_init(void)
1625 int ret = ossl_store_register_loader_int(&file_loader);
1627 OPENSSL_atexit(store_file_loader_deinit);