2 * Copyright 2016-2021 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/o_dir.h"
35 #include "internal/cryptlib.h"
36 #include "crypto/ctype.h" /* For ossl_isdigit */
37 #include "crypto/pem.h" /* For PVK and "blob" PEM headers */
39 #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);
203 data->blob = embedded;
205 new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
207 if (new_pem_name != NULL && data->pem_name == NULL) {
208 ATTICerr(0, ERR_R_MALLOC_FAILURE);
209 store_info_free(info);
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,
266 OSSL_LIB_CTX *libctx,
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,
303 OSSL_LIB_CTX *libctx,
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_mac_present(p12)
327 || PKCS12_verify_mac(p12, "", 0)
328 || PKCS12_verify_mac(p12, NULL, 0)) {
331 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
332 "PKCS12 import", uri,
334 ATTICerr(0, ATTIC_R_PASSPHRASE_CALLBACK_ERROR);
337 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
338 ATTICerr(0, ATTIC_R_ERROR_VERIFYING_PKCS12_MAC);
343 if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
344 OSSL_STORE_INFO *osi_pkey = NULL;
345 OSSL_STORE_INFO *osi_cert = NULL;
346 OSSL_STORE_INFO *osi_ca = NULL;
349 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
351 if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
352 /* clearing pkey here avoids case distinctions */
353 && (pkey = NULL) == NULL
354 && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
359 if (ok && cert != NULL) {
360 if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
361 /* clearing cert here avoids case distinctions */
362 && (cert = NULL) == NULL
363 && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
368 while (ok && sk_X509_num(chain) > 0) {
369 X509 *ca = sk_X509_value(chain, 0);
371 if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
372 && sk_X509_shift(chain) != NULL
373 && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
381 sk_X509_pop_free(chain, X509_free);
382 store_info_free(osi_pkey);
383 store_info_free(osi_cert);
384 store_info_free(osi_ca);
386 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
399 store_info = sk_OSSL_STORE_INFO_shift(ctx);
403 static int eof_PKCS12(void *ctx_)
405 STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
407 return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
410 static void destroy_ctx_PKCS12(void **pctx)
412 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
414 sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
418 static FILE_HANDLER PKCS12_handler = {
427 * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob
428 * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole
429 * decoding process will then start over with the new blob.
431 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
432 const char *pem_header,
433 const unsigned char *blob,
434 size_t len, void **pctx,
436 const UI_METHOD *ui_method,
439 OSSL_LIB_CTX *libctx,
443 char kbuf[PEM_BUFSIZE];
445 const X509_ALGOR *dalg = NULL;
446 const ASN1_OCTET_STRING *doct = NULL;
447 OSSL_STORE_INFO *store_info = NULL;
449 unsigned char *new_data = NULL;
452 if (pem_name != NULL) {
453 if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
458 if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
463 if ((mem = BUF_MEM_new()) == NULL) {
464 ATTICerr(0, ERR_R_MALLOC_FAILURE);
468 if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
469 "PKCS8 decrypt pass phrase", uri,
471 ATTICerr(0, ATTIC_R_BAD_PASSWORD_READ);
475 X509_SIG_get0(p8, &dalg, &doct);
476 if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
477 &new_data, &new_data_len, 0))
480 mem->data = (char *)new_data;
481 mem->max = mem->length = (size_t)new_data_len;
485 store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
486 if (store_info == NULL) {
487 ATTICerr(0, ERR_R_MALLOC_FAILURE);
498 static FILE_HANDLER PKCS8Encrypted_handler = {
500 try_decode_PKCS8Encrypted
504 * Private key decoder. Decodes all sorts of private keys, both PKCS#8
505 * encoded ones and old style PEM ones (with the key type is encoded into
508 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
509 const char *pem_header,
510 const unsigned char *blob,
511 size_t len, void **pctx,
513 const UI_METHOD *ui_method,
514 void *ui_data, const char *uri,
515 OSSL_LIB_CTX *libctx,
518 OSSL_STORE_INFO *store_info = NULL;
519 EVP_PKEY *pkey = NULL;
520 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
522 if (pem_name != NULL) {
523 if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
524 PKCS8_PRIV_KEY_INFO *p8inf =
525 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
529 pkey = EVP_PKCS82PKEY_ex(p8inf, libctx, propq);
530 PKCS8_PRIV_KEY_INFO_free(p8inf);
535 if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
536 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
538 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
541 pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, len,
547 #ifndef OPENSSL_NO_ENGINE
548 ENGINE *curengine = ENGINE_get_first();
550 while (curengine != NULL) {
551 ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
552 ENGINE_get_pkey_asn1_meths(curengine);
554 if (asn1meths != NULL) {
555 const int *nids = NULL;
556 int nids_n = asn1meths(curengine, NULL, &nids, 0);
558 for (i = 0; i < nids_n; i++) {
559 EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
560 EVP_PKEY *tmp_pkey = NULL;
561 const unsigned char *tmp_blob = blob;
562 int pkey_id, pkey_flags;
564 if (!asn1meths(curengine, &ameth2, NULL, nids[i])
565 || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
566 &pkey_flags, NULL, NULL,
568 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
571 ERR_set_mark(); /* prevent flooding error queue */
572 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
575 if (tmp_pkey != NULL) {
577 EVP_PKEY_free(tmp_pkey);
585 curengine = ENGINE_get_next(curengine);
589 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
590 EVP_PKEY *tmp_pkey = NULL;
591 const unsigned char *tmp_blob = blob;
592 int pkey_id, pkey_flags;
594 ameth = EVP_PKEY_asn1_get0(i);
595 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
597 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
600 ERR_set_mark(); /* prevent flooding error queue */
601 tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, len,
603 if (tmp_pkey != NULL) {
605 EVP_PKEY_free(tmp_pkey);
613 if (*matchcount > 1) {
622 store_info = OSSL_STORE_INFO_new_PKEY(pkey);
623 if (store_info == NULL)
629 static FILE_HANDLER PrivateKey_handler = {
631 try_decode_PrivateKey
635 * Public key decoder. Only supports SubjectPublicKeyInfo formatted keys.
637 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
638 const char *pem_header,
639 const unsigned char *blob,
640 size_t len, void **pctx,
642 const UI_METHOD *ui_method,
643 void *ui_data, const char *uri,
644 OSSL_LIB_CTX *libctx,
647 OSSL_STORE_INFO *store_info = NULL;
648 EVP_PKEY *pkey = NULL;
650 if (pem_name != NULL) {
651 if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
657 if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
659 store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
665 static FILE_HANDLER PUBKEY_handler = {
671 * Key parameter decoder.
673 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
674 const char *pem_header,
675 const unsigned char *blob,
676 size_t len, void **pctx,
678 const UI_METHOD *ui_method,
679 void *ui_data, const char *uri,
680 OSSL_LIB_CTX *libctx,
683 OSSL_STORE_INFO *store_info = NULL;
684 EVP_PKEY *pkey = NULL;
685 const EVP_PKEY_ASN1_METHOD *ameth = NULL;
687 if (pem_name != NULL) {
691 if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
692 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
693 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
696 pkey = d2i_KeyParams(pkey_id, NULL, &blob, len);
701 for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
702 EVP_PKEY *tmp_pkey = NULL;
703 const unsigned char *tmp_blob = blob;
704 int pkey_id, pkey_flags;
706 ameth = EVP_PKEY_asn1_get0(i);
707 if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
709 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
712 ERR_set_mark(); /* prevent flooding error queue */
714 tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, len);
716 if (tmp_pkey != NULL) {
718 EVP_PKEY_free(tmp_pkey);
726 if (*matchcount > 1) {
735 store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
736 if (store_info == NULL)
742 static FILE_HANDLER params_handler = {
748 * X.509 certificate decoder.
750 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
751 const char *pem_header,
752 const unsigned char *blob,
753 size_t len, void **pctx,
755 const UI_METHOD *ui_method,
758 OSSL_LIB_CTX *libctx,
761 OSSL_STORE_INFO *store_info = NULL;
765 * In most cases, we can try to interpret the serialized data as a trusted
766 * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
767 * (just X509), but if the PEM name specifically declares it as a trusted
768 * cert, then no fallback should be engaged. |ignore_trusted| tells if
769 * the fallback can be used (1) or not (0).
771 int ignore_trusted = 1;
773 if (pem_name != NULL) {
774 if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
776 else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
777 && strcmp(pem_name, PEM_STRING_X509) != 0)
783 cert = X509_new_ex(libctx, propq);
787 if ((d2i_X509_AUX(&cert, &blob, len)) != NULL
788 || (ignore_trusted && (d2i_X509(&cert, &blob, len)) != NULL)) {
790 store_info = OSSL_STORE_INFO_new_CERT(cert);
793 if (store_info == NULL)
799 static FILE_HANDLER X509Certificate_handler = {
801 try_decode_X509Certificate
807 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
808 const char *pem_header,
809 const unsigned char *blob,
810 size_t len, void **pctx,
812 const UI_METHOD *ui_method,
813 void *ui_data, const char *uri,
814 OSSL_LIB_CTX *libctx,
817 OSSL_STORE_INFO *store_info = NULL;
818 X509_CRL *crl = NULL;
820 if (pem_name != NULL) {
821 if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
827 if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
829 store_info = OSSL_STORE_INFO_new_CRL(crl);
832 if (store_info == NULL)
838 static FILE_HANDLER X509CRL_handler = {
844 * To finish it all off, we collect all the handlers.
846 static const FILE_HANDLER *file_handlers[] = {
848 &PKCS8Encrypted_handler,
849 &X509Certificate_handler,
862 struct ossl_store_loader_ctx_st {
863 char *uri; /* The URI we currently try to load */
870 #define FILE_FLAG_SECMEM (1<<0)
871 #define FILE_FLAG_ATTACHED (1<<1)
874 struct { /* Used with is_raw and is_pem */
878 * The following are used when the handler is marked as
881 const FILE_HANDLER *last_handler;
882 void *last_handler_ctx;
884 struct { /* Used with is_dir */
885 OPENSSL_DIR_CTX *ctx;
889 * When a search expression is given, these are filled in.
890 * |search_name| contains the file basename to look for.
891 * The string is exactly 8 characters long.
896 * The directory reading utility we have combines opening with
897 * reading the first name. To make sure we can detect the end
898 * at the right time, we read early and cache the name.
900 const char *last_entry;
905 /* Expected object type. May be unspecified */
908 OSSL_LIB_CTX *libctx;
912 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
917 OPENSSL_free(ctx->propq);
918 OPENSSL_free(ctx->uri);
919 if (ctx->type != is_dir) {
920 if (ctx->_.file.last_handler != NULL) {
921 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
922 ctx->_.file.last_handler_ctx = NULL;
923 ctx->_.file.last_handler = NULL;
929 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
932 char peekbuf[4096] = { 0, };
934 if ((buff = BIO_new(BIO_f_buffer())) == NULL)
937 ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
938 if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
939 peekbuf[sizeof(peekbuf) - 1] = '\0';
940 if (strstr(peekbuf, "-----BEGIN ") != NULL)
946 static OSSL_STORE_LOADER_CTX *file_open_ex
947 (const OSSL_STORE_LOADER *loader, const char *uri,
948 OSSL_LIB_CTX *libctx, const char *propq,
949 const UI_METHOD *ui_method, void *ui_data)
951 OSSL_STORE_LOADER_CTX *ctx = NULL;
955 unsigned int check_absolute:1;
957 size_t path_data_n = 0, i;
961 * First step, just take the URI as is.
963 path_data[path_data_n].check_absolute = 0;
964 path_data[path_data_n++].path = uri;
967 * Second step, if the URI appears to start with the 'file' scheme,
968 * extract the path and make that the second path to check.
969 * There's a special case if the URI also contains an authority, then
970 * the full URI shouldn't be used as a path anywhere.
972 if (strncasecmp(uri, "file:", 5) == 0) {
973 const char *p = &uri[5];
975 if (strncmp(&uri[5], "//", 2) == 0) {
976 path_data_n--; /* Invalidate using the full URI */
977 if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
979 } else if (uri[7] == '/') {
982 ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
987 path_data[path_data_n].check_absolute = 1;
989 /* Windows file: URIs with a drive letter start with a / */
990 if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
991 char c = tolower(p[1]);
993 if (c >= 'a' && c <= 'z') {
995 /* We know it's absolute, so no need to check */
996 path_data[path_data_n].check_absolute = 0;
1000 path_data[path_data_n++].path = p;
1004 for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
1006 * If the scheme "file" was an explicit part of the URI, the path must
1007 * be absolute. So says RFC 8089
1009 if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
1010 ATTICerr(0, ATTIC_R_PATH_MUST_BE_ABSOLUTE);
1011 ERR_add_error_data(1, path_data[i].path);
1015 if (stat(path_data[i].path, &st) < 0) {
1016 ERR_raise_data(ERR_LIB_SYS, errno,
1020 path = path_data[i].path;
1027 /* Successfully found a working path */
1029 ctx = OPENSSL_zalloc(sizeof(*ctx));
1031 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1034 ctx->uri = OPENSSL_strdup(uri);
1035 if (ctx->uri == NULL) {
1036 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1040 if (S_ISDIR(st.st_mode)) {
1042 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
1043 ctx->_.dir.last_errno = errno;
1044 if (ctx->_.dir.last_entry == NULL) {
1045 if (ctx->_.dir.last_errno != 0) {
1046 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1049 ctx->_.dir.end_reached = 1;
1051 } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
1052 || !file_find_type(ctx)) {
1053 BIO_free_all(ctx->_.file.file);
1056 if (propq != NULL) {
1057 ctx->propq = OPENSSL_strdup(propq);
1058 if (ctx->propq == NULL) {
1059 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1063 ctx->libctx = libctx;
1067 OSSL_STORE_LOADER_CTX_free(ctx);
1071 static OSSL_STORE_LOADER_CTX *file_open
1072 (const OSSL_STORE_LOADER *loader, const char *uri,
1073 const UI_METHOD *ui_method, void *ui_data)
1075 return file_open_ex(loader, uri, NULL, NULL, ui_method, ui_data);
1078 static OSSL_STORE_LOADER_CTX *file_attach
1079 (const OSSL_STORE_LOADER *loader, BIO *bp,
1080 OSSL_LIB_CTX *libctx, const char *propq,
1081 const UI_METHOD *ui_method, void *ui_data)
1083 OSSL_STORE_LOADER_CTX *ctx = NULL;
1085 if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
1086 || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
1087 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1088 OSSL_STORE_LOADER_CTX_free(ctx);
1091 ctx->libctx = libctx;
1092 ctx->flags |= FILE_FLAG_ATTACHED;
1093 ctx->_.file.file = bp;
1094 if (!file_find_type(ctx)) {
1095 /* Safety measure */
1096 ctx->_.file.file = NULL;
1101 OSSL_STORE_LOADER_CTX_free(ctx);
1105 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1110 case OSSL_STORE_C_USE_SECMEM:
1112 int on = *(va_arg(args, int *));
1116 ctx->flags &= ~FILE_FLAG_SECMEM;
1119 ctx->flags |= FILE_FLAG_SECMEM;
1122 ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
1135 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1137 ctx->expected_type = expected;
1141 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1142 const OSSL_STORE_SEARCH *search)
1145 * If ctx == NULL, the library is looking to know if this loader supports
1146 * the given search type.
1149 if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1150 unsigned long hash = 0;
1155 if (ctx->type != is_dir) {
1156 ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1160 hash = X509_NAME_hash_ex(OSSL_STORE_SEARCH_get0_name(search),
1162 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1168 ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1172 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1173 const char *pem_name,
1174 const char *pem_header,
1175 unsigned char *data, size_t len,
1176 const UI_METHOD *ui_method,
1177 void *ui_data, int *matchcount)
1179 OSSL_STORE_INFO *result = NULL;
1180 BUF_MEM *new_mem = NULL;
1181 char *new_pem_name = NULL;
1187 void *handler_ctx = NULL;
1188 const FILE_HANDLER **matching_handlers =
1189 OPENSSL_zalloc(sizeof(*matching_handlers)
1190 * OSSL_NELEM(file_handlers));
1192 if (matching_handlers == NULL) {
1193 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1198 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1199 const FILE_HANDLER *handler = file_handlers[i];
1200 int try_matchcount = 0;
1201 void *tmp_handler_ctx = NULL;
1202 OSSL_STORE_INFO *tmp_result;
1207 handler->try_decode(pem_name, pem_header, data, len,
1208 &tmp_handler_ctx, &try_matchcount,
1209 ui_method, ui_data, ctx->uri,
1210 ctx->libctx, ctx->propq);
1211 /* avoid flooding error queue with low-level ASN.1 parse errors */
1212 err = ERR_peek_last_error();
1213 if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1214 && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1217 ERR_clear_last_mark();
1219 if (try_matchcount > 0) {
1221 matching_handlers[*matchcount] = handler;
1224 handler->destroy_ctx(&handler_ctx);
1225 handler_ctx = tmp_handler_ctx;
1227 if ((*matchcount += try_matchcount) > 1) {
1228 /* more than one match => ambiguous, kill any result */
1229 store_info_free(result);
1230 store_info_free(tmp_result);
1231 if (handler->destroy_ctx != NULL)
1232 handler->destroy_ctx(&handler_ctx);
1238 result = tmp_result;
1239 if (result == NULL) /* e.g., PKCS#12 file decryption error */
1245 && *matchcount == 1 && matching_handlers[0]->repeatable) {
1246 ctx->_.file.last_handler = matching_handlers[0];
1247 ctx->_.file.last_handler_ctx = handler_ctx;
1250 OPENSSL_free(matching_handlers);
1254 OPENSSL_free(new_pem_name);
1255 BUF_MEM_free(new_mem);
1258 && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1259 struct embedded_st *embedded = get0_EMBEDDED(result);
1261 /* "steal" the embedded data */
1262 pem_name = new_pem_name = embedded->pem_name;
1263 new_mem = embedded->blob;
1264 data = (unsigned char *)new_mem->data;
1265 len = new_mem->length;
1266 embedded->pem_name = NULL;
1267 embedded->blob = NULL;
1269 store_info_free(result);
1277 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1278 const UI_METHOD *ui_method,
1281 OSSL_STORE_INFO *result = NULL;
1282 int try_matchcount = 0;
1284 if (ctx->_.file.last_handler != NULL) {
1286 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1287 &ctx->_.file.last_handler_ctx,
1289 ui_method, ui_data, ctx->uri,
1290 ctx->libctx, ctx->propq);
1292 if (result == NULL) {
1293 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1294 ctx->_.file.last_handler_ctx = NULL;
1295 ctx->_.file.last_handler = NULL;
1301 static void pem_free_flag(void *pem_data, int secure, size_t num)
1304 OPENSSL_secure_clear_free(pem_data, num);
1306 OPENSSL_free(pem_data);
1308 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1309 unsigned char **data, long *len,
1310 const UI_METHOD *ui_method, void *ui_data,
1311 const char *uri, int secure)
1314 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1315 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1316 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1322 * 10 is the number of characters in "Proc-Type:", which
1323 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1324 * If the PEM header has less characters than that, it's
1325 * not worth spending cycles on it.
1327 if (strlen(*pem_header) > 10) {
1328 EVP_CIPHER_INFO cipher;
1329 struct pem_pass_data pass_data;
1331 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1332 || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1334 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1342 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1344 OSSL_STORE_INFO *result = NULL;
1348 unsigned int magic = 0, bitlen = 0;
1350 unsigned char peekbuf[16] = { 0, };
1351 const unsigned char *p = peekbuf;
1353 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1355 if (!ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1363 EVP_PKEY *tmp = ispub
1364 ? b2i_PublicKey_bio(bp)
1365 : b2i_PrivateKey_bio(bp);
1368 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1377 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1378 void *ui_data, const char *uri,
1381 OSSL_STORE_INFO *result = NULL;
1384 unsigned int saltlen = 0, keylen = 0;
1385 unsigned char peekbuf[24] = { 0, };
1386 const unsigned char *p = peekbuf;
1388 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1390 if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1397 EVP_PKEY *tmp = NULL;
1398 struct pem_pass_data pass_data;
1400 if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1402 || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1403 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1412 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1414 BUF_MEM *mem = NULL;
1416 if (asn1_d2i_read_bio(bp, &mem) < 0)
1419 *data = (unsigned char *)mem->data;
1420 *len = (long)mem->length;
1426 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1429 assert(name != NULL);
1430 assert(data != NULL);
1432 const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
1433 long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1434 + strlen(name) + 1 /* \0 */;
1436 *data = OPENSSL_zalloc(calculated_length);
1437 if (*data == NULL) {
1438 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1442 OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1443 OPENSSL_strlcat(*data, pathsep, calculated_length);
1444 OPENSSL_strlcat(*data, name, calculated_length);
1449 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1451 const char *p = NULL;
1453 /* If there are no search criteria, all names are accepted */
1454 if (ctx->_.dir.search_name[0] == '\0')
1457 /* If the expected type isn't supported, no name is accepted */
1458 if (ctx->expected_type != 0
1459 && ctx->expected_type != OSSL_STORE_INFO_CERT
1460 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1464 * First, check the basename
1466 if (strncasecmp(name, ctx->_.dir.search_name,
1467 sizeof(ctx->_.dir.search_name) - 1) != 0
1468 || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1470 p = &name[sizeof(ctx->_.dir.search_name)];
1473 * Then, if the expected type is a CRL, check that the extension starts
1478 if (ctx->expected_type != 0
1479 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1481 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1486 * Last, check that the rest of the extension is a decimal number, at
1487 * least one digit long.
1496 * One extra step here, check for a possible generation number.
1499 for (p++; *p != '\0'; p++)
1500 if (!ossl_isdigit(*p))
1505 * If we've reached the end of the string at this point, we've successfully
1506 * found a fitting file name.
1511 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1512 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1513 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1514 const UI_METHOD *ui_method,
1517 OSSL_STORE_INFO *result = NULL;
1521 if (ctx->type == is_dir) {
1523 char *newname = NULL;
1525 if (ctx->_.dir.last_entry == NULL) {
1526 if (!ctx->_.dir.end_reached) {
1527 assert(ctx->_.dir.last_errno != 0);
1528 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1534 if (ctx->_.dir.last_entry[0] != '.'
1535 && file_name_check(ctx, ctx->_.dir.last_entry)
1536 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1540 * On the first call (with a NULL context), OPENSSL_DIR_read()
1541 * cares about the second argument. On the following calls, it
1542 * only cares that it isn't NULL. Therefore, we can safely give
1545 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1546 ctx->_.dir.last_errno = errno;
1547 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1548 ctx->_.dir.end_reached = 1;
1551 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1552 OPENSSL_free(newname);
1553 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1556 } while (result == NULL && !file_eof(ctx));
1558 int matchcount = -1;
1561 result = file_load_try_repeat(ctx, ui_method, ui_data);
1569 char *pem_name = NULL; /* PEM record name */
1570 char *pem_header = NULL; /* PEM record header */
1571 unsigned char *data = NULL; /* DER encoded data */
1572 long len = 0; /* DER encoded data length */
1575 if (ctx->type == is_pem) {
1576 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1577 &data, &len, ui_method, ui_data, ctx->uri,
1578 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1583 if ((result = file_try_read_msblob(ctx->_.file.file,
1584 &matchcount)) != NULL
1585 || (result = file_try_read_PVK(ctx->_.file.file,
1586 ui_method, ui_data, ctx->uri,
1587 &matchcount)) != NULL)
1590 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1596 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1597 ui_method, ui_data, &matchcount);
1603 * If a PEM name matches more than one handler, the handlers are
1606 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1611 if (matchcount > 1) {
1612 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1613 } else if (matchcount == 1) {
1615 * If there are other errors on the stack, they already show
1616 * what the problem is.
1618 if (ERR_peek_error() == 0) {
1619 ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1620 if (pem_name != NULL)
1621 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1628 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1629 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1630 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1631 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1633 /* We bail out on ambiguity */
1634 if (matchcount > 1) {
1635 store_info_free(result);
1640 && ctx->expected_type != 0
1641 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1642 store_info_free(result);
1650 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1652 return ctx->errcnt > 0;
1655 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1657 if (ctx->type == is_dir)
1658 return ctx->_.dir.end_reached;
1660 if (ctx->_.file.last_handler != NULL
1661 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1663 return BIO_eof(ctx->_.file.file);
1666 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1668 if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1669 if (ctx->type == is_dir)
1670 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1672 BIO_free_all(ctx->_.file.file);
1675 * Because file_attach() called file_find_type(), we know that a
1676 * BIO_f_buffer() has been pushed on top of the regular BIO.
1678 BIO *buff = ctx->_.file.file;
1681 (void)BIO_pop(ctx->_.file.file);
1682 /* Safety measure */
1683 ctx->_.file.file = NULL;
1687 OSSL_STORE_LOADER_CTX_free(ctx);
1695 static const char *loader_attic_id = "loader_attic";
1696 static const char *loader_attic_name = "'file:' loader";
1698 static OSSL_STORE_LOADER *loader_attic = NULL;
1700 static int loader_attic_init(ENGINE *e)
1706 static int loader_attic_finish(ENGINE *e)
1712 static int loader_attic_destroy(ENGINE *e)
1714 OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1719 ERR_unload_ATTIC_strings();
1720 OSSL_STORE_LOADER_free(loader);
1724 static int bind_loader_attic(ENGINE *e)
1727 /* Ensure the ATTIC error handling is set up on best effort basis */
1728 ERR_load_ATTIC_strings();
1730 if (/* Create the OSSL_STORE_LOADER */
1731 (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1732 || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
1733 || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1734 || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1735 || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1736 || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1737 || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1738 || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1739 || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1740 || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1741 || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1742 /* Init the engine itself */
1743 || !ENGINE_set_id(e, loader_attic_id)
1744 || !ENGINE_set_name(e, loader_attic_name)
1745 || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1746 || !ENGINE_set_init_function(e, loader_attic_init)
1747 || !ENGINE_set_finish_function(e, loader_attic_finish)
1748 /* Finally, register the method with libcrypto */
1749 || !OSSL_STORE_register_loader(loader_attic)) {
1750 OSSL_STORE_LOADER_free(loader_attic);
1751 loader_attic = NULL;
1752 ATTICerr(0, ATTIC_R_INIT_FAILED);
1759 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1760 # error "Only allowed as dynamically shared object"
1763 static int bind_helper(ENGINE *e, const char *id)
1765 if (id && (strcmp(id, loader_attic_id) != 0))
1767 if (!bind_loader_attic(e))
1772 IMPLEMENT_DYNAMIC_CHECK_FN()
1773 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)