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
10 /* THIS ENGINE IS FOR TESTING PURPOSES ONLY. */
12 /* We need to use some engine deprecated APIs */
13 #define OPENSSL_SUPPRESS_DEPRECATED
15 /* #include "e_os.h" */
21 #include <openssl/bio.h>
22 #include <openssl/dsa.h> /* For d2i_DSAPrivateKey */
23 #include <openssl/err.h>
24 #include <openssl/evp.h>
25 #include <openssl/pem.h>
26 #include <openssl/pkcs12.h> /* For the PKCS8 stuff o.O */
27 #include <openssl/rsa.h> /* For d2i_RSAPrivateKey */
28 #include <openssl/safestack.h>
29 #include <openssl/store.h>
30 #include <openssl/ui.h>
31 #include <openssl/engine.h>
32 #include <openssl/x509.h> /* For the PKCS8 stuff o.O */
33 #include "internal/asn1.h" /* For asn1_d2i_read_bio */
34 #include "internal/pem.h" /* For PVK and "blob" PEM headers */
35 #include "internal/o_dir.h"
36 #include "internal/cryptlib.h"
38 #include "e_loader_attic_err.c"
41 DEFINE_STACK_OF(OSSL_STORE_INFO)
45 # define strncasecmp _strnicmp
49 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
57 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
58 size_t maxsize, const char *desc, const char *info,
65 ATTICerr(0, ERR_R_MALLOC_FAILURE);
69 if (ui_method != NULL)
70 UI_set_method(ui, ui_method);
71 UI_add_user_data(ui, data);
73 if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
74 ATTICerr(0, ERR_R_MALLOC_FAILURE);
76 } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
77 pass, 0, maxsize - 1)) {
78 ATTICerr(0, ERR_R_UI_LIB);
81 switch (UI_process(ui)) {
83 ATTICerr(0, ATTIC_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
87 ATTICerr(0, ERR_R_UI_LIB);
100 struct pem_pass_data {
101 const UI_METHOD *ui_method;
103 const char *prompt_desc;
104 const char *prompt_info;
107 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
108 const char *desc, const char *info,
109 const UI_METHOD *ui_method, void *ui_data)
111 if (pass_data == NULL)
113 pass_data->ui_method = ui_method;
114 pass_data->data = ui_data;
115 pass_data->prompt_desc = desc;
116 pass_data->prompt_info = info;
120 /* This is used anywhere a pem_password_cb is needed */
121 static int file_get_pem_pass(char *buf, int num, int w, void *data)
123 struct pem_pass_data *pass_data = data;
124 char *pass = file_get_pass(pass_data->ui_method, buf, num,
125 pass_data->prompt_desc, pass_data->prompt_info,
128 return pass == NULL ? 0 : strlen(pass);
132 * Check if |str| ends with |suffix| preceded by a space, and if it does,
133 * return the index of that space. If there is no such suffix in |str|,
135 * For |str| == "FOO BAR" and |suffix| == "BAR", the returned value is 3.
137 static int check_suffix(const char *str, const char *suffix)
139 int str_len = strlen(str);
140 int suffix_len = strlen(suffix) + 1;
141 const char *p = NULL;
143 if (suffix_len >= str_len)
145 p = str + str_len - suffix_len;
147 || strcmp(p + 1, suffix) != 0)
153 * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file
154 * handlers, so we define it internally. This uses the possibility to
155 * create an OSSL_STORE_INFO with a generic data pointer and arbitrary
158 * This is used by a FILE_HANDLER's try_decode function to signal that it
159 * has decoded the incoming blob into a new blob, and that the attempted
160 * decoding should be immediately restarted with the new blob, using the
163 /* Negative numbers are never used for public OSSL_STORE_INFO types */
164 #define STORE_INFO_EMBEDDED -1
166 /* This is the embedded data */
172 /* Helper functions */
173 static struct embedded_st *get0_EMBEDDED(OSSL_STORE_INFO *info)
175 return OSSL_STORE_INFO_get0_data(STORE_INFO_EMBEDDED, info);
178 static void store_info_free(OSSL_STORE_INFO *info)
180 struct embedded_st *data;
182 if (info != NULL && (data = get0_EMBEDDED(info)) != NULL) {
183 BUF_MEM_free(data->blob);
184 OPENSSL_free(data->pem_name);
187 OSSL_STORE_INFO_free(info);
190 static OSSL_STORE_INFO *new_EMBEDDED(const char *new_pem_name,
193 OSSL_STORE_INFO *info = NULL;
194 struct embedded_st *data = NULL;
196 if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL
197 || (info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
198 ATTICerr(0, ERR_R_MALLOC_FAILURE);
204 new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
206 if (new_pem_name != NULL && data->pem_name == NULL) {
207 ATTICerr(0, ERR_R_MALLOC_FAILURE);
208 store_info_free(info);
211 data->blob = embedded;
217 * The file scheme decoders
218 * ------------------------
220 * Each possible data type has its own decoder, which either operates
221 * through a given PEM name, or attempts to decode to see if the blob
222 * it's given is decodable for its data type. The assumption is that
223 * only the correct data type will match the content.
227 * The try_decode function is called to check if the blob of data can
228 * be used by this handler, and if it can, decodes it into a supported
229 * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
231 * pem_name: If this blob comes from a PEM file, this holds
232 * the PEM name. If it comes from another type of
233 * file, this is NULL.
234 * pem_header: If this blob comes from a PEM file, this holds
235 * the PEM headers. If it comes from another type of
236 * file, this is NULL.
237 * blob: The blob of data to match with what this handler
239 * len: The length of the blob.
240 * handler_ctx: For a handler marked repeatable, this pointer can
241 * be used to create a context for the handler. IT IS
242 * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
243 * THIS CONTEXT APPROPRIATELY, i.e. create on first call
244 * and destroy when about to return NULL.
245 * matchcount: A pointer to an int to count matches for this data.
246 * Usually becomes 0 (no match) or 1 (match!), but may
247 * be higher in the (unlikely) event that the data matches
248 * more than one possibility. The int will always be
249 * zero when the function is called.
250 * ui_method: Application UI method for getting a password, pin
251 * or any other interactive data.
252 * ui_data: Application data to be passed to ui_method when
254 * libctx: The library context to be used if applicable
255 * propq: The property query string for any algorithm fetches
259 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
260 const char *pem_header,
261 const unsigned char *blob,
262 size_t len, void **handler_ctx,
264 const UI_METHOD *ui_method,
265 void *ui_data, const char *uri,
269 * The eof function should return 1 if there's no more data to be found
270 * with the handler_ctx, otherwise 0. This is only used when the handler is
273 typedef int (*file_eof_fn)(void *handler_ctx);
275 * The destroy_ctx function is used to destroy the handler_ctx that was
276 * initiated by a repeatable try_decode function. This is only used when
277 * the handler is marked repeatable.
279 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
281 typedef struct file_handler_st {
283 file_try_decode_fn try_decode;
285 file_destroy_ctx_fn destroy_ctx;
292 * PKCS#12 decoder. It operates by decoding all of the blob content,
293 * extracting all the interesting data from it and storing them internally,
294 * then serving them one piece at a time.
296 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
297 const char *pem_header,
298 const unsigned char *blob,
299 size_t len, void **pctx,
301 const UI_METHOD *ui_method,
302 void *ui_data, const char *uri,
306 OSSL_STORE_INFO *store_info = NULL;
307 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
310 /* Initial parsing */
313 if (pem_name != NULL)
314 /* No match, there is no PEM PKCS12 tag */
317 if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
319 char tpass[PEM_BUFSIZE];
320 EVP_PKEY *pkey = NULL;
322 STACK_OF(X509) *chain = NULL;
326 if (PKCS12_verify_mac(p12, "", 0)
327 || PKCS12_verify_mac(p12, NULL, 0)) {
330 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
331 "PKCS12 import pass phrase", uri,
333 ATTICerr(0, ATTIC_R_PASSPHRASE_CALLBACK_ERROR);
336 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
337 ATTICerr(0, ATTIC_R_ERROR_VERIFYING_PKCS12_MAC);
342 if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
343 OSSL_STORE_INFO *osi_pkey = NULL;
344 OSSL_STORE_INFO *osi_cert = NULL;
345 OSSL_STORE_INFO *osi_ca = NULL;
348 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
350 if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
351 /* clearing pkey here avoids case distinctions */
352 && (pkey = NULL) == NULL
353 && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
358 if (ok && cert != NULL) {
359 if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
360 /* clearing cert here avoids case distinctions */
361 && (cert = NULL) == NULL
362 && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
367 while (ok && sk_X509_num(chain) > 0) {
368 X509 *ca = sk_X509_value(chain, 0);
370 if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
371 && sk_X509_shift(chain) != NULL
372 && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
380 sk_X509_pop_free(chain, X509_free);
381 store_info_free(osi_pkey);
382 store_info_free(osi_cert);
383 store_info_free(osi_ca);
385 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
398 store_info = sk_OSSL_STORE_INFO_shift(ctx);
402 static int eof_PKCS12(void *ctx_)
404 STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
406 return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
409 static void destroy_ctx_PKCS12(void **pctx)
411 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
413 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
417 static FILE_HANDLER PKCS12_handler = {
426 * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
427 * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
428 * decoding process will then start over with the new blob.
430 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
431 const char *pem_header,
432 const unsigned char *blob,
433 size_t len, void **pctx,
435 const UI_METHOD *ui_method,
442 char kbuf[PEM_BUFSIZE];
444 const X509_ALGOR *dalg = NULL;
445 const ASN1_OCTET_STRING *doct = NULL;
446 OSSL_STORE_INFO *store_info = NULL;
448 unsigned char *new_data = NULL;
451 if (pem_name != NULL) {
452 if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
457 if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
462 if ((mem = BUF_MEM_new()) == NULL) {
463 ATTICerr(0, ERR_R_MALLOC_FAILURE);
467 if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
468 "PKCS8 decrypt pass phrase", uri,
470 ATTICerr(0, ATTIC_R_BAD_PASSWORD_READ);
474 X509_SIG_get0(p8, &dalg, &doct);
475 if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
476 &new_data, &new_data_len, 0))
479 mem->data = (char *)new_data;
480 mem->max = mem->length = (size_t)new_data_len;
483 store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
484 if (store_info == NULL) {
485 ATTICerr(0, ERR_R_MALLOC_FAILURE);
496 static FILE_HANDLER PKCS8Encrypted_handler = {
498 try_decode_PKCS8Encrypted
502 * Private key decoder. Decodes all sorts of private keys, both PKCS#8
503 * encoded ones and old style PEM ones (with the key type is encoded into
506 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
507 const char *pem_header,
508 const unsigned char *blob,
509 size_t len, void **pctx,
511 const UI_METHOD *ui_method,
512 void *ui_data, const char *uri,
516 OSSL_STORE_INFO *store_info = NULL;
517 EVP_PKEY *pkey = NULL;
518 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
520 if (pem_name != NULL) {
521 if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
522 PKCS8_PRIV_KEY_INFO *p8inf =
523 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
527 pkey = EVP_PKCS82PKEY_with_libctx(p8inf, libctx, propq);
528 PKCS8_PRIV_KEY_INFO_free(p8inf);
533 if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
534 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
536 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
539 pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, len,
545 #ifndef OPENSSL_NO_ENGINE
546 ENGINE *curengine = ENGINE_get_first();
548 while (curengine != NULL) {
549 ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
550 ENGINE_get_pkey_asn1_meths(curengine);
552 if (asn1meths != NULL) {
553 const int *nids = NULL;
554 int nids_n = asn1meths(curengine, NULL, &nids, 0);
556 for (i = 0; i < nids_n; i++) {
557 EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
558 EVP_PKEY *tmp_pkey = NULL;
559 const unsigned char *tmp_blob = blob;
560 int pkey_id, pkey_flags;
562 if (!asn1meths(curengine, &ameth2, NULL, nids[i])
563 || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
564 &pkey_flags, NULL, NULL,
566 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
569 ERR_set_mark(); /* prevent flooding error queue */
570 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
573 if (tmp_pkey != NULL) {
575 EVP_PKEY_free(tmp_pkey);
583 curengine = ENGINE_get_next(curengine);
587 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
588 EVP_PKEY *tmp_pkey = NULL;
589 const unsigned char *tmp_blob = blob;
590 int pkey_id, pkey_flags;
592 ameth = EVP_PKEY_asn1_get0(i);
593 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
595 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
598 ERR_set_mark(); /* prevent flooding error queue */
599 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, len,
601 if (tmp_pkey != NULL) {
603 EVP_PKEY_free(tmp_pkey);
611 if (*matchcount > 1) {
620 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
621 if (store_info == NULL)
627 static FILE_HANDLER PrivateKey_handler = {
629 try_decode_PrivateKey
633 * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
635 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
636 const char *pem_header,
637 const unsigned char *blob,
638 size_t len, void **pctx,
640 const UI_METHOD *ui_method,
641 void *ui_data, const char *uri,
645 OSSL_STORE_INFO *store_info = NULL;
646 EVP_PKEY *pkey = NULL;
648 if (pem_name != NULL) {
649 if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
655 if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
657 store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
663 static FILE_HANDLER PUBKEY_handler = {
669 * Key parameter decoder.
671 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
672 const char *pem_header,
673 const unsigned char *blob,
674 size_t len, void **pctx,
676 const UI_METHOD *ui_method,
677 void *ui_data, const char *uri,
681 OSSL_STORE_INFO *store_info = NULL;
682 EVP_PKEY *pkey = NULL;
683 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
685 if (pem_name != NULL) {
689 if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
690 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
691 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
694 pkey = d2i_KeyParams(pkey_id, NULL, &blob, len);
699 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
700 EVP_PKEY *tmp_pkey = NULL;
701 const unsigned char *tmp_blob = blob;
702 int pkey_id, pkey_flags;
704 ameth = EVP_PKEY_asn1_get0(i);
705 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
707 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
710 ERR_set_mark(); /* prevent flooding error queue */
712 tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, len);
714 if (tmp_pkey != NULL) {
716 EVP_PKEY_free(tmp_pkey);
724 if (*matchcount > 1) {
733 store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
734 if (store_info == NULL)
740 static FILE_HANDLER params_handler = {
746 * X.509 certificate decoder.
748 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
749 const char *pem_header,
750 const unsigned char *blob,
751 size_t len, void **pctx,
753 const UI_METHOD *ui_method,
759 OSSL_STORE_INFO *store_info = NULL;
763 * In most cases, we can try to interpret the serialized data as a trusted
764 * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
765 * (just X509), but if the PEM name specifically declares it as a trusted
766 * cert, then no fallback should be engaged. |ignore_trusted| tells if
767 * the fallback can be used (1) or not (0).
769 int ignore_trusted = 1;
771 if (pem_name != NULL) {
772 if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
774 else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
775 && strcmp(pem_name, PEM_STRING_X509) != 0)
781 cert = X509_new_with_libctx(libctx, propq);
785 if ((d2i_X509_AUX(&cert, &blob, len)) != NULL
786 || (ignore_trusted && (d2i_X509(&cert, &blob, len)) != NULL)) {
788 store_info = OSSL_STORE_INFO_new_CERT(cert);
791 if (store_info == NULL)
797 static FILE_HANDLER X509Certificate_handler = {
799 try_decode_X509Certificate
805 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
806 const char *pem_header,
807 const unsigned char *blob,
808 size_t len, void **pctx,
810 const UI_METHOD *ui_method,
811 void *ui_data, const char *uri,
815 OSSL_STORE_INFO *store_info = NULL;
816 X509_CRL *crl = NULL;
818 if (pem_name != NULL) {
819 if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
825 if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
827 store_info = OSSL_STORE_INFO_new_CRL(crl);
830 if (store_info == NULL)
836 static FILE_HANDLER X509CRL_handler = {
842 * To finish it all off, we collect all the handlers.
844 static const FILE_HANDLER *file_handlers[] = {
846 &PKCS8Encrypted_handler,
847 &X509Certificate_handler,
860 struct ossl_store_loader_ctx_st {
861 char *uri; /* The URI we currently try to load */
868 #define FILE_FLAG_SECMEM (1<<0)
869 #define FILE_FLAG_ATTACHED (1<<1)
872 struct { /* Used with is_raw and is_pem */
876 * The following are used when the handler is marked as
879 const FILE_HANDLER *last_handler;
880 void *last_handler_ctx;
882 struct { /* Used with is_dir */
883 OPENSSL_DIR_CTX *ctx;
887 * When a search expression is given, these are filled in.
888 * |search_name| contains the file basename to look for.
889 * The string is exactly 8 characters long.
894 * The directory reading utility we have combines opening with
895 * reading the first name. To make sure we can detect the end
896 * at the right time, we read early and cache the name.
898 const char *last_entry;
903 /* Expected object type. May be unspecified */
910 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
915 OPENSSL_free(ctx->propq);
916 OPENSSL_free(ctx->uri);
917 if (ctx->type != is_dir) {
918 if (ctx->_.file.last_handler != NULL) {
919 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
920 ctx->_.file.last_handler_ctx = NULL;
921 ctx->_.file.last_handler = NULL;
927 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
930 char peekbuf[4096] = { 0, };
932 if ((buff = BIO_new(BIO_f_buffer())) == NULL)
935 ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
936 if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
937 peekbuf[sizeof(peekbuf) - 1] = '\0';
938 if (strstr(peekbuf, "-----BEGIN ") != NULL)
944 static OSSL_STORE_LOADER_CTX *file_open_with_libctx
945 (const OSSL_STORE_LOADER *loader, const char *uri,
946 OPENSSL_CTX *libctx, const char *propq,
947 const UI_METHOD *ui_method, void *ui_data)
949 OSSL_STORE_LOADER_CTX *ctx = NULL;
953 unsigned int check_absolute:1;
955 size_t path_data_n = 0, i;
959 * First step, just take the URI as is.
961 path_data[path_data_n].check_absolute = 0;
962 path_data[path_data_n++].path = uri;
965 * Second step, if the URI appears to start with the 'file' scheme,
966 * extract the path and make that the second path to check.
967 * There's a special case if the URI also contains an authority, then
968 * the full URI shouldn't be used as a path anywhere.
970 if (strncasecmp(uri, "file:", 5) == 0) {
971 const char *p = &uri[5];
973 if (strncmp(&uri[5], "//", 2) == 0) {
974 path_data_n--; /* Invalidate using the full URI */
975 if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
977 } else if (uri[7] == '/') {
980 ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
985 path_data[path_data_n].check_absolute = 1;
987 /* Windows file: URIs with a drive letter start with a / */
988 if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
989 char c = tolower(p[1]);
991 if (c >= 'a' && c <= 'z') {
993 /* We know it's absolute, so no need to check */
994 path_data[path_data_n].check_absolute = 0;
998 path_data[path_data_n++].path = p;
1002 for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
1004 * If the scheme "file" was an explicit part of the URI, the path must
1005 * be absolute. So says RFC 8089
1007 if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
1008 ATTICerr(0, ATTIC_R_PATH_MUST_BE_ABSOLUTE);
1009 ERR_add_error_data(1, path_data[i].path);
1013 if (stat(path_data[i].path, &st) < 0) {
1014 ERR_raise_data(ERR_LIB_SYS, errno,
1018 path = path_data[i].path;
1025 /* Successfully found a working path */
1027 ctx = OPENSSL_zalloc(sizeof(*ctx));
1029 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1032 ctx->uri = OPENSSL_strdup(uri);
1033 if (ctx->uri == NULL) {
1034 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1038 if (S_ISDIR(st.st_mode)) {
1040 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
1041 ctx->_.dir.last_errno = errno;
1042 if (ctx->_.dir.last_entry == NULL) {
1043 if (ctx->_.dir.last_errno != 0) {
1044 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1047 ctx->_.dir.end_reached = 1;
1049 } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
1050 || !file_find_type(ctx)) {
1051 BIO_free_all(ctx->_.file.file);
1054 if (propq != NULL) {
1055 ctx->propq = OPENSSL_strdup(propq);
1056 if (ctx->propq == NULL) {
1057 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1061 ctx->libctx = libctx;
1065 OSSL_STORE_LOADER_CTX_free(ctx);
1069 static OSSL_STORE_LOADER_CTX *file_open
1070 (const OSSL_STORE_LOADER *loader, const char *uri,
1071 const UI_METHOD *ui_method, void *ui_data)
1073 return file_open_with_libctx(loader, uri, NULL, NULL, ui_method, ui_data);
1076 static OSSL_STORE_LOADER_CTX *file_attach
1077 (const OSSL_STORE_LOADER *loader, BIO *bp,
1078 OPENSSL_CTX *libctx, const char *propq,
1079 const UI_METHOD *ui_method, void *ui_data)
1081 OSSL_STORE_LOADER_CTX *ctx = NULL;
1083 if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
1084 || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
1085 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1086 OSSL_STORE_LOADER_CTX_free(ctx);
1089 ctx->libctx = libctx;
1090 ctx->flags |= FILE_FLAG_ATTACHED;
1091 ctx->_.file.file = bp;
1092 if (!file_find_type(ctx)) {
1093 /* Safety measure */
1094 ctx->_.file.file = NULL;
1099 OSSL_STORE_LOADER_CTX_free(ctx);
1103 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1108 case OSSL_STORE_C_USE_SECMEM:
1110 int on = *(va_arg(args, int *));
1114 ctx->flags &= ~FILE_FLAG_SECMEM;
1117 ctx->flags |= FILE_FLAG_SECMEM;
1120 ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
1133 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1135 ctx->expected_type = expected;
1139 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1140 const OSSL_STORE_SEARCH *search)
1143 * If ctx == NULL, the library is looking to know if this loader supports
1144 * the given search type.
1147 if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1148 unsigned long hash = 0;
1153 if (ctx->type != is_dir) {
1154 ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1158 hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
1159 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1165 ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1169 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1170 const char *pem_name,
1171 const char *pem_header,
1172 unsigned char *data, size_t len,
1173 const UI_METHOD *ui_method,
1174 void *ui_data, int *matchcount)
1176 OSSL_STORE_INFO *result = NULL;
1177 BUF_MEM *new_mem = NULL;
1178 char *new_pem_name = NULL;
1184 void *handler_ctx = NULL;
1185 const FILE_HANDLER **matching_handlers =
1186 OPENSSL_zalloc(sizeof(*matching_handlers)
1187 * OSSL_NELEM(file_handlers));
1189 if (matching_handlers == NULL) {
1190 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1195 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1196 const FILE_HANDLER *handler = file_handlers[i];
1197 int try_matchcount = 0;
1198 void *tmp_handler_ctx = NULL;
1199 OSSL_STORE_INFO *tmp_result;
1204 handler->try_decode(pem_name, pem_header, data, len,
1205 &tmp_handler_ctx, &try_matchcount,
1206 ui_method, ui_data, ctx->uri,
1207 ctx->libctx, ctx->propq);
1208 /* avoid flooding error queue with low-level ASN.1 parse errors */
1209 err = ERR_peek_last_error();
1210 if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1211 && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1214 ERR_clear_last_mark();
1216 if (try_matchcount > 0) {
1218 matching_handlers[*matchcount] = handler;
1221 handler->destroy_ctx(&handler_ctx);
1222 handler_ctx = tmp_handler_ctx;
1224 if ((*matchcount += try_matchcount) > 1) {
1225 /* more than one match => ambiguous, kill any result */
1226 store_info_free(result);
1227 store_info_free(tmp_result);
1228 if (handler->destroy_ctx != NULL)
1229 handler->destroy_ctx(&handler_ctx);
1235 result = tmp_result;
1239 if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1240 ctx->_.file.last_handler = matching_handlers[0];
1241 ctx->_.file.last_handler_ctx = handler_ctx;
1244 OPENSSL_free(matching_handlers);
1248 OPENSSL_free(new_pem_name);
1249 BUF_MEM_free(new_mem);
1252 && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1253 struct embedded_st *embedded = get0_EMBEDDED(result);
1255 /* "steal" the embedded data */
1256 pem_name = new_pem_name = embedded->pem_name;
1257 new_mem = embedded->blob;
1258 data = (unsigned char *)new_mem->data;
1259 len = new_mem->length;
1260 embedded->pem_name = NULL;
1261 embedded->blob = NULL;
1263 store_info_free(result);
1271 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1272 const UI_METHOD *ui_method,
1275 OSSL_STORE_INFO *result = NULL;
1276 int try_matchcount = 0;
1278 if (ctx->_.file.last_handler != NULL) {
1280 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1281 &ctx->_.file.last_handler_ctx,
1283 ui_method, ui_data, ctx->uri,
1284 ctx->libctx, ctx->propq);
1286 if (result == NULL) {
1287 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1288 ctx->_.file.last_handler_ctx = NULL;
1289 ctx->_.file.last_handler = NULL;
1295 static void pem_free_flag(void *pem_data, int secure, size_t num)
1298 OPENSSL_secure_clear_free(pem_data, num);
1300 OPENSSL_free(pem_data);
1302 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1303 unsigned char **data, long *len,
1304 const UI_METHOD *ui_method, void *ui_data,
1305 const char *uri, int secure)
1308 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1309 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1310 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1316 * 10 is the number of characters in "Proc-Type:", which
1317 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1318 * If the PEM header has less characters than that, it's
1319 * not worth spending cycles on it.
1321 if (strlen(*pem_header) > 10) {
1322 EVP_CIPHER_INFO cipher;
1323 struct pem_pass_data pass_data;
1325 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1326 || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1328 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1336 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1338 #ifdef OPENSSL_NO_DSA
1341 OSSL_STORE_INFO *result = NULL;
1345 unsigned int magic = 0, bitlen = 0;
1347 unsigned char peekbuf[16] = { 0, };
1348 const unsigned char *p = peekbuf;
1350 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1352 if (!ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1360 EVP_PKEY *tmp = ispub
1361 ? b2i_PublicKey_bio(bp)
1362 : b2i_PrivateKey_bio(bp);
1365 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1375 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1376 void *ui_data, const char *uri,
1379 #if defined(OPENSSL_NO_DSA) || defined(OPENSSL_NO_RC4)
1382 OSSL_STORE_INFO *result = NULL;
1385 unsigned int saltlen = 0, keylen = 0;
1386 unsigned char peekbuf[24] = { 0, };
1387 const unsigned char *p = peekbuf;
1389 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1391 if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1398 EVP_PKEY *tmp = NULL;
1399 struct pem_pass_data pass_data;
1401 if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1403 || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1404 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1414 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1416 BUF_MEM *mem = NULL;
1418 if (asn1_d2i_read_bio(bp, &mem) < 0)
1421 *data = (unsigned char *)mem->data;
1422 *len = (long)mem->length;
1428 static int ends_with_dirsep(const char *uri)
1431 uri += strlen(uri) - 1;
1433 if (*uri == ']' || *uri == '>' || *uri == ':')
1435 #elif defined(_WIN32)
1442 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1445 assert(name != NULL);
1446 assert(data != NULL);
1448 const char *pathsep = ends_with_dirsep(ctx->uri) ? "" : "/";
1449 long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1450 + strlen(name) + 1 /* \0 */;
1452 *data = OPENSSL_zalloc(calculated_length);
1453 if (*data == NULL) {
1454 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1458 OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1459 OPENSSL_strlcat(*data, pathsep, calculated_length);
1460 OPENSSL_strlcat(*data, name, calculated_length);
1465 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1467 const char *p = NULL;
1469 /* If there are no search criteria, all names are accepted */
1470 if (ctx->_.dir.search_name[0] == '\0')
1473 /* If the expected type isn't supported, no name is accepted */
1474 if (ctx->expected_type != 0
1475 && ctx->expected_type != OSSL_STORE_INFO_CERT
1476 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1480 * First, check the basename
1482 if (strncasecmp(name, ctx->_.dir.search_name,
1483 sizeof(ctx->_.dir.search_name) - 1) != 0
1484 || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1486 p = &name[sizeof(ctx->_.dir.search_name)];
1489 * Then, if the expected type is a CRL, check that the extension starts
1494 if (ctx->expected_type != 0
1495 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1497 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1502 * Last, check that the rest of the extension is a decimal number, at
1503 * least one digit long.
1512 * One extra step here, check for a possible generation number.
1515 for (p++; *p != '\0'; p++)
1516 if (!ossl_isdigit(*p))
1521 * If we've reached the end of the string at this point, we've successfully
1522 * found a fitting file name.
1527 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1528 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1529 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1530 const UI_METHOD *ui_method,
1533 OSSL_STORE_INFO *result = NULL;
1537 if (ctx->type == is_dir) {
1539 char *newname = NULL;
1541 if (ctx->_.dir.last_entry == NULL) {
1542 if (!ctx->_.dir.end_reached) {
1543 assert(ctx->_.dir.last_errno != 0);
1544 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1550 if (ctx->_.dir.last_entry[0] != '.'
1551 && file_name_check(ctx, ctx->_.dir.last_entry)
1552 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1556 * On the first call (with a NULL context), OPENSSL_DIR_read()
1557 * cares about the second argument. On the following calls, it
1558 * only cares that it isn't NULL. Therefore, we can safely give
1561 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1562 ctx->_.dir.last_errno = errno;
1563 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1564 ctx->_.dir.end_reached = 1;
1567 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1568 OPENSSL_free(newname);
1569 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1572 } while (result == NULL && !file_eof(ctx));
1574 int matchcount = -1;
1577 result = file_load_try_repeat(ctx, ui_method, ui_data);
1585 char *pem_name = NULL; /* PEM record name */
1586 char *pem_header = NULL; /* PEM record header */
1587 unsigned char *data = NULL; /* DER encoded data */
1588 long len = 0; /* DER encoded data length */
1591 if (ctx->type == is_pem) {
1592 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1593 &data, &len, ui_method, ui_data, ctx->uri,
1594 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1599 if ((result = file_try_read_msblob(ctx->_.file.file,
1600 &matchcount)) != NULL
1601 || (result = file_try_read_PVK(ctx->_.file.file,
1602 ui_method, ui_data, ctx->uri,
1603 &matchcount)) != NULL)
1606 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1612 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1613 ui_method, ui_data, &matchcount);
1619 * If a PEM name matches more than one handler, the handlers are
1622 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1627 if (matchcount > 1) {
1628 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1629 } else if (matchcount == 1) {
1631 * If there are other errors on the stack, they already show
1632 * what the problem is.
1634 if (ERR_peek_error() == 0) {
1635 ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1636 if (pem_name != NULL)
1637 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1644 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1645 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1646 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1647 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1649 /* We bail out on ambiguity */
1650 if (matchcount > 1) {
1651 store_info_free(result);
1656 && ctx->expected_type != 0
1657 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1658 store_info_free(result);
1666 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1668 return ctx->errcnt > 0;
1671 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1673 if (ctx->type == is_dir)
1674 return ctx->_.dir.end_reached;
1676 if (ctx->_.file.last_handler != NULL
1677 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1679 return BIO_eof(ctx->_.file.file);
1682 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1684 if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1685 if (ctx->type == is_dir)
1686 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1688 BIO_free_all(ctx->_.file.file);
1691 * Because file_attach() called file_find_type(), we know that a
1692 * BIO_f_buffer() has been pushed on top of the regular BIO.
1694 BIO *buff = ctx->_.file.file;
1697 (void)BIO_pop(ctx->_.file.file);
1698 /* Safety measure */
1699 ctx->_.file.file = NULL;
1703 OSSL_STORE_LOADER_CTX_free(ctx);
1711 static const char *loader_attic_id = "loader_attic";
1712 static const char *loader_attic_name = "'file:' loader";
1714 static OSSL_STORE_LOADER *loader_attic = NULL;
1716 static int loader_attic_init(ENGINE *e)
1722 static int loader_attic_finish(ENGINE *e)
1728 static int loader_attic_destroy(ENGINE *e)
1730 OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1735 ERR_unload_ATTIC_strings();
1736 OSSL_STORE_LOADER_free(loader);
1740 static int bind_loader_attic(ENGINE *e)
1743 /* Ensure the ATTIC error handdling is set up on best effort basis */
1744 ERR_load_ATTIC_strings();
1746 if (/* Create the OSSL_STORE_LOADER */
1747 (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1748 || !OSSL_STORE_LOADER_set_open_with_libctx(loader_attic,
1749 file_open_with_libctx)
1750 || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1751 || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1752 || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1753 || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1754 || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1755 || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1756 || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1757 || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1758 || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1759 /* Init the engine itself */
1760 || !ENGINE_set_id(e, loader_attic_id)
1761 || !ENGINE_set_name(e, loader_attic_name)
1762 || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1763 || !ENGINE_set_init_function(e, loader_attic_init)
1764 || !ENGINE_set_finish_function(e, loader_attic_finish)
1765 /* Finally, register the method with libcrypto */
1766 || !OSSL_STORE_register_loader(loader_attic)) {
1767 OSSL_STORE_LOADER_free(loader_attic);
1768 loader_attic = NULL;
1769 ATTICerr(0, ATTIC_R_INIT_FAILED);
1776 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1777 # error "Only allowed as dynamically shared object"
1780 static int bind_helper(ENGINE *e, const char *id)
1782 if (id && (strcmp(id, loader_attic_id) != 0))
1784 if (!bind_loader_attic(e))
1789 IMPLEMENT_DYNAMIC_CHECK_FN()
1790 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)