2 * Copyright 2016-2023 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
10 /* THIS ENGINE IS FOR TESTING PURPOSES ONLY. */
12 /* This file has quite some overlap with providers/implementations/storemgmt/file_store.c */
14 /* We need to use some engine deprecated APIs */
15 #define OPENSSL_SUPPRESS_DEPRECATED
17 #include "internal/e_os.h" /* for stat */
23 #include <openssl/bio.h>
24 #include <openssl/dsa.h> /* For d2i_DSAPrivateKey */
25 #include <openssl/err.h>
26 #include <openssl/evp.h>
27 #include <openssl/pem.h>
28 #include <openssl/pkcs12.h> /* For the PKCS8 stuff o.O */
29 #include <openssl/rsa.h> /* For d2i_RSAPrivateKey */
30 #include <openssl/safestack.h>
31 #include <openssl/store.h>
32 #include <openssl/ui.h>
33 #include <openssl/engine.h>
34 #include <openssl/x509.h> /* For the PKCS8 stuff o.O */
35 #include "internal/asn1.h" /* For asn1_d2i_read_bio */
36 #include "internal/o_dir.h"
37 #include "internal/cryptlib.h"
38 #include "crypto/ctype.h" /* For ossl_isdigit */
39 #include "crypto/pem.h" /* For PVK and "blob" PEM headers */
41 #include "e_loader_attic_err.c"
43 DEFINE_STACK_OF(OSSL_STORE_INFO)
46 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
54 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
55 size_t maxsize, const char *desc, const char *info,
62 ATTICerr(0, ERR_R_UI_LIB);
66 if (ui_method != NULL)
67 UI_set_method(ui, ui_method);
68 UI_add_user_data(ui, data);
70 if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
71 ATTICerr(0, ERR_R_UI_LIB);
73 } else if (UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
74 pass, 0, maxsize - 1) <= 0) {
75 ATTICerr(0, ERR_R_UI_LIB);
78 switch (UI_process(ui)) {
80 ATTICerr(0, ATTIC_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
84 ATTICerr(0, ERR_R_UI_LIB);
97 struct pem_pass_data {
98 const UI_METHOD *ui_method;
100 const char *prompt_desc;
101 const char *prompt_info;
104 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
105 const char *desc, const char *info,
106 const UI_METHOD *ui_method, void *ui_data)
108 if (pass_data == NULL)
110 pass_data->ui_method = ui_method;
111 pass_data->data = ui_data;
112 pass_data->prompt_desc = desc;
113 pass_data->prompt_info = info;
117 /* This is used anywhere a pem_password_cb is needed */
118 static int file_get_pem_pass(char *buf, int num, int w, void *data)
120 struct pem_pass_data *pass_data = data;
121 char *pass = file_get_pass(pass_data->ui_method, buf, num,
122 pass_data->prompt_desc, pass_data->prompt_info,
125 return pass == NULL ? 0 : strlen(pass);
129 * Check if |str| ends with |suffix| preceded by a space, and if it does,
130 * return the index of that space. If there is no such suffix in |str|,
132 * For |str| == "FOO BAR" and |suffix| == "BAR", the returned value is 3.
134 static int check_suffix(const char *str, const char *suffix)
136 int str_len = strlen(str);
137 int suffix_len = strlen(suffix) + 1;
138 const char *p = NULL;
140 if (suffix_len >= str_len)
142 p = str + str_len - suffix_len;
144 || strcmp(p + 1, suffix) != 0)
150 * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file
151 * handlers, so we define it internally. This uses the possibility to
152 * create an OSSL_STORE_INFO with a generic data pointer and arbitrary
155 * This is used by a FILE_HANDLER's try_decode function to signal that it
156 * has decoded the incoming blob into a new blob, and that the attempted
157 * decoding should be immediately restarted with the new blob, using the
160 /* Negative numbers are never used for public OSSL_STORE_INFO types */
161 #define STORE_INFO_EMBEDDED -1
163 /* This is the embedded data */
169 /* Helper functions */
170 static struct embedded_st *get0_EMBEDDED(OSSL_STORE_INFO *info)
172 return OSSL_STORE_INFO_get0_data(STORE_INFO_EMBEDDED, info);
175 static void store_info_free(OSSL_STORE_INFO *info)
177 struct embedded_st *data;
179 if (info != NULL && (data = get0_EMBEDDED(info)) != NULL) {
180 BUF_MEM_free(data->blob);
181 OPENSSL_free(data->pem_name);
184 OSSL_STORE_INFO_free(info);
187 static OSSL_STORE_INFO *new_EMBEDDED(const char *new_pem_name,
190 OSSL_STORE_INFO *info = NULL;
191 struct embedded_st *data = NULL;
193 if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL)
195 if ((info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
196 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
201 data->blob = embedded;
203 new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
205 if (new_pem_name != NULL && data->pem_name == NULL) {
206 store_info_free(info);
214 * The file scheme decoders
215 * ------------------------
217 * Each possible data type has its own decoder, which either operates
218 * through a given PEM name, or attempts to decode to see if the blob
219 * it's given is decodable for its data type. The assumption is that
220 * only the correct data type will match the content.
224 * The try_decode function is called to check if the blob of data can
225 * be used by this handler, and if it can, decodes it into a supported
226 * OpenSSL type and returns an OSSL_STORE_INFO with the decoded data.
228 * pem_name: If this blob comes from a PEM file, this holds
229 * the PEM name. If it comes from another type of
230 * file, this is NULL.
231 * pem_header: If this blob comes from a PEM file, this holds
232 * the PEM headers. If it comes from another type of
233 * file, this is NULL.
234 * blob: The blob of data to match with what this handler
236 * len: The length of the blob.
237 * handler_ctx: For a handler marked repeatable, this pointer can
238 * be used to create a context for the handler. IT IS
239 * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
240 * THIS CONTEXT APPROPRIATELY, i.e. create on first call
241 * and destroy when about to return NULL.
242 * matchcount: A pointer to an int to count matches for this data.
243 * Usually becomes 0 (no match) or 1 (match!), but may
244 * be higher in the (unlikely) event that the data matches
245 * more than one possibility. The int will always be
246 * zero when the function is called.
247 * ui_method: Application UI method for getting a password, pin
248 * or any other interactive data.
249 * ui_data: Application data to be passed to ui_method when
251 * libctx: The library context to be used if applicable
252 * propq: The property query string for any algorithm fetches
256 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
257 const char *pem_header,
258 const unsigned char *blob,
259 size_t len, void **handler_ctx,
261 const UI_METHOD *ui_method,
262 void *ui_data, const char *uri,
263 OSSL_LIB_CTX *libctx,
266 * The eof function should return 1 if there's no more data to be found
267 * with the handler_ctx, otherwise 0. This is only used when the handler is
270 typedef int (*file_eof_fn)(void *handler_ctx);
272 * The destroy_ctx function is used to destroy the handler_ctx that was
273 * initiated by a repeatable try_decode function. This is only used when
274 * the handler is marked repeatable.
276 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
278 typedef struct file_handler_st {
280 file_try_decode_fn try_decode;
282 file_destroy_ctx_fn destroy_ctx;
289 * PKCS#12 decoder. It operates by decoding all of the blob content,
290 * extracting all the interesting data from it and storing them internally,
291 * then serving them one piece at a time.
293 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
294 const char *pem_header,
295 const unsigned char *blob,
296 size_t len, void **pctx,
298 const UI_METHOD *ui_method,
299 void *ui_data, const char *uri,
300 OSSL_LIB_CTX *libctx,
303 OSSL_STORE_INFO *store_info = NULL;
304 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
307 /* Initial parsing */
310 if (pem_name != NULL)
311 /* No match, there is no PEM PKCS12 tag */
314 if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
316 char tpass[PEM_BUFSIZE];
317 EVP_PKEY *pkey = NULL;
319 STACK_OF(X509) *chain = NULL;
323 if (!PKCS12_mac_present(p12)
324 || PKCS12_verify_mac(p12, "", 0)
325 || PKCS12_verify_mac(p12, NULL, 0)) {
328 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
329 "PKCS12 import", uri,
331 ATTICerr(0, ATTIC_R_PASSPHRASE_CALLBACK_ERROR);
334 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
335 ATTICerr(0, ATTIC_R_ERROR_VERIFYING_PKCS12_MAC);
340 if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
341 OSSL_STORE_INFO *osi_pkey = NULL;
342 OSSL_STORE_INFO *osi_cert = NULL;
343 OSSL_STORE_INFO *osi_ca = NULL;
346 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
348 if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
349 /* clearing pkey here avoids case distinctions */
350 && (pkey = NULL) == NULL
351 && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
356 if (ok && cert != NULL) {
357 if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
358 /* clearing cert here avoids case distinctions */
359 && (cert = NULL) == NULL
360 && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
365 while (ok && sk_X509_num(chain) > 0) {
366 X509 *ca = sk_X509_value(chain, 0);
368 if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
369 && sk_X509_shift(chain) != NULL
370 && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
378 OSSL_STACK_OF_X509_free(chain);
379 store_info_free(osi_pkey);
380 store_info_free(osi_cert);
381 store_info_free(osi_ca);
383 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
396 store_info = sk_OSSL_STORE_INFO_shift(ctx);
400 static int eof_PKCS12(void *ctx_)
402 STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
404 return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
407 static void destroy_ctx_PKCS12(void **pctx)
409 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
411 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
415 static FILE_HANDLER PKCS12_handler = {
424 * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
425 * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
426 * decoding process will then start over with the new blob.
428 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
429 const char *pem_header,
430 const unsigned char *blob,
431 size_t len, void **pctx,
433 const UI_METHOD *ui_method,
436 OSSL_LIB_CTX *libctx,
440 char kbuf[PEM_BUFSIZE];
442 const X509_ALGOR *dalg = NULL;
443 const ASN1_OCTET_STRING *doct = NULL;
444 OSSL_STORE_INFO *store_info = NULL;
446 unsigned char *new_data = NULL;
449 if (pem_name != NULL) {
450 if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
455 if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
460 if ((mem = BUF_MEM_new()) == NULL) {
461 ATTICerr(0, ERR_R_BUF_LIB);
465 if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
466 "PKCS8 decrypt pass phrase", uri,
468 ATTICerr(0, ATTIC_R_BAD_PASSWORD_READ);
472 X509_SIG_get0(p8, &dalg, &doct);
473 if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
474 &new_data, &new_data_len, 0))
477 mem->data = (char *)new_data;
478 mem->max = mem->length = (size_t)new_data_len;
482 store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
483 if (store_info == NULL) {
484 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
495 static FILE_HANDLER PKCS8Encrypted_handler = {
497 try_decode_PKCS8Encrypted
501 * Private key decoder. Decodes all sorts of private keys, both PKCS#8
502 * encoded ones and old style PEM ones (with the key type is encoded into
505 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
506 const char *pem_header,
507 const unsigned char *blob,
508 size_t len, void **pctx,
510 const UI_METHOD *ui_method,
511 void *ui_data, const char *uri,
512 OSSL_LIB_CTX *libctx,
515 OSSL_STORE_INFO *store_info = NULL;
516 EVP_PKEY *pkey = NULL;
517 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
519 if (pem_name != NULL) {
520 if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
521 PKCS8_PRIV_KEY_INFO *p8inf =
522 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
526 pkey = EVP_PKCS82PKEY_ex(p8inf, libctx, propq);
527 PKCS8_PRIV_KEY_INFO_free(p8inf);
532 if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
533 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
535 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
538 pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, len,
544 #ifndef OPENSSL_NO_ENGINE
545 ENGINE *curengine = ENGINE_get_first();
547 while (curengine != NULL) {
548 ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
549 ENGINE_get_pkey_asn1_meths(curengine);
551 if (asn1meths != NULL) {
552 const int *nids = NULL;
553 int nids_n = asn1meths(curengine, NULL, &nids, 0);
555 for (i = 0; i < nids_n; i++) {
556 EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
557 EVP_PKEY *tmp_pkey = NULL;
558 const unsigned char *tmp_blob = blob;
559 int pkey_id, pkey_flags;
561 if (!asn1meths(curengine, &ameth2, NULL, nids[i])
562 || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
563 &pkey_flags, NULL, NULL,
565 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
568 ERR_set_mark(); /* prevent flooding error queue */
569 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
572 if (tmp_pkey != NULL) {
574 EVP_PKEY_free(tmp_pkey);
582 curengine = ENGINE_get_next(curengine);
586 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
587 EVP_PKEY *tmp_pkey = NULL;
588 const unsigned char *tmp_blob = blob;
589 int pkey_id, pkey_flags;
591 ameth = EVP_PKEY_asn1_get0(i);
592 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
594 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
597 ERR_set_mark(); /* prevent flooding error queue */
598 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, len,
600 if (tmp_pkey != NULL) {
602 EVP_PKEY_free(tmp_pkey);
610 if (*matchcount > 1) {
619 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
620 if (store_info == NULL)
626 static FILE_HANDLER PrivateKey_handler = {
628 try_decode_PrivateKey
632 * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
634 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
635 const char *pem_header,
636 const unsigned char *blob,
637 size_t len, void **pctx,
639 const UI_METHOD *ui_method,
640 void *ui_data, const char *uri,
641 OSSL_LIB_CTX *libctx,
644 OSSL_STORE_INFO *store_info = NULL;
645 EVP_PKEY *pkey = NULL;
647 if (pem_name != NULL) {
648 if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
654 if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
656 store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
662 static FILE_HANDLER PUBKEY_handler = {
668 * Key parameter decoder.
670 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
671 const char *pem_header,
672 const unsigned char *blob,
673 size_t len, void **pctx,
675 const UI_METHOD *ui_method,
676 void *ui_data, const char *uri,
677 OSSL_LIB_CTX *libctx,
680 OSSL_STORE_INFO *store_info = NULL;
681 EVP_PKEY *pkey = NULL;
682 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
684 if (pem_name != NULL) {
688 if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
689 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
690 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
693 pkey = d2i_KeyParams(pkey_id, NULL, &blob, len);
698 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
699 EVP_PKEY *tmp_pkey = NULL;
700 const unsigned char *tmp_blob = blob;
701 int pkey_id, pkey_flags;
703 ameth = EVP_PKEY_asn1_get0(i);
704 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
706 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
709 ERR_set_mark(); /* prevent flooding error queue */
711 tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, len);
713 if (tmp_pkey != NULL) {
715 EVP_PKEY_free(tmp_pkey);
723 if (*matchcount > 1) {
732 store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
733 if (store_info == NULL)
739 static FILE_HANDLER params_handler = {
745 * X.509 certificate decoder.
747 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
748 const char *pem_header,
749 const unsigned char *blob,
750 size_t len, void **pctx,
752 const UI_METHOD *ui_method,
755 OSSL_LIB_CTX *libctx,
758 OSSL_STORE_INFO *store_info = NULL;
762 * In most cases, we can try to interpret the serialized data as a trusted
763 * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
764 * (just X509), but if the PEM name specifically declares it as a trusted
765 * cert, then no fallback should be engaged. |ignore_trusted| tells if
766 * the fallback can be used (1) or not (0).
768 int ignore_trusted = 1;
770 if (pem_name != NULL) {
771 if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
773 else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
774 && strcmp(pem_name, PEM_STRING_X509) != 0)
780 cert = X509_new_ex(libctx, propq);
784 if ((d2i_X509_AUX(&cert, &blob, len)) != NULL
785 || (ignore_trusted && (d2i_X509(&cert, &blob, len)) != NULL)) {
787 store_info = OSSL_STORE_INFO_new_CERT(cert);
790 if (store_info == NULL)
796 static FILE_HANDLER X509Certificate_handler = {
798 try_decode_X509Certificate
804 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
805 const char *pem_header,
806 const unsigned char *blob,
807 size_t len, void **pctx,
809 const UI_METHOD *ui_method,
810 void *ui_data, const char *uri,
811 OSSL_LIB_CTX *libctx,
814 OSSL_STORE_INFO *store_info = NULL;
815 X509_CRL *crl = NULL;
817 if (pem_name != NULL) {
818 if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
824 if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
826 store_info = OSSL_STORE_INFO_new_CRL(crl);
829 if (store_info == NULL)
835 static FILE_HANDLER X509CRL_handler = {
841 * To finish it all off, we collect all the handlers.
843 static const FILE_HANDLER *file_handlers[] = {
845 &PKCS8Encrypted_handler,
846 &X509Certificate_handler,
859 struct ossl_store_loader_ctx_st {
860 char *uri; /* The URI we currently try to load */
867 #define FILE_FLAG_SECMEM (1<<0)
868 #define FILE_FLAG_ATTACHED (1<<1)
871 struct { /* Used with is_raw and is_pem */
875 * The following are used when the handler is marked as
878 const FILE_HANDLER *last_handler;
879 void *last_handler_ctx;
881 struct { /* Used with is_dir */
882 OPENSSL_DIR_CTX *ctx;
886 * When a search expression is given, these are filled in.
887 * |search_name| contains the file basename to look for.
888 * The string is exactly 8 characters long.
893 * The directory reading utility we have combines opening with
894 * reading the first name. To make sure we can detect the end
895 * at the right time, we read early and cache the name.
897 const char *last_entry;
902 /* Expected object type. May be unspecified */
905 OSSL_LIB_CTX *libctx;
909 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
914 OPENSSL_free(ctx->propq);
915 OPENSSL_free(ctx->uri);
916 if (ctx->type != is_dir) {
917 if (ctx->_.file.last_handler != NULL) {
918 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
919 ctx->_.file.last_handler_ctx = NULL;
920 ctx->_.file.last_handler = NULL;
926 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
929 char peekbuf[4096] = { 0, };
931 if ((buff = BIO_new(BIO_f_buffer())) == NULL)
934 ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
935 if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
936 peekbuf[sizeof(peekbuf) - 1] = '\0';
937 if (strstr(peekbuf, "-----BEGIN ") != NULL)
943 static OSSL_STORE_LOADER_CTX *file_open_ex
944 (const OSSL_STORE_LOADER *loader, const char *uri,
945 OSSL_LIB_CTX *libctx, const char *propq,
946 const UI_METHOD *ui_method, void *ui_data)
948 OSSL_STORE_LOADER_CTX *ctx = NULL;
952 unsigned int check_absolute:1;
954 size_t path_data_n = 0, i;
955 const char *path, *p = uri, *q;
958 * First step, just take the URI as is.
960 path_data[path_data_n].check_absolute = 0;
961 path_data[path_data_n++].path = uri;
964 * Second step, if the URI appears to start with the "file" scheme,
965 * extract the path and make that the second path to check.
966 * There's a special case if the URI also contains an authority, then
967 * the full URI shouldn't be used as a path anywhere.
969 if (CHECK_AND_SKIP_CASE_PREFIX(p, "file:")) {
971 if (CHECK_AND_SKIP_PREFIX(q, "//")) {
972 path_data_n--; /* Invalidate using the full URI */
973 if (CHECK_AND_SKIP_CASE_PREFIX(q, "localhost/")
974 || CHECK_AND_SKIP_PREFIX(q, "/")) {
977 ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
982 path_data[path_data_n].check_absolute = 1;
984 /* Windows "file:" URIs with a drive letter start with a '/' */
985 if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
986 char c = tolower(p[1]);
988 if (c >= 'a' && c <= 'z') {
990 /* We know it's absolute, so no need to check */
991 path_data[path_data_n].check_absolute = 0;
995 path_data[path_data_n++].path = p;
999 for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
1001 * If the scheme "file" was an explicit part of the URI, the path must
1002 * be absolute. So says RFC 8089
1004 if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
1005 ATTICerr(0, ATTIC_R_PATH_MUST_BE_ABSOLUTE);
1006 ERR_add_error_data(1, path_data[i].path);
1010 if (stat(path_data[i].path, &st) < 0) {
1011 ERR_raise_data(ERR_LIB_SYS, errno,
1015 path = path_data[i].path;
1022 /* Successfully found a working path */
1024 ctx = OPENSSL_zalloc(sizeof(*ctx));
1027 ctx->uri = OPENSSL_strdup(uri);
1028 if (ctx->uri == NULL)
1031 if (S_ISDIR(st.st_mode)) {
1033 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
1034 ctx->_.dir.last_errno = errno;
1035 if (ctx->_.dir.last_entry == NULL) {
1036 if (ctx->_.dir.last_errno != 0) {
1037 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1040 ctx->_.dir.end_reached = 1;
1042 } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
1043 || !file_find_type(ctx)) {
1044 BIO_free_all(ctx->_.file.file);
1047 if (propq != NULL) {
1048 ctx->propq = OPENSSL_strdup(propq);
1049 if (ctx->propq == NULL)
1052 ctx->libctx = libctx;
1056 OSSL_STORE_LOADER_CTX_free(ctx);
1060 static OSSL_STORE_LOADER_CTX *file_open
1061 (const OSSL_STORE_LOADER *loader, const char *uri,
1062 const UI_METHOD *ui_method, void *ui_data)
1064 return file_open_ex(loader, uri, NULL, NULL, ui_method, ui_data);
1067 static OSSL_STORE_LOADER_CTX *file_attach
1068 (const OSSL_STORE_LOADER *loader, BIO *bp,
1069 OSSL_LIB_CTX *libctx, const char *propq,
1070 const UI_METHOD *ui_method, void *ui_data)
1072 OSSL_STORE_LOADER_CTX *ctx = NULL;
1074 if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
1075 || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
1076 OSSL_STORE_LOADER_CTX_free(ctx);
1079 ctx->libctx = libctx;
1080 ctx->flags |= FILE_FLAG_ATTACHED;
1081 ctx->_.file.file = bp;
1082 if (!file_find_type(ctx)) {
1083 /* Safety measure */
1084 ctx->_.file.file = NULL;
1089 OSSL_STORE_LOADER_CTX_free(ctx);
1093 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1098 case OSSL_STORE_C_USE_SECMEM:
1100 int on = *(va_arg(args, int *));
1104 ctx->flags &= ~FILE_FLAG_SECMEM;
1107 ctx->flags |= FILE_FLAG_SECMEM;
1110 ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
1123 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1125 ctx->expected_type = expected;
1129 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1130 const OSSL_STORE_SEARCH *search)
1133 * If ctx == NULL, the library is looking to know if this loader supports
1134 * the given search type.
1137 if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1138 unsigned long hash = 0;
1143 if (ctx->type != is_dir) {
1144 ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1148 hash = X509_NAME_hash_ex(OSSL_STORE_SEARCH_get0_name(search),
1150 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1156 ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1160 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1161 const char *pem_name,
1162 const char *pem_header,
1163 unsigned char *data, size_t len,
1164 const UI_METHOD *ui_method,
1165 void *ui_data, int *matchcount)
1167 OSSL_STORE_INFO *result = NULL;
1168 BUF_MEM *new_mem = NULL;
1169 char *new_pem_name = NULL;
1175 void *handler_ctx = NULL;
1176 const FILE_HANDLER **matching_handlers =
1177 OPENSSL_zalloc(sizeof(*matching_handlers)
1178 * OSSL_NELEM(file_handlers));
1180 if (matching_handlers == NULL)
1184 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1185 const FILE_HANDLER *handler = file_handlers[i];
1186 int try_matchcount = 0;
1187 void *tmp_handler_ctx = NULL;
1188 OSSL_STORE_INFO *tmp_result;
1193 handler->try_decode(pem_name, pem_header, data, len,
1194 &tmp_handler_ctx, &try_matchcount,
1195 ui_method, ui_data, ctx->uri,
1196 ctx->libctx, ctx->propq);
1197 /* avoid flooding error queue with low-level ASN.1 parse errors */
1198 err = ERR_peek_last_error();
1199 if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1200 && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1203 ERR_clear_last_mark();
1205 if (try_matchcount > 0) {
1207 matching_handlers[*matchcount] = handler;
1210 handler->destroy_ctx(&handler_ctx);
1211 handler_ctx = tmp_handler_ctx;
1213 if ((*matchcount += try_matchcount) > 1) {
1214 /* more than one match => ambiguous, kill any result */
1215 store_info_free(result);
1216 store_info_free(tmp_result);
1217 if (handler->destroy_ctx != NULL)
1218 handler->destroy_ctx(&handler_ctx);
1224 result = tmp_result;
1225 if (result == NULL) /* e.g., PKCS#12 file decryption error */
1231 && *matchcount == 1 && matching_handlers[0]->repeatable) {
1232 ctx->_.file.last_handler = matching_handlers[0];
1233 ctx->_.file.last_handler_ctx = handler_ctx;
1236 OPENSSL_free(matching_handlers);
1240 OPENSSL_free(new_pem_name);
1241 BUF_MEM_free(new_mem);
1244 && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1245 struct embedded_st *embedded = get0_EMBEDDED(result);
1247 /* "steal" the embedded data */
1248 pem_name = new_pem_name = embedded->pem_name;
1249 new_mem = embedded->blob;
1250 data = (unsigned char *)new_mem->data;
1251 len = new_mem->length;
1252 embedded->pem_name = NULL;
1253 embedded->blob = NULL;
1255 store_info_free(result);
1263 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1264 const UI_METHOD *ui_method,
1267 OSSL_STORE_INFO *result = NULL;
1268 int try_matchcount = 0;
1270 if (ctx->_.file.last_handler != NULL) {
1272 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1273 &ctx->_.file.last_handler_ctx,
1275 ui_method, ui_data, ctx->uri,
1276 ctx->libctx, ctx->propq);
1278 if (result == NULL) {
1279 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1280 ctx->_.file.last_handler_ctx = NULL;
1281 ctx->_.file.last_handler = NULL;
1287 static void pem_free_flag(void *pem_data, int secure, size_t num)
1290 OPENSSL_secure_clear_free(pem_data, num);
1292 OPENSSL_free(pem_data);
1294 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1295 unsigned char **data, long *len,
1296 const UI_METHOD *ui_method, void *ui_data,
1297 const char *uri, int secure)
1300 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1301 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1302 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1308 * 10 is the number of characters in "Proc-Type:", which
1309 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1310 * If the PEM header has less characters than that, it's
1311 * not worth spending cycles on it.
1313 if (strlen(*pem_header) > 10) {
1314 EVP_CIPHER_INFO cipher;
1315 struct pem_pass_data pass_data;
1317 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1318 || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1320 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1328 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1330 OSSL_STORE_INFO *result = NULL;
1334 unsigned int magic = 0, bitlen = 0;
1336 unsigned char peekbuf[16] = { 0, };
1337 const unsigned char *p = peekbuf;
1339 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1341 if (ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1342 &isdss, &ispub) <= 0)
1349 EVP_PKEY *tmp = ispub
1350 ? b2i_PublicKey_bio(bp)
1351 : b2i_PrivateKey_bio(bp);
1354 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1363 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1364 void *ui_data, const char *uri,
1367 OSSL_STORE_INFO *result = NULL;
1370 unsigned int saltlen = 0, keylen = 0;
1371 unsigned char peekbuf[24] = { 0, };
1372 const unsigned char *p = peekbuf;
1374 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1376 if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1383 EVP_PKEY *tmp = NULL;
1384 struct pem_pass_data pass_data;
1386 if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1388 || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1389 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1398 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1400 BUF_MEM *mem = NULL;
1402 if (asn1_d2i_read_bio(bp, &mem) < 0)
1405 *data = (unsigned char *)mem->data;
1406 *len = (long)mem->length;
1412 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1415 assert(name != NULL);
1416 assert(data != NULL);
1418 const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
1419 long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1420 + strlen(name) + 1 /* \0 */;
1422 *data = OPENSSL_zalloc(calculated_length);
1426 OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1427 OPENSSL_strlcat(*data, pathsep, calculated_length);
1428 OPENSSL_strlcat(*data, name, calculated_length);
1433 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1435 const char *p = NULL;
1436 size_t len = strlen(ctx->_.dir.search_name);
1438 /* If there are no search criteria, all names are accepted */
1439 if (ctx->_.dir.search_name[0] == '\0')
1442 /* If the expected type isn't supported, no name is accepted */
1443 if (ctx->expected_type != 0
1444 && ctx->expected_type != OSSL_STORE_INFO_CERT
1445 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1449 * First, check the basename
1451 if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
1452 || name[len] != '.')
1457 * Then, if the expected type is a CRL, check that the extension starts
1462 if (ctx->expected_type != 0
1463 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1465 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1470 * Last, check that the rest of the extension is a decimal number, at
1471 * least one digit long.
1473 if (!isdigit((unsigned char)*p))
1475 while (isdigit((unsigned char)*p))
1480 * One extra step here, check for a possible generation number.
1483 for (p++; *p != '\0'; p++)
1484 if (!ossl_isdigit(*p))
1489 * If we've reached the end of the string at this point, we've successfully
1490 * found a fitting file name.
1495 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1496 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1497 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1498 const UI_METHOD *ui_method,
1501 OSSL_STORE_INFO *result = NULL;
1505 if (ctx->type == is_dir) {
1507 char *newname = NULL;
1509 if (ctx->_.dir.last_entry == NULL) {
1510 if (!ctx->_.dir.end_reached) {
1511 assert(ctx->_.dir.last_errno != 0);
1512 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1518 if (ctx->_.dir.last_entry[0] != '.'
1519 && file_name_check(ctx, ctx->_.dir.last_entry)
1520 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1524 * On the first call (with a NULL context), OPENSSL_DIR_read()
1525 * cares about the second argument. On the following calls, it
1526 * only cares that it isn't NULL. Therefore, we can safely give
1529 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1530 ctx->_.dir.last_errno = errno;
1531 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1532 ctx->_.dir.end_reached = 1;
1535 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1536 OPENSSL_free(newname);
1537 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1540 } while (result == NULL && !file_eof(ctx));
1542 int matchcount = -1;
1545 result = file_load_try_repeat(ctx, ui_method, ui_data);
1553 char *pem_name = NULL; /* PEM record name */
1554 char *pem_header = NULL; /* PEM record header */
1555 unsigned char *data = NULL; /* DER encoded data */
1556 long len = 0; /* DER encoded data length */
1559 if (ctx->type == is_pem) {
1560 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1561 &data, &len, ui_method, ui_data, ctx->uri,
1562 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1567 if ((result = file_try_read_msblob(ctx->_.file.file,
1568 &matchcount)) != NULL
1569 || (result = file_try_read_PVK(ctx->_.file.file,
1570 ui_method, ui_data, ctx->uri,
1571 &matchcount)) != NULL)
1574 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1580 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1581 ui_method, ui_data, &matchcount);
1587 * If a PEM name matches more than one handler, the handlers are
1590 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1595 if (matchcount > 1) {
1596 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1597 } else if (matchcount == 1) {
1599 * If there are other errors on the stack, they already show
1600 * what the problem is.
1602 if (ERR_peek_error() == 0) {
1603 ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1604 if (pem_name != NULL)
1605 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1612 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1613 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1614 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1615 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1617 /* We bail out on ambiguity */
1618 if (matchcount > 1) {
1619 store_info_free(result);
1624 && ctx->expected_type != 0
1625 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1626 store_info_free(result);
1634 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1636 return ctx->errcnt > 0;
1639 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1641 if (ctx->type == is_dir)
1642 return ctx->_.dir.end_reached;
1644 if (ctx->_.file.last_handler != NULL
1645 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1647 return BIO_eof(ctx->_.file.file);
1650 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1652 if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1653 if (ctx->type == is_dir)
1654 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1656 BIO_free_all(ctx->_.file.file);
1659 * Because file_attach() called file_find_type(), we know that a
1660 * BIO_f_buffer() has been pushed on top of the regular BIO.
1662 BIO *buff = ctx->_.file.file;
1665 (void)BIO_pop(ctx->_.file.file);
1666 /* Safety measure */
1667 ctx->_.file.file = NULL;
1671 OSSL_STORE_LOADER_CTX_free(ctx);
1679 static const char *loader_attic_id = "loader_attic";
1680 static const char *loader_attic_name = "'file:' loader";
1682 static OSSL_STORE_LOADER *loader_attic = NULL;
1684 static int loader_attic_init(ENGINE *e)
1690 static int loader_attic_finish(ENGINE *e)
1696 static int loader_attic_destroy(ENGINE *e)
1698 OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1703 ERR_unload_ATTIC_strings();
1704 OSSL_STORE_LOADER_free(loader);
1708 static int bind_loader_attic(ENGINE *e)
1711 /* Ensure the ATTIC error handling is set up on best effort basis */
1712 ERR_load_ATTIC_strings();
1714 if (/* Create the OSSL_STORE_LOADER */
1715 (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1716 || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
1717 || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1718 || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1719 || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1720 || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1721 || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1722 || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1723 || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1724 || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1725 || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1726 /* Init the engine itself */
1727 || !ENGINE_set_id(e, loader_attic_id)
1728 || !ENGINE_set_name(e, loader_attic_name)
1729 || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1730 || !ENGINE_set_init_function(e, loader_attic_init)
1731 || !ENGINE_set_finish_function(e, loader_attic_finish)
1732 /* Finally, register the method with libcrypto */
1733 || !OSSL_STORE_register_loader(loader_attic)) {
1734 OSSL_STORE_LOADER_free(loader_attic);
1735 loader_attic = NULL;
1736 ATTICerr(0, ATTIC_R_INIT_FAILED);
1743 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1744 # error "Only allowed as dynamically shared object"
1747 static int bind_helper(ENGINE *e, const char *id)
1749 if (id && (strcmp(id, loader_attic_id) != 0))
1751 if (!bind_loader_attic(e))
1756 IMPLEMENT_DYNAMIC_CHECK_FN()
1757 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)