feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter

This commit is contained in:
faumaray committed 2026-11-25 06:28:50 +03:00
1 parent 8a1c15f9c0
commit eb42228604
14 files changed
+2448 -90

No files matched your search

+658 -85
View File
@@ -1,48 +1,226 @@
#include <Void/Crypto/Crypto.hpp>
#include <array>
#include <cstdint>
#include <cstring>
#include <format>
#include <fstream>
#include <limits>
#include <utility>
#include <openssl/core_names.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/params.h>
namespace Void::Crypto
{
namespace
{
[[nodiscard]] const EVP_MD*
algorithm_impl(HashAlgorithm algorithm) noexcept
thread_local FaultConfig g_fault_config{};
thread_local std::size_t g_fault_hits{0};
[[nodiscard]] std::optional<Void::Result::Error>
maybe_inject_fault(FaultOperation op, std::string_view operation)
{
if (g_fault_config.op == FaultOperation::none) {
return std::nullopt;
}
if (g_fault_config.op != FaultOperation::any &&
g_fault_config.op != op) {
return std::nullopt;
}
if (g_fault_hits < g_fault_config.fail_after) {
++g_fault_hits;
return std::nullopt;
}
++g_fault_hits;
return make_crypto_error(
g_fault_config.code,
std::format("{}: injected crypto backend fault", operation));
}
[[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept
{
switch (algorithm) {
case HashAlgorithm::Sha1:
return EVP_sha1();
return "SHA1";
case HashAlgorithm::Sha256:
return EVP_sha256();
return "SHA256";
case HashAlgorithm::Sha512:
return EVP_sha512();
return "SHA512";
}
return nullptr;
}
[[nodiscard]] std::string openssl_error(std::string_view operation)
[[nodiscard]] const char*
propq_or_null(const ProviderOptions& provider) noexcept
{
const unsigned long code = ERR_get_error();
if (code == 0) {
return std::string{operation};
return provider.property_query.empty()
? nullptr
: provider.property_query.c_str();
}
[[nodiscard]] Void::Result::Error
make_openssl_error(CryptoErrorCode code, std::string_view operation)
{
const unsigned long err_code = ERR_get_error();
ERR_clear_error();
if (err_code == 0) {
return make_crypto_error(code, std::string{operation});
}
std::array<char, 256> buffer{};
ERR_error_string_n(code, buffer.data(), buffer.size());
return std::format("{}: {}", operation, buffer.data());
ERR_error_string_n(err_code, buffer.data(), buffer.size());
return make_crypto_error(
code, std::format("{}: {}", operation, buffer.data()));
}
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
using EvpMdPtr = std::unique_ptr<EVP_MD, decltype(&EVP_MD_free)>;
using EvpMdCtxPtr =
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
using EvpPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using EvpMacPtr = std::unique_ptr<EVP_MAC, decltype(&EVP_MAC_free)>;
using EvpMacCtxPtr =
std::unique_ptr<EVP_MAC_CTX, decltype(&EVP_MAC_CTX_free)>;
using EvpKdfPtr = std::unique_ptr<EVP_KDF, decltype(&EVP_KDF_free)>;
using EvpKdfCtxPtr =
std::unique_ptr<EVP_KDF_CTX, decltype(&EVP_KDF_CTX_free)>;
[[nodiscard]] const unsigned char*
non_null_bytes(std::span<const std::byte> span) noexcept
{
static constexpr unsigned char kEmptyByte = 0;
return span.empty()
? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data());
}
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message,
std::span<const std::byte> signature,
std::span<const std::byte> public_key,
const ProviderOptions& provider)
{
if (signature.size() != Ed25519SignatureSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_signature_size,
std::format("Crypto::verifyEd25519: signature must be {} "
"bytes",
Ed25519SignatureSize))};
}
if (public_key.size() != Ed25519PublicKeySize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::verifyEd25519: public key must be {} "
"bytes",
Ed25519PublicKeySize))};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::verifyEd25519: message exceeds {} "
"byte one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_verify,
"Crypto::verifyEd25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
nullptr, "ED25519", propq,
non_null_bytes(public_key), public_key.size()),
&EVP_PKEY_free};
if (!key) {
const auto code =
provider.property_query.empty()
? CryptoErrorCode::backend_error
: CryptoErrorCode::provider_error;
return std::unexpected{make_openssl_error(
code, "Crypto::verifyEd25519: invalid public key or "
"unavailable provider")};
}
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestVerifyInit_ex(context.get(), nullptr, nullptr,
nullptr, propq, key.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::verifyEd25519: initialization failed")};
}
const int result = EVP_DigestVerify(
context.get(), non_null_bytes(signature), signature.size(),
non_null_bytes(message), message.size());
if (result < 0) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::verifyEd25519 failed")};
}
ERR_clear_error();
return result == 1;
}
} // namespace
void secure_wipe(std::span<std::byte> buffer) noexcept
{
if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size());
}
}
bool constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
if (lhs.empty()) {
return true;
}
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
}
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
: m_previous(g_fault_config), m_previous_hits(g_fault_hits)
{
g_fault_config = config;
g_fault_hits = 0;
}
ScopedFaultGuard::~ScopedFaultGuard() noexcept
{
g_fault_config = m_previous;
g_fault_hits = m_previous_hits;
}
struct Hasher::Impl {
EVP_MD_CTX* context{nullptr};
const EVP_MD* algorithm{nullptr};
bool finalized{false};
~Impl() { EVP_MD_CTX_free(context); }
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
HasherState state{HasherState::Ready};
};
Hasher::Hasher(std::unique_ptr<Impl> impl) noexcept
@@ -53,36 +231,85 @@ namespace Void::Crypto
Hasher::Hasher(Hasher&&) noexcept = default;
Hasher& Hasher::operator=(Hasher&&) noexcept = default;
HasherState Hasher::state() const noexcept
{
return m_impl ? m_impl->state : HasherState::MovedFrom;
}
Void::Result::Result<Hasher> Hasher::create(HashAlgorithm algorithm)
{
return create(algorithm, ProviderOptions{});
}
Void::Result::Result<Hasher>
Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider)
{
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
auto impl = std::make_unique<Impl>();
impl->algorithm = algorithm_impl(algorithm);
if (impl->algorithm == nullptr) {
return Void::Result::fail("Crypto::Hasher: unsupported algorithm");
impl->algorithm = EvpMdPtr{
EVP_MD_fetch(nullptr, md_name, propq_or_null(provider)),
&EVP_MD_free};
if (!impl->algorithm) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: EVP_MD_fetch failed")};
}
impl->context = EVP_MD_CTX_new();
if (impl->context == nullptr) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed"));
impl->context = EvpMdCtxPtr{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!impl->context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: EVP_MD_CTX_new failed")};
}
if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher: digest initialization failed"));
if (EVP_DigestInit_ex2(impl->context.get(), impl->algorithm.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")};
}
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::update: hasher is finalized or moved-from");
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is moved-from")};
}
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::update: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_update,
"Crypto::Hasher::update");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (!data.empty() &&
EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::update failed"));
EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) {
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update failed")};
}
m_impl->state = HasherState::Updating;
return {};
}
@@ -93,24 +320,41 @@ namespace Void::Crypto
Void::Result::Result<Digest> Hasher::finalize()
{
if (!m_impl || m_impl->finalized) {
return Void::Result::fail(
"Crypto::Hasher::finalize: hasher is finalized or moved-from");
if (!m_impl) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is moved-from")};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm);
if (m_impl->state == HasherState::Finalized ||
m_impl->state == HasherState::Failed) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Hasher::finalize: hasher is finalized or failed")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_finalize,
"Crypto::Hasher::finalize");
fault.has_value()) {
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) {
return Void::Result::fail(
"Crypto::Hasher::finalize: invalid digest size");
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid digest size")};
}
Digest digest(static_cast<std::size_t>(digest_size));
unsigned int written = 0;
if (EVP_DigestFinal_ex(m_impl->context,
if (EVP_DigestFinal_ex(m_impl->context.get(),
reinterpret_cast<unsigned char*>(digest.data()),
&written) != 1) {
return Void::Result::fail(
openssl_error("Crypto::Hasher::finalize failed"));
m_impl->state = HasherState::Failed;
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize failed")};
}
m_impl->finalized = true;
m_impl->state = HasherState::Finalized;
digest.resize(written);
return digest;
}
@@ -118,7 +362,13 @@ namespace Void::Crypto
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
-> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm);
return hash(algorithm, data, ProviderOptions{});
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data,
const ProviderOptions& provider) -> Void::Result::Result<Digest>
{
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
@@ -137,17 +387,26 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hashFile(algorithm, path, ProviderOptions{});
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: cannot open '{}'", path.string()));
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'",
path.string()))};
}
auto hasher = Hasher::create(algorithm);
auto hasher = Hasher::create(algorithm, provider);
if (!hasher) {
return std::unexpected{hasher.error()};
}
std::array<char, 64 * 1024> buffer{};
std::array<char, CryptoLimits::kStreamChunkBytes> buffer{};
while (input) {
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
@@ -160,9 +419,11 @@ namespace Void::Crypto
}
}
}
if (input.bad()) {
return Void::Result::fail(std::format(
"Crypto::hashFile: I/O error reading '{}'", path.string()));
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'",
path.string()))};
}
return hasher->finalize();
}
@@ -204,54 +465,366 @@ namespace Void::Crypto
return hashFile(HashAlgorithm::Sha512, path);
}
struct Ed25519PrivateKey::Impl {
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
};
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
Ed25519PrivateKey::~Ed25519PrivateKey() = default;
Ed25519PrivateKey::Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept =
default;
Ed25519PrivateKey&
Ed25519PrivateKey::operator=(Ed25519PrivateKey&&) noexcept = default;
bool Ed25519PrivateKey::valid() const noexcept
{
return m_impl != nullptr && m_impl->pkey != nullptr;
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::generate(const ProviderOptions& provider)
{
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_keygen,
"Crypto::Ed25519PrivateKey::generate");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::generate failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PrivateKey>
Ed25519PrivateKey::from_raw_seed(std::span<const std::byte> seed,
const ProviderOptions& provider)
{
if (seed.size() != Ed25519SeedSize) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_key_size,
std::format("Crypto::Ed25519PrivateKey::from_raw_seed: seed "
"must be {} bytes",
Ed25519SeedSize))};
}
if (auto fault = maybe_inject_fault(
FaultOperation::ed25519_import,
"Crypto::Ed25519PrivateKey::from_raw_seed");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider),
non_null_bytes(seed), seed.size()),
&EVP_PKEY_free};
if (!key) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::Ed25519PrivateKey::from_raw_seed failed")};
}
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
}
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")};
}
Ed25519PublicKey pub;
std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(pub.bytes.data()),
&len) != 1 ||
len != Ed25519PublicKeySize) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::public_key failed")};
}
return pub;
}
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
{
if (!valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")};
}
std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key(
m_impl->pkey.get(),
reinterpret_cast<unsigned char*>(raw.data()), &len) != 1 ||
len != Ed25519SeedSize) {
secure_wipe(raw);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::Ed25519PrivateKey::export_raw_seed failed")};
}
auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw);
return result;
}
Void::Result::Result<Ed25519Signature>
sign_ed25519(std::span<const std::byte> message,
const Ed25519PrivateKey& private_key,
const ProviderOptions& provider)
{
if (!private_key.valid()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_state,
"Crypto::sign_ed25519: private key is invalid or moved-from")};
}
if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::message_too_large,
std::format("Crypto::sign_ed25519: message exceeds {} byte "
"one-shot limit",
CryptoLimits::kMaxOneShotMessageBytes))};
}
if (auto fault = maybe_inject_fault(FaultOperation::ed25519_sign,
"Crypto::sign_ed25519");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519: EVP_MD_CTX_new failed")};
}
if (EVP_DigestSignInit_ex(context.get(), nullptr, nullptr, nullptr,
propq_or_null(provider),
private_key.m_impl->pkey.get(),
nullptr) != 1) {
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::sign_ed25519: initialization failed")};
}
Ed25519Signature signature;
std::size_t sig_len = signature.bytes.size();
if (EVP_DigestSign(
context.get(),
reinterpret_cast<unsigned char*>(signature.bytes.data()),
&sig_len, non_null_bytes(message), message.size()) != 1 ||
sig_len != Ed25519SignatureSize) {
secure_wipe(signature.bytes);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::sign_ed25519 failed")};
}
return signature;
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
std::span<const std::byte>
signature,
std::span<const std::byte>
publicKey)
{
if (signature.size() != Ed25519SignatureSize) {
return Void::Result::fail(
std::format("Crypto::verifyEd25519: signature must be {} bytes",
Ed25519SignatureSize));
return verify_ed25519_impl(message, signature, publicKey,
ProviderOptions{});
}
Void::Result::Result<bool>
verify_ed25519(std::span<const std::byte> message,
const Ed25519Signature& signature,
const Ed25519PublicKey& public_key,
const ProviderOptions& provider)
{
return verify_ed25519_impl(message, signature.view(), public_key.view(),
provider);
}
Void::Result::Result<void>
hmac_sha256_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider)
{
if (output.size() != HmacSha256Size) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
std::format("Crypto::hmac_sha256_into: output must be {} bytes",
HmacSha256Size))};
}
if (publicKey.size() != Ed25519PublicKeySize) {
return Void::Result::fail(std::format(
"Crypto::verifyEd25519: public key must be {} bytes",
Ed25519PublicKeySize));
if (spans_overlap(secret_key, output) ||
spans_overlap(message, output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hmac_sha256_into: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hmac,
"Crypto::hmac_sha256_into");
fault.has_value()) {
secure_wipe(output);
return std::unexpected{std::move(*fault)};
}
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
Key key{EVP_PKEY_new_raw_public_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(publicKey.data()),
publicKey.size()),
&EVP_PKEY_free};
if (!key) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: invalid public key"));
ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free};
if (!mac) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_fetch failed")};
}
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed"));
EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free};
if (!ctx) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")};
}
if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr,
key.get()) != 1) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519: initialization failed"));
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 2> params = {
OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_end(),
};
if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key),
secret_key.size(), params.data()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: EVP_MAC_init failed")};
}
const int result = EVP_DigestVerify(
context.get(),
reinterpret_cast<const unsigned char*>(signature.data()),
signature.size(),
reinterpret_cast<const unsigned char*>(message.data()),
message.size());
if (result < 0) {
return Void::Result::fail(
openssl_error("Crypto::verifyEd25519 failed"));
if (!message.empty() &&
EVP_MAC_update(ctx.get(), non_null_bytes(message),
message.size()) != 1) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_update failed")};
}
return result == 1;
std::size_t out_len = 0;
if (EVP_MAC_final(ctx.get(),
reinterpret_cast<unsigned char*>(output.data()),
&out_len, output.size()) != 1 ||
out_len != HmacSha256Size) {
secure_wipe(output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
}
return {};
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider)
{
Digest out(HmacSha256Size);
if (auto res = hmac_sha256_into(secret_key, message, out, provider);
!res.has_value()) {
secure_wipe(out);
return std::unexpected{std::move(res.error())};
}
return out;
}
Void::Result::Result<void>
hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output,
const ProviderOptions& provider)
{
if (secret_output.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"Crypto::hkdf_sha256: output buffer must be non-empty")};
}
if (secret_output.size() > CryptoLimits::kMaxHkdfOutputBytes) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::output_too_large,
std::format("Crypto::hkdf_sha256: output size exceeds {} byte "
"cap",
CryptoLimits::kMaxHkdfOutputBytes))};
}
if (spans_overlap(secret_input, secret_output) ||
spans_overlap(salt, secret_output) ||
spans_overlap(context, secret_output)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::overlapping_buffers,
"Crypto::hkdf_sha256: output buffer overlaps input")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hkdf,
"Crypto::hkdf_sha256");
fault.has_value()) {
secure_wipe(secret_output);
return std::unexpected{std::move(*fault)};
}
ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free};
if (!kdf) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: EVP_KDF_fetch failed")};
}
EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free};
if (!ctx) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_CTX_new failed")};
}
char digest_name[] = "SHA256";
std::array<OSSL_PARAM, 5> params = {
OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name,
0),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_KEY,
const_cast<unsigned char*>(non_null_bytes(secret_input)),
secret_input.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_SALT,
const_cast<unsigned char*>(non_null_bytes(salt)), salt.size()),
OSSL_PARAM_construct_octet_string(
OSSL_KDF_PARAM_INFO,
const_cast<unsigned char*>(non_null_bytes(context)),
context.size()),
OSSL_PARAM_construct_end(),
};
if (EVP_KDF_derive(
ctx.get(),
reinterpret_cast<unsigned char*>(secret_output.data()),
secret_output.size(), params.data()) != 1) {
secure_wipe(secret_output);
return std::unexpected{make_openssl_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: EVP_KDF_derive failed")};
}
return {};
}
} // namespace Void::Crypto
+2
View File
@@ -1,4 +1,6 @@
void_add_module(Crypto
INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto
EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp
)
+522
View File
@@ -0,0 +1,522 @@
#include <Void/Crypto/AsyncHash.hpp>
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <format>
#include <fstream>
#include <functional>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>
namespace Void::CryptoAsync
{
namespace
{
[[nodiscard]] Void::Result::Error
map_io_error(const Void::Result::Error& err)
{
if (err.kind() == Void::Result::ErrorKind::cancelled) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::cancelled, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::timeout) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout, err.message(),
err.system_code());
}
if (err.kind() == Void::Result::ErrorKind::exhausted) {
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::resource_exhausted,
err.message(), err.system_code());
}
return Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::io_error, err.message(),
err.system_code());
}
} // namespace
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
hash_stream(Void::Crypto::HashAlgorithm algorithm,
Void::IO::Driver& driver, Void::IO::ByteStream& stream,
Void::Async::OperationOptions options,
StreamHashOptions hash_options)
{
using namespace Void::Crypto;
if (hash_options.chunk_bytes == 0 ||
hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")};
}
if (!stream.valid()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::hash_stream: stream is invalid or closed")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: operation stopped before start")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired before start")};
}
auto hasher = Hasher::create(algorithm, hash_options.provider);
if (!hasher.has_value()) {
co_return std::unexpected{std::move(hasher.error())};
}
auto lease = driver.allocate_buffer(hash_options.chunk_bytes);
if (!lease.has_value()) {
co_return std::unexpected{map_io_error(lease.error())};
}
for (;;) {
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped between chunks")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired between chunks")};
}
auto transfer = co_await stream.read_some_owned(*lease, options);
if (!transfer.has_value()) {
co_return std::unexpected{map_io_error(transfer.error())};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped during stream read")};
}
if (Void::Async::is_deadline_expired(options, driver.clock())) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::hash_stream: deadline expired after read")};
}
if (transfer->bytes > 0) {
if (auto upd = hasher->update(lease->readable());
!upd.has_value()) {
co_return std::unexpected{std::move(upd.error())};
}
}
if (transfer->eof) {
break;
}
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::hash_stream: stopped before finalize")};
}
co_return hasher->finalize();
}
struct AsyncFileHasher::State : std::enable_shared_from_this<State> {
struct Job {
Job(Void::Crypto::HashAlgorithm alg,
std::filesystem::path p,
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
o)
: algorithm(alg), path(std::move(p)), op(std::move(o))
{
}
Void::Crypto::HashAlgorithm algorithm;
std::filesystem::path path;
std::shared_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>
op;
std::optional<std::stop_callback<std::function<void()>>>
cancel_cb{};
};
State(Void::Async::Executor& exec, FileHasherOptions opts,
const Void::Time::MonotonicClock& clk)
: executor(exec), options(std::move(opts)), clock(clk)
{
}
void start_workers_locked()
{
if (workers_started || options.max_concurrent == 0) {
return;
}
workers_started = true;
const std::size_t count =
std::max<std::size_t>(1, options.max_concurrent);
workers.reserve(count);
auto self = shared_from_this();
for (std::size_t i = 0; i < count; ++i) {
workers.emplace_back([self] { self->worker_loop(); });
}
}
void worker_loop()
{
for (;;) {
std::shared_ptr<Job> job;
{
std::unique_lock lk{mu};
cv.wait(lk, [this] {
if (closing) {
return true;
}
if (queue.empty()) {
return false;
}
if (active < options.max_concurrent &&
reserved_bytes + options.chunk_bytes <=
options.buffer_budget_bytes) {
return true;
}
return std::any_of(
queue.begin(), queue.end(),
[this](const auto& j) {
return j->op->stop_requested() ||
j->op->is_deadline_expired(clock);
});
});
// Purge any already-cancelled or expired jobs in queue.
std::vector<std::pair<std::shared_ptr<Job>,
Void::Result::Error>>
dropped_jobs;
for (auto it = queue.begin(); it != queue.end();) {
auto& item = *it;
if (closing || item->op->stop_requested()) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
closing
? Void::Crypto::CryptoErrorCode::closed
: Void::Crypto::CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: job cancelled while queued"));
it = queue.erase(it);
} else if (item->op->is_deadline_expired(clock)) {
dropped_jobs.emplace_back(
std::move(item),
Void::Crypto::make_crypto_error(
Void::Crypto::CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired while queued"));
it = queue.erase(it);
} else {
++it;
}
}
if (!dropped_jobs.empty()) {
lk.unlock();
for (auto& [dropped, err] : dropped_jobs) {
dropped->cancel_cb.reset();
const auto kind =
(err.kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
auto ticket = dropped->op->try_commit_error(
std::move(err), kind);
if (ticket.has_value()) {
ticket->dispatch();
}
dropped->op->release_backend_ref_and_dispatch();
}
lk.lock();
}
if (closing && queue.empty()) {
return;
}
if (queue.empty() || active >= options.max_concurrent ||
reserved_bytes + options.chunk_bytes >
options.buffer_budget_bytes) {
continue;
}
job = std::move(queue.front());
queue.pop_front();
++active;
reserved_bytes += options.chunk_bytes;
in_flight.push_back(job->op);
}
job->cancel_cb.reset();
auto result = run_job(*job);
{
std::lock_guard lk{mu};
--active;
reserved_bytes -= options.chunk_bytes;
++completed;
std::erase_if(in_flight, [&](const auto& weak_op) {
auto sp = weak_op.lock();
return !sp || sp == job->op;
});
}
cv.notify_all();
std::optional<Void::Async::ResumeTicket> ticket;
if (result.has_value()) {
ticket = job->op->try_commit_value(std::move(*result));
} else {
const auto kind =
(result.error().kind() ==
Void::Result::ErrorKind::cancelled)
? Void::Async::DomainOutcomeKind::cancelled
: Void::Async::DomainOutcomeKind::failed;
ticket = job->op->try_commit_error(
std::move(result.error()), kind);
}
if (ticket.has_value()) {
ticket->dispatch();
}
job->op->release_backend_ref_and_dispatch();
}
}
[[nodiscard]] Void::Result::Result<Void::Crypto::Digest>
run_job(const Job& job) const
{
using namespace Void::Crypto;
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: cancelled before open")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before open")};
}
std::ifstream input{job.path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: cannot open '{}'",
job.path.string()))};
}
auto hasher = Hasher::create(job.algorithm, options.provider);
if (!hasher.has_value()) {
return std::unexpected{std::move(hasher.error())};
}
std::vector<char> buffer(options.chunk_bytes);
while (input) {
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped during file read")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired during read")};
}
input.read(buffer.data(),
static_cast<std::streamsize>(buffer.size()));
const auto count = input.gcount();
if (count > 0) {
const auto bytes = std::as_bytes(std::span{
buffer.data(), static_cast<std::size_t>(count)});
if (auto upd = hasher->update(bytes);
!upd.has_value()) {
return std::unexpected{std::move(upd.error())};
}
}
}
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format(
"CryptoAsync::AsyncFileHasher: I/O error reading '{}'",
job.path.string()))};
}
if (job.op->stop_requested()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before finalize")};
}
if (job.op->is_deadline_expired(clock)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before finalize")};
}
return hasher->finalize();
}
Void::Async::Executor& executor;
FileHasherOptions options;
const Void::Time::MonotonicClock& clock;
mutable std::mutex mu{};
std::condition_variable cv{};
std::deque<std::shared_ptr<Job>> queue{};
std::vector<std::weak_ptr<
Void::Async::OperationState<Void::Crypto::Digest>>>
in_flight{};
std::vector<std::thread> workers{};
bool workers_started{false};
bool closing{false};
bool joined{false};
std::size_t active{0};
std::size_t reserved_bytes{0};
std::uint64_t completed{0};
std::uint64_t rejected{0};
};
AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor,
FileHasherOptions options,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>(executor, std::move(options), clock))
{
}
AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); }
Void::Coro::Task<Void::Result::Result<Void::Crypto::Digest>>
AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm,
std::filesystem::path path,
Void::Async::OperationOptions options)
{
using namespace Void::Crypto;
auto state = m_state;
if (state->options.max_concurrent == 0 ||
state->options.chunk_bytes == 0 ||
state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::invalid_argument,
"CryptoAsync::AsyncFileHasher: invalid options")};
}
if (state->options.chunk_bytes > state->options.buffer_budget_bytes) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::resource_exhausted,
"CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")};
}
if (options.stop.stop_requested()) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::cancelled,
"CryptoAsync::AsyncFileHasher: stopped before admission")};
}
if (Void::Async::is_deadline_expired(options, state->clock)) {
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::timeout,
"CryptoAsync::AsyncFileHasher: deadline expired before admission")};
}
auto op = Void::Async::OperationState<Digest>::create(
options, &state->executor, Void::Async::StopBehavior::notify_only);
auto job = std::make_shared<State::Job>(algorithm, std::move(path), op);
{
std::lock_guard lk{state->mu};
if (state->closing) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::closed,
"CryptoAsync::AsyncFileHasher: service is closing")};
}
const std::size_t max_effective_concurrent = std::min(
state->options.max_concurrent,
state->options.buffer_budget_bytes / state->options.chunk_bytes);
const std::size_t capacity =
max_effective_concurrent + state->options.max_waiting;
if (state->active + state->queue.size() >= capacity) {
++state->rejected;
co_return std::unexpected{make_crypto_error(
CryptoErrorCode::overloaded,
"CryptoAsync::AsyncFileHasher: wait queue is full")};
}
op->acquire_backend_ref();
state->start_workers_locked();
if (options.stop.stop_possible()) {
std::weak_ptr<State> weak_state = state;
job->cancel_cb.emplace(options.stop, [weak_state]() {
if (auto s = weak_state.lock()) {
s->cv.notify_all();
}
});
}
state->queue.push_back(std::move(job));
}
state->cv.notify_one();
co_return co_await op->awaitable(&state->executor);
}
void AsyncFileHasher::request_stop() noexcept
{
std::vector<
std::shared_ptr<Void::Async::OperationState<Void::Crypto::Digest>>>
ops;
{
std::lock_guard lk{m_state->mu};
m_state->closing = true;
for (const auto& j : m_state->queue) {
ops.push_back(j->op);
}
for (const auto& weak_op : m_state->in_flight) {
if (auto sp = weak_op.lock()) {
ops.push_back(std::move(sp));
}
}
}
for (auto& op : ops) {
op->request_stop();
}
m_state->cv.notify_all();
}
Void::Result::Result<void> AsyncFileHasher::close_and_join()
{
request_stop();
std::vector<std::thread> threads;
{
std::lock_guard lk{m_state->mu};
if (m_state->joined) {
return {};
}
m_state->joined = true;
threads.swap(m_state->workers);
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return {};
}
FileHasherStats AsyncFileHasher::stats() const noexcept
{
std::lock_guard lk{m_state->mu};
return FileHasherStats{
.active = m_state->active,
.waiting = m_state->queue.size(),
.reserved_buffer_bytes = m_state->reserved_bytes,
.completed = m_state->completed,
.rejected = m_state->rejected,
.closing = m_state->closing,
};
}
} // namespace Void::CryptoAsync
+6
View File
@@ -0,0 +1,6 @@
void_add_module(CryptoAsync
INTERNAL_DEPS Crypto IO Async Time Functional
EXTERNAL_DEPS Threads::Threads
EXTRA_HEADERS
Void/Crypto/AsyncHash.hpp
)