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/pem.h" /* For PVK and "blob" PEM headers */
38 #include "e_loader_attic_err.c"
40 DEFINE_STACK_OF(OSSL_STORE_INFO)
44 # define strncasecmp _strnicmp
48 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
56 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
57 size_t maxsize, const char *desc, const char *info,
64 ATTICerr(0, ERR_R_MALLOC_FAILURE);
68 if (ui_method != NULL)
69 UI_set_method(ui, ui_method);
70 UI_add_user_data(ui, data);
72 if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
73 ATTICerr(0, ERR_R_MALLOC_FAILURE);
75 } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
76 pass, 0, maxsize - 1)) {
77 ATTICerr(0, ERR_R_UI_LIB);
80 switch (UI_process(ui)) {
82 ATTICerr(0, ATTIC_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
86 ATTICerr(0, ERR_R_UI_LIB);
99 struct pem_pass_data {
100 const UI_METHOD *ui_method;
102 const char *prompt_desc;
103 const char *prompt_info;
106 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
107 const char *desc, const char *info,
108 const UI_METHOD *ui_method, void *ui_data)
110 if (pass_data == NULL)
112 pass_data->ui_method = ui_method;
113 pass_data->data = ui_data;
114 pass_data->prompt_desc = desc;
115 pass_data->prompt_info = info;
119 /* This is used anywhere a pem_password_cb is needed */
120 static int file_get_pem_pass(char *buf, int num, int w, void *data)
122 struct pem_pass_data *pass_data = data;
123 char *pass = file_get_pass(pass_data->ui_method, buf, num,
124 pass_data->prompt_desc, pass_data->prompt_info,
127 return pass == NULL ? 0 : strlen(pass);
131 * Check if |str| ends with |suffix| preceded by a space, and if it does,
132 * return the index of that space. If there is no such suffix in |str|,
134 * For |str| == "FOO BAR" and |suffix| == "BAR", the returned value is 3.
136 static int check_suffix(const char *str, const char *suffix)
138 int str_len = strlen(str);
139 int suffix_len = strlen(suffix) + 1;
140 const char *p = NULL;
142 if (suffix_len >= str_len)
144 p = str + str_len - suffix_len;
146 || strcmp(p + 1, suffix) != 0)
152 * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file
153 * handlers, so we define it internally. This uses the possibility to
154 * create an OSSL_STORE_INFO with a generic data pointer and arbitrary
157 * This is used by a FILE_HANDLER's try_decode function to signal that it
158 * has decoded the incoming blob into a new blob, and that the attempted
159 * decoding should be immediately restarted with the new blob, using the
162 /* Negative numbers are never used for public OSSL_STORE_INFO types */
163 #define STORE_INFO_EMBEDDED -1
165 /* This is the embedded data */
171 /* Helper functions */
172 static struct embedded_st *get0_EMBEDDED(OSSL_STORE_INFO *info)
174 return OSSL_STORE_INFO_get0_data(STORE_INFO_EMBEDDED, info);
177 static void store_info_free(OSSL_STORE_INFO *info)
179 struct embedded_st *data;
181 if (info != NULL && (data = get0_EMBEDDED(info)) != NULL) {
182 BUF_MEM_free(data->blob);
183 OPENSSL_free(data->pem_name);
186 OSSL_STORE_INFO_free(info);
189 static OSSL_STORE_INFO *new_EMBEDDED(const char *new_pem_name,
192 OSSL_STORE_INFO *info = NULL;
193 struct embedded_st *data = NULL;
195 if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL
196 || (info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
197 ATTICerr(0, ERR_R_MALLOC_FAILURE);
203 new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
205 if (new_pem_name != NULL && data->pem_name == NULL) {
206 ATTICerr(0, ERR_R_MALLOC_FAILURE);
207 store_info_free(info);
210 data->blob = embedded;
216 * The file scheme decoders
217 * ------------------------
219 * Each possible data type has its own decoder, which either operates
220 * through a given PEM name, or attempts to decode to see if the blob
221 * it's given is decodable for its data type. The assumption is that
222 * only the correct data type will match the content.
226 * The try_decode function is called to check if the blob of data can
227 * be used by this handler, and if it can, decodes it into a supported
228 * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
230 * pem_name: If this blob comes from a PEM file, this holds
231 * the PEM name. If it comes from another type of
232 * file, this is NULL.
233 * pem_header: If this blob comes from a PEM file, this holds
234 * the PEM headers. If it comes from another type of
235 * file, this is NULL.
236 * blob: The blob of data to match with what this handler
238 * len: The length of the blob.
239 * handler_ctx: For a handler marked repeatable, this pointer can
240 * be used to create a context for the handler. IT IS
241 * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
242 * THIS CONTEXT APPROPRIATELY, i.e. create on first call
243 * and destroy when about to return NULL.
244 * matchcount: A pointer to an int to count matches for this data.
245 * Usually becomes 0 (no match) or 1 (match!), but may
246 * be higher in the (unlikely) event that the data matches
247 * more than one possibility. The int will always be
248 * zero when the function is called.
249 * ui_method: Application UI method for getting a password, pin
250 * or any other interactive data.
251 * ui_data: Application data to be passed to ui_method when
253 * libctx: The library context to be used if applicable
254 * propq: The property query string for any algorithm fetches
258 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
259 const char *pem_header,
260 const unsigned char *blob,
261 size_t len, void **handler_ctx,
263 const UI_METHOD *ui_method,
264 void *ui_data, const char *uri,
265 OSSL_LIB_CTX *libctx,
268 * The eof function should return 1 if there's no more data to be found
269 * with the handler_ctx, otherwise 0. This is only used when the handler is
272 typedef int (*file_eof_fn)(void *handler_ctx);
274 * The destroy_ctx function is used to destroy the handler_ctx that was
275 * initiated by a repeatable try_decode function. This is only used when
276 * the handler is marked repeatable.
278 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
280 typedef struct file_handler_st {
282 file_try_decode_fn try_decode;
284 file_destroy_ctx_fn destroy_ctx;
291 * PKCS#12 decoder. It operates by decoding all of the blob content,
292 * extracting all the interesting data from it and storing them internally,
293 * then serving them one piece at a time.
295 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
296 const char *pem_header,
297 const unsigned char *blob,
298 size_t len, void **pctx,
300 const UI_METHOD *ui_method,
301 void *ui_data, const char *uri,
302 OSSL_LIB_CTX *libctx,
305 OSSL_STORE_INFO *store_info = NULL;
306 STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
309 /* Initial parsing */
312 if (pem_name != NULL)
313 /* No match, there is no PEM PKCS12 tag */
316 if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
318 char tpass[PEM_BUFSIZE];
319 EVP_PKEY *pkey = NULL;
321 STACK_OF(X509) *chain = NULL;
325 if (!PKCS12_mac_present(p12)
326 || 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", 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,
438 OSSL_LIB_CTX *libctx,
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,
513 OSSL_LIB_CTX *libctx,
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_ex(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,
642 OSSL_LIB_CTX *libctx,
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,
678 OSSL_LIB_CTX *libctx,
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,
756 OSSL_LIB_CTX *libctx,
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_ex(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,
812 OSSL_LIB_CTX *libctx,
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 */
906 OSSL_LIB_CTX *libctx;
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_ex
945 (const OSSL_STORE_LOADER *loader, const char *uri,
946 OSSL_LIB_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_ex(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 OSSL_LIB_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_ex(OSSL_STORE_SEARCH_get0_name(search),
1160 BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1166 ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1170 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1171 const char *pem_name,
1172 const char *pem_header,
1173 unsigned char *data, size_t len,
1174 const UI_METHOD *ui_method,
1175 void *ui_data, int *matchcount)
1177 OSSL_STORE_INFO *result = NULL;
1178 BUF_MEM *new_mem = NULL;
1179 char *new_pem_name = NULL;
1185 void *handler_ctx = NULL;
1186 const FILE_HANDLER **matching_handlers =
1187 OPENSSL_zalloc(sizeof(*matching_handlers)
1188 * OSSL_NELEM(file_handlers));
1190 if (matching_handlers == NULL) {
1191 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1196 for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1197 const FILE_HANDLER *handler = file_handlers[i];
1198 int try_matchcount = 0;
1199 void *tmp_handler_ctx = NULL;
1200 OSSL_STORE_INFO *tmp_result;
1205 handler->try_decode(pem_name, pem_header, data, len,
1206 &tmp_handler_ctx, &try_matchcount,
1207 ui_method, ui_data, ctx->uri,
1208 ctx->libctx, ctx->propq);
1209 /* avoid flooding error queue with low-level ASN.1 parse errors */
1210 err = ERR_peek_last_error();
1211 if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1212 && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1215 ERR_clear_last_mark();
1217 if (try_matchcount > 0) {
1219 matching_handlers[*matchcount] = handler;
1222 handler->destroy_ctx(&handler_ctx);
1223 handler_ctx = tmp_handler_ctx;
1225 if ((*matchcount += try_matchcount) > 1) {
1226 /* more than one match => ambiguous, kill any result */
1227 store_info_free(result);
1228 store_info_free(tmp_result);
1229 if (handler->destroy_ctx != NULL)
1230 handler->destroy_ctx(&handler_ctx);
1236 result = tmp_result;
1237 if (result == NULL) /* e.g., PKCS#12 file decryption error */
1243 && *matchcount == 1 && matching_handlers[0]->repeatable) {
1244 ctx->_.file.last_handler = matching_handlers[0];
1245 ctx->_.file.last_handler_ctx = handler_ctx;
1248 OPENSSL_free(matching_handlers);
1252 OPENSSL_free(new_pem_name);
1253 BUF_MEM_free(new_mem);
1256 && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1257 struct embedded_st *embedded = get0_EMBEDDED(result);
1259 /* "steal" the embedded data */
1260 pem_name = new_pem_name = embedded->pem_name;
1261 new_mem = embedded->blob;
1262 data = (unsigned char *)new_mem->data;
1263 len = new_mem->length;
1264 embedded->pem_name = NULL;
1265 embedded->blob = NULL;
1267 store_info_free(result);
1275 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1276 const UI_METHOD *ui_method,
1279 OSSL_STORE_INFO *result = NULL;
1280 int try_matchcount = 0;
1282 if (ctx->_.file.last_handler != NULL) {
1284 ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1285 &ctx->_.file.last_handler_ctx,
1287 ui_method, ui_data, ctx->uri,
1288 ctx->libctx, ctx->propq);
1290 if (result == NULL) {
1291 ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1292 ctx->_.file.last_handler_ctx = NULL;
1293 ctx->_.file.last_handler = NULL;
1299 static void pem_free_flag(void *pem_data, int secure, size_t num)
1302 OPENSSL_secure_clear_free(pem_data, num);
1304 OPENSSL_free(pem_data);
1306 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1307 unsigned char **data, long *len,
1308 const UI_METHOD *ui_method, void *ui_data,
1309 const char *uri, int secure)
1312 ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1313 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1314 : PEM_read_bio(bp, pem_name, pem_header, data, len);
1320 * 10 is the number of characters in "Proc-Type:", which
1321 * PEM_get_EVP_CIPHER_INFO() requires to be present.
1322 * If the PEM header has less characters than that, it's
1323 * not worth spending cycles on it.
1325 if (strlen(*pem_header) > 10) {
1326 EVP_CIPHER_INFO cipher;
1327 struct pem_pass_data pass_data;
1329 if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1330 || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1332 || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1340 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1342 OSSL_STORE_INFO *result = NULL;
1346 unsigned int magic = 0, bitlen = 0;
1348 unsigned char peekbuf[16] = { 0, };
1349 const unsigned char *p = peekbuf;
1351 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1353 if (!ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1361 EVP_PKEY *tmp = ispub
1362 ? b2i_PublicKey_bio(bp)
1363 : b2i_PrivateKey_bio(bp);
1366 || (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 OSSL_STORE_INFO *result = NULL;
1382 unsigned int saltlen = 0, keylen = 0;
1383 unsigned char peekbuf[24] = { 0, };
1384 const unsigned char *p = peekbuf;
1386 if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1388 if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1395 EVP_PKEY *tmp = NULL;
1396 struct pem_pass_data pass_data;
1398 if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1400 || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1401 || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1410 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1412 BUF_MEM *mem = NULL;
1414 if (asn1_d2i_read_bio(bp, &mem) < 0)
1417 *data = (unsigned char *)mem->data;
1418 *len = (long)mem->length;
1424 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1427 assert(name != NULL);
1428 assert(data != NULL);
1430 const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
1431 long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1432 + strlen(name) + 1 /* \0 */;
1434 *data = OPENSSL_zalloc(calculated_length);
1435 if (*data == NULL) {
1436 ATTICerr(0, ERR_R_MALLOC_FAILURE);
1440 OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1441 OPENSSL_strlcat(*data, pathsep, calculated_length);
1442 OPENSSL_strlcat(*data, name, calculated_length);
1447 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1449 const char *p = NULL;
1451 /* If there are no search criteria, all names are accepted */
1452 if (ctx->_.dir.search_name[0] == '\0')
1455 /* If the expected type isn't supported, no name is accepted */
1456 if (ctx->expected_type != 0
1457 && ctx->expected_type != OSSL_STORE_INFO_CERT
1458 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1462 * First, check the basename
1464 if (strncasecmp(name, ctx->_.dir.search_name,
1465 sizeof(ctx->_.dir.search_name) - 1) != 0
1466 || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1468 p = &name[sizeof(ctx->_.dir.search_name)];
1471 * Then, if the expected type is a CRL, check that the extension starts
1476 if (ctx->expected_type != 0
1477 && ctx->expected_type != OSSL_STORE_INFO_CRL)
1479 } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1484 * Last, check that the rest of the extension is a decimal number, at
1485 * least one digit long.
1494 * One extra step here, check for a possible generation number.
1497 for (p++; *p != '\0'; p++)
1498 if (!ossl_isdigit(*p))
1503 * If we've reached the end of the string at this point, we've successfully
1504 * found a fitting file name.
1509 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1510 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1511 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1512 const UI_METHOD *ui_method,
1515 OSSL_STORE_INFO *result = NULL;
1519 if (ctx->type == is_dir) {
1521 char *newname = NULL;
1523 if (ctx->_.dir.last_entry == NULL) {
1524 if (!ctx->_.dir.end_reached) {
1525 assert(ctx->_.dir.last_errno != 0);
1526 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1532 if (ctx->_.dir.last_entry[0] != '.'
1533 && file_name_check(ctx, ctx->_.dir.last_entry)
1534 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1538 * On the first call (with a NULL context), OPENSSL_DIR_read()
1539 * cares about the second argument. On the following calls, it
1540 * only cares that it isn't NULL. Therefore, we can safely give
1543 ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1544 ctx->_.dir.last_errno = errno;
1545 if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1546 ctx->_.dir.end_reached = 1;
1549 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1550 OPENSSL_free(newname);
1551 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1554 } while (result == NULL && !file_eof(ctx));
1556 int matchcount = -1;
1559 result = file_load_try_repeat(ctx, ui_method, ui_data);
1567 char *pem_name = NULL; /* PEM record name */
1568 char *pem_header = NULL; /* PEM record header */
1569 unsigned char *data = NULL; /* DER encoded data */
1570 long len = 0; /* DER encoded data length */
1573 if (ctx->type == is_pem) {
1574 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1575 &data, &len, ui_method, ui_data, ctx->uri,
1576 (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1581 if ((result = file_try_read_msblob(ctx->_.file.file,
1582 &matchcount)) != NULL
1583 || (result = file_try_read_PVK(ctx->_.file.file,
1584 ui_method, ui_data, ctx->uri,
1585 &matchcount)) != NULL)
1588 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1594 result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1595 ui_method, ui_data, &matchcount);
1601 * If a PEM name matches more than one handler, the handlers are
1604 if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1609 if (matchcount > 1) {
1610 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1611 } else if (matchcount == 1) {
1613 * If there are other errors on the stack, they already show
1614 * what the problem is.
1616 if (ERR_peek_error() == 0) {
1617 ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1618 if (pem_name != NULL)
1619 ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1626 pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1627 pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1628 pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1629 } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1631 /* We bail out on ambiguity */
1632 if (matchcount > 1) {
1633 store_info_free(result);
1638 && ctx->expected_type != 0
1639 && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1640 store_info_free(result);
1648 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1650 return ctx->errcnt > 0;
1653 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1655 if (ctx->type == is_dir)
1656 return ctx->_.dir.end_reached;
1658 if (ctx->_.file.last_handler != NULL
1659 && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1661 return BIO_eof(ctx->_.file.file);
1664 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1666 if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1667 if (ctx->type == is_dir)
1668 OPENSSL_DIR_end(&ctx->_.dir.ctx);
1670 BIO_free_all(ctx->_.file.file);
1673 * Because file_attach() called file_find_type(), we know that a
1674 * BIO_f_buffer() has been pushed on top of the regular BIO.
1676 BIO *buff = ctx->_.file.file;
1679 (void)BIO_pop(ctx->_.file.file);
1680 /* Safety measure */
1681 ctx->_.file.file = NULL;
1685 OSSL_STORE_LOADER_CTX_free(ctx);
1693 static const char *loader_attic_id = "loader_attic";
1694 static const char *loader_attic_name = "'file:' loader";
1696 static OSSL_STORE_LOADER *loader_attic = NULL;
1698 static int loader_attic_init(ENGINE *e)
1704 static int loader_attic_finish(ENGINE *e)
1710 static int loader_attic_destroy(ENGINE *e)
1712 OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1717 ERR_unload_ATTIC_strings();
1718 OSSL_STORE_LOADER_free(loader);
1722 static int bind_loader_attic(ENGINE *e)
1725 /* Ensure the ATTIC error handling is set up on best effort basis */
1726 ERR_load_ATTIC_strings();
1728 if (/* Create the OSSL_STORE_LOADER */
1729 (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1730 || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
1731 || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1732 || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1733 || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1734 || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1735 || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1736 || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1737 || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1738 || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1739 || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1740 /* Init the engine itself */
1741 || !ENGINE_set_id(e, loader_attic_id)
1742 || !ENGINE_set_name(e, loader_attic_name)
1743 || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1744 || !ENGINE_set_init_function(e, loader_attic_init)
1745 || !ENGINE_set_finish_function(e, loader_attic_finish)
1746 /* Finally, register the method with libcrypto */
1747 || !OSSL_STORE_register_loader(loader_attic)) {
1748 OSSL_STORE_LOADER_free(loader_attic);
1749 loader_attic = NULL;
1750 ATTICerr(0, ATTIC_R_INIT_FAILED);
1757 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1758 # error "Only allowed as dynamically shared object"
1761 static int bind_helper(ENGINE *e, const char *id)
1763 if (id && (strcmp(id, loader_attic_id) != 0))
1765 if (!bind_loader_attic(e))
1770 IMPLEMENT_DYNAMIC_CHECK_FN()
1771 IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)