feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter
This commit is contained in:
1 parent
8a1c15f9c0
commit
eb42228604
14 files changed
+2448
-90
No files matched your search
+658
-85
@@ -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
|
||||
Reference in new issue
Block a user