434 lines
14 KiB
C++
434 lines
14 KiB
C++
#include <Void/Security/Envelope.hpp>
|
|
|
|
#include <sodium.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cstring>
|
|
#include <vector>
|
|
|
|
namespace Void::Security
|
|
{
|
|
namespace
|
|
{
|
|
constexpr std::array<unsigned char, 4> kMagic{'V', 'S', 'E', 'C'};
|
|
constexpr std::size_t kFixedPrefixBytes = 4 + 1 + 1 + 2 + 4; // 12
|
|
|
|
[[nodiscard]] Void::Result::Result<void> ensure_sodium_env()
|
|
{
|
|
if (auto fault = Detail::maybe_inject_fault(
|
|
FaultOperation::sodium_init, "Security::Envelope");
|
|
fault.has_value()) {
|
|
return std::unexpected{std::move(*fault)};
|
|
}
|
|
static const bool ok = sodium_init() >= 0;
|
|
if (!ok) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::backend_error,
|
|
"Security::Envelope: libsodium initialization failed")};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
void append_u16_be(std::vector<unsigned char>& out, std::uint16_t v)
|
|
{
|
|
out.push_back(static_cast<unsigned char>((v >> 8U) & 0xFFU));
|
|
out.push_back(static_cast<unsigned char>(v & 0xFFU));
|
|
}
|
|
|
|
void append_u32_be(std::vector<unsigned char>& out, std::uint32_t v)
|
|
{
|
|
out.push_back(static_cast<unsigned char>((v >> 24U) & 0xFFU));
|
|
out.push_back(static_cast<unsigned char>((v >> 16U) & 0xFFU));
|
|
out.push_back(static_cast<unsigned char>((v >> 8U) & 0xFFU));
|
|
out.push_back(static_cast<unsigned char>(v & 0xFFU));
|
|
}
|
|
|
|
void append_u64_be(std::vector<unsigned char>& out, std::uint64_t v)
|
|
{
|
|
for (int shift = 56; shift >= 0; shift -= 8) {
|
|
out.push_back(static_cast<unsigned char>((v >> shift) & 0xFFU));
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::uint16_t read_u16_be(const unsigned char* p) noexcept
|
|
{
|
|
return static_cast<std::uint16_t>(
|
|
(static_cast<std::uint16_t>(p[0]) << 8U) |
|
|
static_cast<std::uint16_t>(p[1]));
|
|
}
|
|
|
|
[[nodiscard]] std::uint32_t read_u32_be(const unsigned char* p) noexcept
|
|
{
|
|
return (static_cast<std::uint32_t>(p[0]) << 24U) |
|
|
(static_cast<std::uint32_t>(p[1]) << 16U) |
|
|
(static_cast<std::uint32_t>(p[2]) << 8U) |
|
|
static_cast<std::uint32_t>(p[3]);
|
|
}
|
|
|
|
[[nodiscard]] bool valid_key_id(std::string_view key_id) noexcept
|
|
{
|
|
if (key_id.empty() || key_id.size() > SecurityLimits::kMaxKeyIdBytes) {
|
|
return false;
|
|
}
|
|
for (const unsigned char ch : key_id) {
|
|
if (ch < 0x20U || ch == 0x7FU) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] std::vector<unsigned char>
|
|
build_aead_aad(std::span<const unsigned char> header_and_nonce,
|
|
std::span<const unsigned char> caller_aad)
|
|
{
|
|
std::vector<unsigned char> combined;
|
|
combined.reserve(header_and_nonce.size() + 8 + caller_aad.size());
|
|
combined.insert(combined.end(), header_and_nonce.begin(),
|
|
header_and_nonce.end());
|
|
append_u64_be(combined, static_cast<std::uint64_t>(caller_aad.size()));
|
|
combined.insert(combined.end(), caller_aad.begin(),
|
|
caller_aad.end());
|
|
return combined;
|
|
}
|
|
} // namespace
|
|
|
|
Void::Result::Result<EnvelopeHeader>
|
|
inspect_envelope(std::span<const unsigned char> envelope)
|
|
{
|
|
if (envelope.size() <
|
|
kFixedPrefixBytes + kEnvelopeNonceBytes + kEnvelopeTagBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::unsupported_version,
|
|
"Security::inspect_envelope: truncated or non-VSEC envelope")};
|
|
}
|
|
if (!std::equal(kMagic.begin(), kMagic.end(), envelope.begin())) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::unsupported_version,
|
|
"Security::inspect_envelope: invalid magic (legacy fallback "
|
|
"disabled)")};
|
|
}
|
|
|
|
const std::uint8_t version = envelope[4];
|
|
const std::uint8_t algorithm = envelope[5];
|
|
if (version != kEnvelopeVersionV1) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::unsupported_version,
|
|
"Security::inspect_envelope: unsupported envelope version")};
|
|
}
|
|
if (algorithm != kEnvelopeAlgXChaCha20Poly1305Ietf) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::unsupported_version,
|
|
"Security::inspect_envelope: unsupported envelope algorithm")};
|
|
}
|
|
|
|
const std::uint16_t key_id_len = read_u16_be(envelope.data() + 6);
|
|
const std::uint32_t plaintext_size = read_u32_be(envelope.data() + 8);
|
|
if (key_id_len == 0 || key_id_len > SecurityLimits::kMaxKeyIdBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::authentication_failed,
|
|
"Security::inspect_envelope: invalid key_id length")};
|
|
}
|
|
if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::input_too_large,
|
|
"Security::inspect_envelope: declared plaintext exceeds 16 MiB "
|
|
"cap")};
|
|
}
|
|
|
|
const std::size_t expected_size =
|
|
kFixedPrefixBytes + static_cast<std::size_t>(key_id_len) +
|
|
kEnvelopeNonceBytes + static_cast<std::size_t>(plaintext_size) +
|
|
kEnvelopeTagBytes;
|
|
if (envelope.size() != expected_size) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::authentication_failed,
|
|
"Security::inspect_envelope: envelope length mismatch")};
|
|
}
|
|
|
|
std::string key_id(
|
|
reinterpret_cast<const char*>(envelope.data() + kFixedPrefixBytes),
|
|
key_id_len);
|
|
if (!valid_key_id(key_id)) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::authentication_failed,
|
|
"Security::inspect_envelope: invalid characters in key_id")};
|
|
}
|
|
|
|
return EnvelopeHeader{
|
|
.version = version,
|
|
.algorithm = algorithm,
|
|
.key_id = std::move(key_id),
|
|
.plaintext_size = plaintext_size,
|
|
};
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
SecretKeyRing::add_key(std::string key_id,
|
|
std::span<const unsigned char> raw_key,
|
|
bool make_active, LockPolicy lock_policy)
|
|
{
|
|
if (!valid_key_id(key_id)) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::invalid_argument,
|
|
"Security::SecretKeyRing::add_key: invalid key_id")};
|
|
}
|
|
if (raw_key.size() != kEnvelopeKeyBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::invalid_argument,
|
|
"Security::SecretKeyRing::add_key: key must be 32 bytes")};
|
|
}
|
|
if (m_keys.contains(key_id)) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::conflict,
|
|
"Security::SecretKeyRing::add_key: duplicate key_id")};
|
|
}
|
|
auto stored = SecureBuffer::from_bytes(raw_key, lock_policy);
|
|
if (!stored.has_value()) {
|
|
return std::unexpected{std::move(stored.error())};
|
|
}
|
|
const std::string id_copy = key_id;
|
|
m_keys.emplace(std::move(key_id), std::move(*stored));
|
|
if (make_active || m_active_key_id.empty()) {
|
|
m_active_key_id = id_copy;
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
SecretKeyRing::generate_and_add_key(std::string key_id,
|
|
bool make_active,
|
|
LockPolicy lock_policy)
|
|
{
|
|
if (auto init = ensure_sodium_env(); !init.has_value()) {
|
|
return std::unexpected{std::move(init.error())};
|
|
}
|
|
if (auto fault = Detail::maybe_inject_fault(
|
|
FaultOperation::random_bytes,
|
|
"Security::SecretKeyRing::generate_and_add_key");
|
|
fault.has_value()) {
|
|
return std::unexpected{std::move(*fault)};
|
|
}
|
|
auto key_buf = SecureBuffer::allocate(kEnvelopeKeyBytes, lock_policy);
|
|
if (!key_buf.has_value()) {
|
|
return std::unexpected{std::move(key_buf.error())};
|
|
}
|
|
static_assert(kEnvelopeKeyBytes ==
|
|
crypto_aead_xchacha20poly1305_ietf_KEYBYTES);
|
|
crypto_aead_xchacha20poly1305_ietf_keygen(key_buf->writable().data());
|
|
return add_key(std::move(key_id), key_buf->view(), make_active,
|
|
lock_policy);
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
SecretKeyRing::set_active_key(std::string_view key_id)
|
|
{
|
|
auto it = m_keys.find(key_id);
|
|
if (it == m_keys.end()) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_not_found,
|
|
"Security::SecretKeyRing::set_active_key: unknown key_id")};
|
|
}
|
|
m_active_key_id = it->first;
|
|
return {};
|
|
}
|
|
|
|
Void::Result::Result<void> SecretKeyRing::retire_key(
|
|
std::string_view key_id,
|
|
std::span<const std::string> remaining_ciphertext_key_ids)
|
|
{
|
|
auto it = m_keys.find(key_id);
|
|
if (it == m_keys.end()) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_not_found,
|
|
"Security::SecretKeyRing::retire_key: unknown key_id")};
|
|
}
|
|
if (it->first == m_active_key_id) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_in_use,
|
|
"Security::SecretKeyRing::retire_key: cannot retire active "
|
|
"key")};
|
|
}
|
|
for (const auto& referenced : remaining_ciphertext_key_ids) {
|
|
if (referenced == key_id) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_in_use,
|
|
"Security::SecretKeyRing::retire_key: ciphertext inventory "
|
|
"still references key_id")};
|
|
}
|
|
}
|
|
m_keys.erase(it);
|
|
return {};
|
|
}
|
|
|
|
std::optional<std::string> SecretKeyRing::active_key_id() const
|
|
{
|
|
if (m_active_key_id.empty()) {
|
|
return std::nullopt;
|
|
}
|
|
return m_active_key_id;
|
|
}
|
|
|
|
bool SecretKeyRing::has_key(std::string_view key_id) const
|
|
{
|
|
return m_keys.find(key_id) != m_keys.end();
|
|
}
|
|
|
|
std::vector<std::string> SecretKeyRing::key_ids() const
|
|
{
|
|
std::vector<std::string> ids;
|
|
ids.reserve(m_keys.size());
|
|
for (const auto& [id, _] : m_keys) {
|
|
ids.push_back(id);
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
Void::Result::Result<std::vector<unsigned char>>
|
|
SecretKeyRing::seal(std::span<const unsigned char> plaintext,
|
|
std::span<const unsigned char> aad) const
|
|
{
|
|
if (auto init = ensure_sodium_env(); !init.has_value()) {
|
|
return std::unexpected{std::move(init.error())};
|
|
}
|
|
if (m_active_key_id.empty()) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_not_found,
|
|
"Security::SecretKeyRing::seal: no active key configured")};
|
|
}
|
|
if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::input_too_large,
|
|
"Security::SecretKeyRing::seal: plaintext exceeds 16 MiB cap")};
|
|
}
|
|
if (aad.size() > SecurityLimits::kMaxAadBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::input_too_large,
|
|
"Security::SecretKeyRing::seal: AAD exceeds 64 KiB cap")};
|
|
}
|
|
if (auto fault = Detail::maybe_inject_fault(
|
|
FaultOperation::secret_seal, "Security::SecretKeyRing::seal");
|
|
fault.has_value()) {
|
|
return std::unexpected{std::move(*fault)};
|
|
}
|
|
|
|
auto it = m_keys.find(m_active_key_id);
|
|
if (it == m_keys.end()) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_not_found,
|
|
"Security::SecretKeyRing::seal: active key missing")};
|
|
}
|
|
|
|
static_assert(kEnvelopeNonceBytes ==
|
|
crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
|
|
static_assert(kEnvelopeTagBytes ==
|
|
crypto_aead_xchacha20poly1305_ietf_ABYTES);
|
|
|
|
const std::size_t header_size =
|
|
kFixedPrefixBytes + m_active_key_id.size() + kEnvelopeNonceBytes;
|
|
std::vector<unsigned char> out;
|
|
out.reserve(header_size + plaintext.size() + kEnvelopeTagBytes);
|
|
|
|
out.insert(out.end(), kMagic.begin(), kMagic.end());
|
|
out.push_back(kEnvelopeVersionV1);
|
|
out.push_back(kEnvelopeAlgXChaCha20Poly1305Ietf);
|
|
append_u16_be(out, static_cast<std::uint16_t>(m_active_key_id.size()));
|
|
append_u32_be(out, static_cast<std::uint32_t>(plaintext.size()));
|
|
for (const char ch : m_active_key_id) {
|
|
out.push_back(static_cast<unsigned char>(ch));
|
|
}
|
|
|
|
const std::size_t nonce_offset = out.size();
|
|
out.resize(nonce_offset + kEnvelopeNonceBytes);
|
|
randombytes_buf(out.data() + nonce_offset, kEnvelopeNonceBytes);
|
|
|
|
const auto combined_aad =
|
|
build_aead_aad(std::span<const unsigned char>{out}, aad);
|
|
|
|
const std::size_t ct_offset = out.size();
|
|
out.resize(ct_offset + plaintext.size() + kEnvelopeTagBytes);
|
|
unsigned long long ct_len = 0;
|
|
|
|
static constexpr unsigned char kEmptyByte = 0;
|
|
const unsigned char* pt_ptr =
|
|
plaintext.empty() ? &kEmptyByte : plaintext.data();
|
|
if (crypto_aead_xchacha20poly1305_ietf_encrypt(
|
|
out.data() + ct_offset, &ct_len, pt_ptr,
|
|
static_cast<unsigned long long>(plaintext.size()),
|
|
combined_aad.data(),
|
|
static_cast<unsigned long long>(combined_aad.size()), nullptr,
|
|
out.data() + nonce_offset, it->second.view().data()) != 0 ||
|
|
ct_len != plaintext.size() + kEnvelopeTagBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::backend_error,
|
|
"Security::SecretKeyRing::seal: AEAD encryption failed")};
|
|
}
|
|
return out;
|
|
}
|
|
|
|
Void::Result::Result<SecureBuffer>
|
|
SecretKeyRing::open(std::span<const unsigned char> envelope,
|
|
std::span<const unsigned char> aad,
|
|
LockPolicy out_policy) const
|
|
{
|
|
if (auto init = ensure_sodium_env(); !init.has_value()) {
|
|
return std::unexpected{std::move(init.error())};
|
|
}
|
|
if (aad.size() > SecurityLimits::kMaxAadBytes) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::input_too_large,
|
|
"Security::SecretKeyRing::open: AAD exceeds 64 KiB cap")};
|
|
}
|
|
auto header = inspect_envelope(envelope);
|
|
if (!header.has_value()) {
|
|
return std::unexpected{std::move(header.error())};
|
|
}
|
|
auto it = m_keys.find(header->key_id);
|
|
if (it == m_keys.end()) {
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::key_not_found,
|
|
"Security::SecretKeyRing::open: unknown key_id in envelope")};
|
|
}
|
|
if (auto fault = Detail::maybe_inject_fault(
|
|
FaultOperation::secret_open, "Security::SecretKeyRing::open");
|
|
fault.has_value()) {
|
|
return std::unexpected{std::move(*fault)};
|
|
}
|
|
|
|
const std::size_t nonce_offset =
|
|
kFixedPrefixBytes + header->key_id.size();
|
|
const std::size_t header_and_nonce_len =
|
|
nonce_offset + kEnvelopeNonceBytes;
|
|
const auto combined_aad =
|
|
build_aead_aad(envelope.subspan(0, header_and_nonce_len), aad);
|
|
|
|
auto plaintext =
|
|
SecureBuffer::allocate(header->plaintext_size, out_policy);
|
|
if (!plaintext.has_value()) {
|
|
return std::unexpected{std::move(plaintext.error())};
|
|
}
|
|
|
|
unsigned char dummy_out = 0;
|
|
unsigned char* out_ptr =
|
|
plaintext->empty() ? &dummy_out : plaintext->writable().data();
|
|
unsigned long long pt_len = 0;
|
|
const std::size_t ct_size = envelope.size() - header_and_nonce_len;
|
|
if (crypto_aead_xchacha20poly1305_ietf_decrypt(
|
|
out_ptr, &pt_len, nullptr,
|
|
envelope.data() + header_and_nonce_len,
|
|
static_cast<unsigned long long>(ct_size), combined_aad.data(),
|
|
static_cast<unsigned long long>(combined_aad.size()),
|
|
envelope.data() + nonce_offset,
|
|
it->second.view().data()) != 0 ||
|
|
pt_len != header->plaintext_size) {
|
|
plaintext->clear();
|
|
return std::unexpected{make_security_error(
|
|
SecurityErrorCode::authentication_failed,
|
|
"Security::SecretKeyRing::open: AEAD authentication failed")};
|
|
}
|
|
return plaintext;
|
|
}
|
|
|
|
} // namespace Void::Security
|