Files

422 lines
15 KiB
C++

#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
namespace
{
int hex_nibble(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
std::vector<std::byte> from_hex(std::string_view hex)
{
Void::Testing::require(hex.size() % 2 == 0);
std::vector<std::byte> out;
out.reserve(hex.size() / 2);
for (std::size_t i = 0; i < hex.size(); i += 2) {
const int hi = hex_nibble(hex[i]);
const int lo = hex_nibble(hex[i + 1]);
Void::Testing::require(hi >= 0 && lo >= 0);
out.push_back(static_cast<std::byte>((hi << 4) | lo));
}
return out;
}
std::string to_hex(std::span<const std::byte> data)
{
static constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (const std::byte b : data) {
const auto v = static_cast<unsigned char>(b);
out.push_back(kHex[v >> 4]);
out.push_back(kHex[v & 0x0F]);
}
return out;
}
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
} // namespace
Void::Testing::Test crypto_hasher_state_poisoning_and_provider_isolation()
{
using namespace Void::Crypto;
auto h = Hasher::create(HashAlgorithm::Sha256);
Void::Testing::require(h.has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Ready));
Void::Testing::require(h->update("ab").has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Updating));
// Inject mid-stream update failure -> hasher is permanently poisoned.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::hash_update,
CryptoErrorCode::backend_error, 0}};
auto bad = h->update("c");
Void::Testing::require(!bad.has_value());
Void::Testing::expect_eq(bad.error().code().domain,
Void::Result::kCryptoErrorDomain);
Void::Testing::expect_eq(
bad.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::backend_error));
}
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Failed));
auto retry_update = h->update("d");
Void::Testing::require(!retry_update.has_value());
Void::Testing::expect_eq(
retry_update.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
auto retry_finalize = h->finalize();
Void::Testing::require(!retry_finalize.has_value());
Void::Testing::expect_eq(
retry_finalize.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
// Moved-from state reports MovedFrom and fails cleanly.
Hasher moved = std::move(*h);
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::MovedFrom));
Void::Testing::expect(!h->update("x").has_value());
Void::Testing::expect(!moved.finalize().has_value());
// Per-context unavailable provider fails without breaking subsequent
// default-provider operations.
ProviderOptions bad_provider{.property_query = "provider=nonexistent_void"};
auto unavailable = Hasher::create(HashAlgorithm::Sha256, bad_provider);
Void::Testing::require(!unavailable.has_value());
Void::Testing::expect_eq(
unavailable.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
auto good = sha256("abc");
Void::Testing::require(good.has_value());
Void::Testing::expect_eq(
to_hex(*good),
std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f"
"20015ad"});
}
Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
{
using namespace Void::Crypto;
if (!has_openssl_backend()) {
auto gen_unavail = Ed25519PrivateKey::generate();
Void::Testing::require(!gen_unavail.has_value());
Void::Testing::expect_eq(
gen_unavail.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::unsupported_algorithm));
const std::array<std::byte, Ed25519PublicKeySize> dummy_pub{};
const std::array<std::byte, Ed25519SignatureSize> dummy_sig{};
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, dummy_sig, bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, dummy_pub);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(
CryptoErrorCode::invalid_signature_size));
}
return;
}
struct Rfc8032Vector {
std::string_view seed_hex;
std::string_view pub_hex;
std::string_view msg_hex;
std::string_view sig_hex;
};
const std::array<Rfc8032Vector, 3> vectors = {{
{"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
"",
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"},
{"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
"72",
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da"
"085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"},
{"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
"af82",
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac"
"18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"},
}};
for (const auto& vec : vectors) {
const auto seed = from_hex(vec.seed_hex);
const auto expected_pub = from_hex(vec.pub_hex);
const auto msg = from_hex(vec.msg_hex);
const auto expected_sig = from_hex(vec.sig_hex);
auto key = Ed25519PrivateKey::from_raw_seed(seed);
Void::Testing::require(key.has_value());
auto pub = key->public_key();
Void::Testing::require(pub.has_value());
Void::Testing::expect_eq(to_hex(pub->view()), std::string{vec.pub_hex});
auto exported = key->export_raw_seed();
Void::Testing::require(exported.has_value());
Void::Testing::expect(constant_time_equal(exported->view(), seed));
exported->clear();
Void::Testing::expect(!exported->valid());
Void::Testing::expect(exported->view().empty());
auto sig = sign_ed25519(msg, *key);
Void::Testing::require(sig.has_value());
Void::Testing::expect_eq(to_hex(sig->view()), std::string{vec.sig_hex});
auto verified = verify_ed25519(msg, *sig, *pub);
Void::Testing::require(verified.has_value());
Void::Testing::expect(*verified);
// Flipping a single signature bit yields false, NOT an error.
auto tampered_sig = *sig;
tampered_sig.bytes[0] ^= std::byte{0x01};
auto bad_verify = verify_ed25519(msg, tampered_sig, *pub);
Void::Testing::require(bad_verify.has_value());
Void::Testing::expect(!*bad_verify);
}
// Key generation round-trip.
auto generated = Ed25519PrivateKey::generate();
Void::Testing::require(generated.has_value());
auto gen_pub = generated->public_key();
Void::Testing::require(gen_pub.has_value());
auto gen_sig = sign_ed25519(as_bytes("hello ed25519"), *generated);
Void::Testing::require(gen_sig.has_value());
auto gen_ok =
verify_ed25519(as_bytes("hello ed25519"), *gen_sig, *gen_pub);
Void::Testing::require(gen_ok.has_value());
Void::Testing::expect(*gen_ok);
// Invalid sizes near boundaries must fail with typed invalid_argument.
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, gen_sig->view(), bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
auto import_r = Ed25519PrivateKey::from_raw_seed(bad_key);
Void::Testing::require(!import_r.has_value());
Void::Testing::expect_eq(
import_r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, gen_pub->view());
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_signature_size));
}
// Oversized message (>16 MiB) rejected before OpenSSL call.
std::vector<std::byte> huge(CryptoLimits::kMaxOneShotMessageBytes + 1U,
std::byte{0});
auto huge_sign = sign_ed25519(huge, *generated);
Void::Testing::require(!huge_sign.has_value());
Void::Testing::expect_eq(
huge_sign.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
auto huge_verify = verify_ed25519(huge, *gen_sig, *gen_pub);
Void::Testing::require(!huge_verify.has_value());
Void::Testing::expect_eq(
huge_verify.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
// Provider fault returns error without leaking secret key material.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::ed25519_sign,
CryptoErrorCode::provider_error, 0}};
auto failed = sign_ed25519(as_bytes("secret-free"), *generated);
Void::Testing::require(!failed.has_value());
Void::Testing::expect_eq(
failed.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
}
}
Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
{
using namespace Void::Crypto;
// RFC 4231 Case 1
{
const std::vector<std::byte> key(20, std::byte{0x0b});
auto mac = hmac_sha256(key, as_bytes("Hi There"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
"76c2e32cff7"});
}
// RFC 4231 Case 2
{
auto mac = hmac_sha256(as_bytes("Jefe"),
as_bytes("what do ya want for nothing?"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec5"
"8b964ec3843"});
}
// RFC 4231 Case 3
{
const std::vector<std::byte> key(20, std::byte{0xaa});
const std::vector<std::byte> msg(50, std::byte{0xdd});
auto mac = hmac_sha256(key, msg);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635"
"514ced565fe"});
}
// Empty key and empty message work cleanly.
{
auto mac = hmac_sha256({}, {});
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(mac->size(), HmacSha256Size);
}
// RFC 5869 Appendix A Case 1
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
const auto salt = from_hex("000102030405060708090a0b0c");
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, salt, info, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
"d56ecc4c5bf34007208d5b887185865"});
}
// RFC 5869 Appendix A Case 3 (empty salt & info)
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, {}, {}, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454"
"e5f3c738d2d9d201395faa4b61a96c8"});
}
// HKDF guards: empty output, oversized (>4 KiB) without mutating buffer,
// overlapping spans rejected, fault wipes destination.
{
const std::vector<std::byte> ikm(16, std::byte{0x42});
std::vector<std::byte> empty_out;
auto r_empty = hkdf_sha256(ikm, {}, {}, empty_out);
Void::Testing::require(!r_empty.has_value());
Void::Testing::expect_eq(
r_empty.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
std::vector<std::byte> too_large(CryptoLimits::kMaxHkdfOutputBytes + 1U,
std::byte{0x7A});
auto r_large = hkdf_sha256(ikm, {}, {}, too_large);
Void::Testing::require(!r_large.has_value());
Void::Testing::expect_eq(
r_large.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
Void::Testing::expect(
std::all_of(too_large.begin(), too_large.end(),
[](std::byte b) { return b == std::byte{0x7A}; }));
std::array<std::byte, 64> shared{};
shared.fill(std::byte{0x55});
auto r_overlap =
hkdf_sha256(std::span{shared}.subspan(0, 32), {}, {},
std::span{shared}.subspan(16, 32));
Void::Testing::require(!r_overlap.has_value());
Void::Testing::expect_eq(
r_overlap.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
std::array<std::byte, 32> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{
FaultConfig{FaultOperation::hkdf,
CryptoErrorCode::provider_error, 0}};
auto r_fault = hkdf_sha256(ikm, {}, {}, wiped);
Void::Testing::require(!r_fault.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0x00}; }));
}
// Also verify built-in HMAC-SHA-256 and HKDF-SHA-256 produce identical
// outputs without OpenSSL.
{
const ProviderOptions builtin_opts{.prefer_builtin = true};
const std::vector<std::byte> key(20, std::byte{0x0b});
auto mac = hmac_sha256(key, as_bytes("Hi There"), builtin_opts);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
"76c2e32cff7"});
const std::vector<std::byte> ikm(22, std::byte{0x0b});
const auto salt = from_hex("000102030405060708090a0b0c");
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, salt, info, okm, builtin_opts);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
"d56ecc4c5bf34007208d5b887185865"});
}
// constant_time_equal checks
const auto a = from_hex("01020304");
const auto b = from_hex("01020304");
const auto c = from_hex("01020305");
const auto d = from_hex("010203");
Void::Testing::expect(constant_time_equal(a, b));
Void::Testing::expect(!constant_time_equal(a, c));
Void::Testing::expect(!constant_time_equal(a, d));
}