feat(security): add SecureBuffer, VSEC envelopes, authorization, and SecurityAsync Authenticator
This commit is contained in:
1 parent
eb42228604
commit
713d2dc656
20 files changed
+4070
-43
No files matched your search
@@ -0,0 +1,203 @@
|
||||
#include <Void/Security/Authorization.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
validate_predicate(const Predicate& pred, std::size_t depth)
|
||||
{
|
||||
if (depth > SecurityLimits::kMaxPredicateDepth) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::policy_invalid,
|
||||
"Security::PolicySnapshot: predicate nesting exceeds max "
|
||||
"depth 16")};
|
||||
}
|
||||
switch (pred.kind) {
|
||||
case Predicate::Kind::AlwaysTrue:
|
||||
case Predicate::Kind::AlwaysFalse:
|
||||
case Predicate::Kind::HasRole:
|
||||
case Predicate::Kind::SubjectEquals:
|
||||
case Predicate::Kind::ResourceTypeEquals:
|
||||
case Predicate::Kind::ResourceIdEquals:
|
||||
case Predicate::Kind::ResourceAttrEquals:
|
||||
case Predicate::Kind::PrincipalAttrEquals:
|
||||
case Predicate::Kind::ResourceOwnerMatchesSubject:
|
||||
return {};
|
||||
case Predicate::Kind::AllOf:
|
||||
case Predicate::Kind::AnyOf:
|
||||
for (const auto& child : pred.children) {
|
||||
if (auto res = validate_predicate(child, depth + 1U);
|
||||
!res.has_value()) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
case Predicate::Kind::Not:
|
||||
if (pred.children.size() != 1U) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::policy_invalid,
|
||||
"Security::PolicySnapshot: Not predicate requires "
|
||||
"exactly 1 child")};
|
||||
}
|
||||
return validate_predicate(pred.children.front(),
|
||||
depth + 1U);
|
||||
}
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::policy_invalid,
|
||||
"Security::PolicySnapshot: unknown predicate kind")};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool eval_predicate(const Predicate& pred,
|
||||
const Principal& principal,
|
||||
const ResourceAttributes& resource,
|
||||
std::size_t depth)
|
||||
{
|
||||
if (depth > SecurityLimits::kMaxPredicateDepth) {
|
||||
return false;
|
||||
}
|
||||
switch (pred.kind) {
|
||||
case Predicate::Kind::AlwaysTrue:
|
||||
return true;
|
||||
case Predicate::Kind::AlwaysFalse:
|
||||
return false;
|
||||
case Predicate::Kind::HasRole:
|
||||
return std::find(principal.roles.begin(),
|
||||
principal.roles.end(),
|
||||
pred.value) != principal.roles.end();
|
||||
case Predicate::Kind::SubjectEquals:
|
||||
return !principal.subject.empty() &&
|
||||
principal.subject == pred.value;
|
||||
case Predicate::Kind::ResourceTypeEquals:
|
||||
return resource.resource_type == pred.value;
|
||||
case Predicate::Kind::ResourceIdEquals:
|
||||
return resource.resource_id == pred.value;
|
||||
case Predicate::Kind::ResourceAttrEquals:
|
||||
{
|
||||
auto it = resource.attributes.find(pred.key);
|
||||
return it != resource.attributes.end() &&
|
||||
it->second == pred.value;
|
||||
}
|
||||
case Predicate::Kind::PrincipalAttrEquals:
|
||||
{
|
||||
auto it = principal.attributes.find(pred.key);
|
||||
return it != principal.attributes.end() &&
|
||||
it->second == pred.value;
|
||||
}
|
||||
case Predicate::Kind::ResourceOwnerMatchesSubject:
|
||||
{
|
||||
if (principal.subject.empty()) {
|
||||
return false;
|
||||
}
|
||||
const std::string_view attr_key =
|
||||
pred.key.empty() ? std::string_view{"owner"}
|
||||
: std::string_view{pred.key};
|
||||
auto it = resource.attributes.find(attr_key);
|
||||
return it != resource.attributes.end() &&
|
||||
it->second == principal.subject;
|
||||
}
|
||||
case Predicate::Kind::AllOf:
|
||||
if (pred.children.empty()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& child : pred.children) {
|
||||
if (!eval_predicate(child, principal, resource,
|
||||
depth + 1U)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
case Predicate::Kind::AnyOf:
|
||||
for (const auto& child : pred.children) {
|
||||
if (eval_predicate(child, principal, resource,
|
||||
depth + 1U)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
case Predicate::Kind::Not:
|
||||
if (pred.children.size() != 1U) {
|
||||
return false;
|
||||
}
|
||||
return !eval_predicate(pred.children.front(), principal,
|
||||
resource, depth + 1U);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<PolicySnapshot>
|
||||
PolicySnapshot::create(std::uint64_t generation,
|
||||
std::vector<PolicyRule> rules)
|
||||
{
|
||||
if (rules.size() > SecurityLimits::kMaxPolicyRules) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::policy_invalid,
|
||||
"Security::PolicySnapshot: rule count exceeds 4096 cap")};
|
||||
}
|
||||
for (const auto& rule : rules) {
|
||||
if (rule.action.empty()) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::policy_invalid,
|
||||
"Security::PolicySnapshot: rule action must be non-empty")};
|
||||
}
|
||||
if (auto res = validate_predicate(rule.condition, 1U);
|
||||
!res.has_value()) {
|
||||
return std::unexpected{std::move(res.error())};
|
||||
}
|
||||
}
|
||||
return PolicySnapshot{generation, std::move(rules)};
|
||||
}
|
||||
|
||||
Decision PolicySnapshot::authorize(const Principal& principal,
|
||||
std::string_view action,
|
||||
const ResourceAttributes& resource) const
|
||||
{
|
||||
if (action.empty()) {
|
||||
return Decision{.allowed = false,
|
||||
.reason = "empty action denied",
|
||||
.policy_generation = m_generation};
|
||||
}
|
||||
if (principal.roles.size() > SecurityLimits::kMaxRolesPerPrincipal) {
|
||||
return Decision{.allowed = false,
|
||||
.reason = "principal exceeds 64-role cap",
|
||||
.policy_generation = m_generation};
|
||||
}
|
||||
|
||||
std::string allow_rule_id;
|
||||
bool matched_allow = false;
|
||||
|
||||
for (const auto& rule : m_rules) {
|
||||
if (rule.action != "*" && rule.action != action) {
|
||||
continue;
|
||||
}
|
||||
if (!eval_predicate(rule.condition, principal, resource, 1U)) {
|
||||
continue;
|
||||
}
|
||||
if (rule.effect == Effect::Deny) {
|
||||
return Decision{.allowed = false,
|
||||
.matched_rule_id = rule.id,
|
||||
.reason = "explicit deny",
|
||||
.policy_generation = m_generation};
|
||||
}
|
||||
if (!matched_allow) {
|
||||
matched_allow = true;
|
||||
allow_rule_id = rule.id;
|
||||
}
|
||||
}
|
||||
|
||||
if (matched_allow) {
|
||||
return Decision{.allowed = true,
|
||||
.matched_rule_id = std::move(allow_rule_id),
|
||||
.reason = "explicit allow",
|
||||
.policy_generation = m_generation};
|
||||
}
|
||||
|
||||
return Decision{.allowed = false,
|
||||
.reason = "default deny",
|
||||
.policy_generation = m_generation};
|
||||
}
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,433 @@
|
||||
#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
|
||||
@@ -0,0 +1,152 @@
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
|
||||
#include <sodium.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
std::atomic<std::uint64_t> g_total_wiped_bytes{0};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> ensure_sodium_buf()
|
||||
{
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::sodium_init, "Security::SecureBuffer");
|
||||
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::SecureBuffer: libsodium initialization failed")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
SecureBuffer::~SecureBuffer() noexcept { clear(); }
|
||||
|
||||
SecureBuffer::SecureBuffer(SecureBuffer&& other) noexcept
|
||||
: m_data(std::exchange(other.m_data, nullptr)),
|
||||
m_size(std::exchange(other.m_size, 0)),
|
||||
m_locked(std::exchange(other.m_locked, false))
|
||||
{
|
||||
}
|
||||
|
||||
SecureBuffer& SecureBuffer::operator=(SecureBuffer&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
clear();
|
||||
m_data = std::exchange(other.m_data, nullptr);
|
||||
m_size = std::exchange(other.m_size, 0);
|
||||
m_locked = std::exchange(other.m_locked, false);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void SecureBuffer::clear() noexcept
|
||||
{
|
||||
if (m_data != nullptr) {
|
||||
if (m_size > 0) {
|
||||
sodium_memzero(m_data, m_size);
|
||||
g_total_wiped_bytes.fetch_add(m_size,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
if (m_locked) {
|
||||
sodium_free(m_data);
|
||||
} else {
|
||||
delete[] m_data;
|
||||
}
|
||||
m_data = nullptr;
|
||||
m_size = 0;
|
||||
m_locked = false;
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t SecureBuffer::total_wiped_bytes() noexcept
|
||||
{
|
||||
return g_total_wiped_bytes.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
Void::Result::Result<SecureBuffer>
|
||||
SecureBuffer::allocate(std::size_t size, LockPolicy policy)
|
||||
{
|
||||
if (size > SecurityLimits::kMaxSecretPlaintextBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::SecureBuffer: allocation exceeds 16 MiB cap")};
|
||||
}
|
||||
if (auto init = ensure_sodium_buf(); !init.has_value()) {
|
||||
return std::unexpected{std::move(init.error())};
|
||||
}
|
||||
if (size == 0) {
|
||||
return SecureBuffer{};
|
||||
}
|
||||
|
||||
if (policy == LockPolicy::LockedRequired ||
|
||||
policy == LockPolicy::LockedOptional) {
|
||||
auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::locked_alloc,
|
||||
"Security::SecureBuffer::allocate");
|
||||
void* raw = fault.has_value() ? nullptr : sodium_malloc(size);
|
||||
if (raw != nullptr) {
|
||||
sodium_memzero(raw, size);
|
||||
SecureBuffer buf;
|
||||
buf.m_data = static_cast<unsigned char*>(raw);
|
||||
buf.m_size = size;
|
||||
buf.m_locked = true;
|
||||
return buf;
|
||||
}
|
||||
if (policy == LockPolicy::LockedRequired) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::locked_memory_unavailable,
|
||||
"Security::SecureBuffer: required locked allocation "
|
||||
"failed")};
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char* raw = new (std::nothrow) unsigned char[size];
|
||||
if (raw == nullptr) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::backend_error,
|
||||
"Security::SecureBuffer: allocation failed")};
|
||||
}
|
||||
sodium_memzero(raw, size);
|
||||
SecureBuffer buf;
|
||||
buf.m_data = raw;
|
||||
buf.m_size = size;
|
||||
buf.m_locked = false;
|
||||
return buf;
|
||||
}
|
||||
|
||||
Void::Result::Result<SecureBuffer>
|
||||
SecureBuffer::from_bytes(std::span<const unsigned char> data,
|
||||
LockPolicy policy)
|
||||
{
|
||||
auto buf = allocate(data.size(), policy);
|
||||
if (!buf.has_value()) {
|
||||
return std::unexpected{std::move(buf.error())};
|
||||
}
|
||||
if (!data.empty()) {
|
||||
std::memcpy(buf->m_data, data.data(), data.size());
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
Void::Result::Result<SecureBuffer>
|
||||
SecureBuffer::from_string(std::string_view text, LockPolicy policy)
|
||||
{
|
||||
return from_bytes(
|
||||
std::span<const unsigned char>{
|
||||
reinterpret_cast<const unsigned char*>(text.data()),
|
||||
text.size()},
|
||||
policy);
|
||||
}
|
||||
|
||||
} // namespace Void::Security
|
||||
+338
-40
@@ -3,7 +3,9 @@
|
||||
#include <sodium.h>
|
||||
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
@@ -12,6 +14,9 @@ namespace Void::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
thread_local FaultConfig g_fault_config{};
|
||||
thread_local std::size_t g_fault_hits{0};
|
||||
|
||||
struct PasswordLimits {
|
||||
unsigned long long operations;
|
||||
std::size_t memory;
|
||||
@@ -19,10 +24,16 @@ namespace Void::Security
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> ensure_sodium()
|
||||
{
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::sodium_init, "Security::ensure_sodium");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
static const bool initialized = sodium_init() >= 0;
|
||||
if (!initialized) {
|
||||
return Void::Result::fail(
|
||||
"Security: libsodium initialization failed");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::backend_error,
|
||||
"Security: libsodium initialization failed")};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
@@ -54,21 +65,106 @@ namespace Void::Security
|
||||
token.size(), nullptr, 0);
|
||||
return digest;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t>
|
||||
parse_u64_strict(std::string_view text) noexcept
|
||||
{
|
||||
if (text.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
for (const char ch : text) {
|
||||
if (ch < '0' || ch > '9') {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
std::uint64_t value = 0;
|
||||
const auto res = std::from_chars(
|
||||
text.data(), text.data() + text.size(), value);
|
||||
if (res.ec != std::errc{} ||
|
||||
res.ptr != text.data() + text.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
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_security_error(
|
||||
g_fault_config.code,
|
||||
std::format("{}: injected security backend fault", operation));
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
void wipe_bytes(std::span<unsigned char> buffer) noexcept
|
||||
{
|
||||
if (!buffer.empty()) {
|
||||
sodium_memzero(buffer.data(), buffer.size());
|
||||
}
|
||||
}
|
||||
|
||||
bool constant_time_equal(std::span<const unsigned char> lhs,
|
||||
std::span<const unsigned char> rhs) noexcept
|
||||
{
|
||||
if (lhs.size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
if (lhs.empty()) {
|
||||
return true;
|
||||
}
|
||||
return sodium_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string> random_token(std::size_t entropy_bytes)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (entropy_bytes == 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy must be greater than zero");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::invalid_argument,
|
||||
"Security::random_token: entropy must be greater than zero")};
|
||||
}
|
||||
if (entropy_bytes >
|
||||
(std::numeric_limits<std::size_t>::max() - 2) / 4 * 3) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy size is too large");
|
||||
// 384 bytes base64url encodes to 512 chars (SecurityLimits::kMaxTokenBytes).
|
||||
constexpr std::size_t kMaxEntropyBytes =
|
||||
(SecurityLimits::kMaxTokenBytes / 4U) * 3U;
|
||||
if (entropy_bytes > kMaxEntropyBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::random_token: entropy exceeds 512-byte token cap")};
|
||||
}
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::random_bytes, "Security::random_token");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
std::vector<unsigned char> random(entropy_bytes);
|
||||
@@ -82,8 +178,9 @@ namespace Void::Security
|
||||
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
|
||||
sodium_memzero(random.data(), random.size());
|
||||
if (result == nullptr) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: base64 encoding failed");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::backend_error,
|
||||
"Security::random_token: base64 encoding failed")};
|
||||
}
|
||||
encoded.resize(std::strlen(encoded.c_str()));
|
||||
return encoded;
|
||||
@@ -92,7 +189,12 @@ namespace Void::Security
|
||||
Void::Result::Result<std::string> hash_token(std::string_view token)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (token.size() > SecurityLimits::kMaxTokenBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::hash_token: token exceeds 512-byte cap")};
|
||||
}
|
||||
|
||||
const auto digest = token_digest(token);
|
||||
@@ -106,7 +208,12 @@ namespace Void::Security
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (token.size() > SecurityLimits::kMaxTokenBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::verify_token: token exceeds 512-byte cap")};
|
||||
}
|
||||
|
||||
constexpr auto encoded_length = crypto_generichash_BYTES * 2;
|
||||
@@ -132,17 +239,24 @@ namespace Void::Security
|
||||
hash_password(std::string_view password, PasswordHashStrength strength)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: password is too long");
|
||||
if (password.size() > SecurityLimits::kMaxPasswordBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::hash_password: password exceeds 1 KiB cap")};
|
||||
}
|
||||
|
||||
const auto limits = password_limits(strength);
|
||||
if (!limits) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: invalid strength");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::invalid_argument,
|
||||
"Security::hash_password: invalid strength")};
|
||||
}
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::password_hash, "Security::hash_password");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
std::array<char, crypto_pwhash_STRBYTES> encoded{};
|
||||
@@ -151,23 +265,183 @@ namespace Void::Security
|
||||
static_cast<unsigned long long>(password.size()),
|
||||
limits->operations, limits->memory,
|
||||
crypto_pwhash_ALG_ARGON2ID13) != 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: Argon2id hashing failed");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::backend_error,
|
||||
"Security::hash_password: Argon2id hashing failed")};
|
||||
}
|
||||
return std::string{encoded.data()};
|
||||
}
|
||||
|
||||
Void::Result::Result<Argon2idCost>
|
||||
parse_argon2id_cost(std::string_view encoded_hash)
|
||||
{
|
||||
if (encoded_hash.empty() ||
|
||||
encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes ||
|
||||
encoded_hash.find('\0') != std::string_view::npos) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: invalid hash length or NUL")};
|
||||
}
|
||||
|
||||
// Format: $argon2id$v=19$m=<kib>,t=<ops>,p=<par>$<salt>$<digest>
|
||||
constexpr std::string_view kPrefix = "$argon2id$";
|
||||
if (!encoded_hash.starts_with(kPrefix)) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: unsupported algorithm prefix")};
|
||||
}
|
||||
|
||||
std::string_view rest = encoded_hash.substr(kPrefix.size());
|
||||
const auto next_field = [&](std::string_view& field) -> bool {
|
||||
const auto sep = rest.find('$');
|
||||
if (sep == std::string_view::npos) {
|
||||
return false;
|
||||
}
|
||||
field = rest.substr(0, sep);
|
||||
rest = rest.substr(sep + 1);
|
||||
return true;
|
||||
};
|
||||
|
||||
std::string_view ver_field;
|
||||
std::string_view params_field;
|
||||
std::string_view salt_field;
|
||||
if (!next_field(ver_field) || !next_field(params_field) ||
|
||||
!next_field(salt_field) || salt_field.empty() || rest.empty() ||
|
||||
rest.find('$') != std::string_view::npos) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: malformed PHC structure")};
|
||||
}
|
||||
|
||||
if (!ver_field.starts_with("v=")) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: missing version field")};
|
||||
}
|
||||
const auto ver = parse_u64_strict(ver_field.substr(2));
|
||||
if (!ver.has_value() || *ver != 19ULL) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: unsupported Argon2 version")};
|
||||
}
|
||||
|
||||
const auto c1 = params_field.find(',');
|
||||
if (c1 == std::string_view::npos) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: missing parameter separators")};
|
||||
}
|
||||
const auto c2 = params_field.find(',', c1 + 1);
|
||||
if (c2 == std::string_view::npos ||
|
||||
params_field.find(',', c2 + 1) != std::string_view::npos) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: invalid parameter list")};
|
||||
}
|
||||
|
||||
const std::string_view m_part = params_field.substr(0, c1);
|
||||
const std::string_view t_part = params_field.substr(c1 + 1, c2 - c1 - 1);
|
||||
const std::string_view p_part = params_field.substr(c2 + 1);
|
||||
if (!m_part.starts_with("m=") || !t_part.starts_with("t=") ||
|
||||
!p_part.starts_with("p=")) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: expected m=,t=,p= fields")};
|
||||
}
|
||||
|
||||
const auto m_val = parse_u64_strict(m_part.substr(2));
|
||||
const auto t_val = parse_u64_strict(t_part.substr(2));
|
||||
const auto p_val = parse_u64_strict(p_part.substr(2));
|
||||
if (!m_val.has_value() || !t_val.has_value() || !p_val.has_value() ||
|
||||
*m_val == 0 || *t_val == 0 || *p_val == 0 ||
|
||||
*p_val > std::numeric_limits<std::uint32_t>::max()) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::malformed_hash,
|
||||
"Security::parse_argon2id_cost: invalid m/t/p values")};
|
||||
}
|
||||
|
||||
Argon2idCost cost{
|
||||
.version = static_cast<std::uint32_t>(*ver),
|
||||
.memory_kib = *m_val,
|
||||
.iterations = *t_val,
|
||||
.parallelism = static_cast<std::uint32_t>(*p_val),
|
||||
};
|
||||
if (!cost.memory_bytes().has_value()) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::cost_budget_exceeded,
|
||||
"Security::parse_argon2id_cost: memory cost overflows")};
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
Void::Result::Result<bool>
|
||||
verify_password_budgeted(std::string_view password,
|
||||
std::string_view encoded_hash,
|
||||
const PasswordVerifyBudget& budget)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (password.size() > SecurityLimits::kMaxPasswordBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::verify_password_budgeted: password exceeds 1 KiB "
|
||||
"cap")};
|
||||
}
|
||||
if (encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::verify_password_budgeted: encoded hash exceeds 1 "
|
||||
"KiB cap")};
|
||||
}
|
||||
|
||||
auto cost = parse_argon2id_cost(encoded_hash);
|
||||
if (!cost.has_value()) {
|
||||
return std::unexpected{std::move(cost.error())};
|
||||
}
|
||||
const auto mem_bytes = cost->memory_bytes();
|
||||
if (!mem_bytes.has_value() || *mem_bytes > budget.max_memory_bytes ||
|
||||
cost->iterations > budget.max_iterations ||
|
||||
cost->parallelism > budget.max_parallelism) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::cost_budget_exceeded,
|
||||
"Security::verify_password_budgeted: encoded Argon2id cost "
|
||||
"exceeds approved verification budget")};
|
||||
}
|
||||
|
||||
const std::string terminated_hash{encoded_hash};
|
||||
return crypto_pwhash_str_verify(
|
||||
terminated_hash.c_str(), password.data(),
|
||||
static_cast<unsigned long long>(password.size())) == 0;
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verify_password(std::string_view password,
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX ||
|
||||
if (password.size() > SecurityLimits::kMaxPasswordBytes ||
|
||||
encoded_hash.empty() ||
|
||||
encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes ||
|
||||
encoded_hash.find('\0') != std::string_view::npos) {
|
||||
return false;
|
||||
}
|
||||
auto cost = parse_argon2id_cost(encoded_hash);
|
||||
if (!cost.has_value()) {
|
||||
return false;
|
||||
}
|
||||
// Prevent DoS from malicious encoded costs even through the legacy
|
||||
// helper while allowing all built-in libsodium presets up to Sensitive.
|
||||
const auto mem_bytes = cost->memory_bytes();
|
||||
if (!mem_bytes.has_value() ||
|
||||
*mem_bytes > crypto_pwhash_MEMLIMIT_SENSITIVE ||
|
||||
cost->iterations > 32ULL || cost->parallelism > 8U) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::cost_budget_exceeded,
|
||||
"Security::verify_password: encoded Argon2id cost exceeds "
|
||||
"safety ceiling")};
|
||||
}
|
||||
|
||||
const std::string terminated_hash{encoded_hash};
|
||||
return crypto_pwhash_str_verify(
|
||||
@@ -178,7 +452,12 @@ namespace Void::Security
|
||||
Void::Result::Result<SecretKey> random_secret_key()
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::random_bytes, "Security::random_secret_key");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
static_assert(secret_key_bytes == crypto_secretbox_KEYBYTES);
|
||||
@@ -192,15 +471,19 @@ namespace Void::Security
|
||||
const SecretKey& key)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES);
|
||||
static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES);
|
||||
if (plaintext.size() > std::numeric_limits<std::size_t>::max() -
|
||||
secret_nonce_bytes -
|
||||
secret_authentication_bytes) {
|
||||
return Void::Result::fail(
|
||||
"Security::seal_secret: plaintext is too large");
|
||||
if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::seal_secret: plaintext exceeds 16 MiB cap")};
|
||||
}
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::secret_seal, "Security::seal_secret");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
std::vector<unsigned char> envelope(secret_nonce_bytes +
|
||||
@@ -213,8 +496,9 @@ namespace Void::Security
|
||||
ciphertext, plaintext.data(),
|
||||
static_cast<unsigned long long>(plaintext.size()), nonce,
|
||||
key.data()) != 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::seal_secret: encryption failed");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::backend_error,
|
||||
"Security::seal_secret: encryption failed")};
|
||||
}
|
||||
return envelope;
|
||||
}
|
||||
@@ -224,25 +508,39 @@ namespace Void::Security
|
||||
const SecretKey& key)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
return std::unexpected{initialized.error()};
|
||||
}
|
||||
if (envelope.size() <
|
||||
secret_nonce_bytes + secret_authentication_bytes) {
|
||||
return Void::Result::fail(
|
||||
"Security::open_secret: envelope is truncated");
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::authentication_failed,
|
||||
"Security::open_secret: envelope is truncated")};
|
||||
}
|
||||
const auto ciphertext_size = envelope.size() - secret_nonce_bytes;
|
||||
const auto plaintext_size =
|
||||
ciphertext_size - secret_authentication_bytes;
|
||||
if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) {
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::input_too_large,
|
||||
"Security::open_secret: envelope exceeds 16 MiB cap")};
|
||||
}
|
||||
if (auto fault = Detail::maybe_inject_fault(
|
||||
FaultOperation::secret_open, "Security::open_secret");
|
||||
fault.has_value()) {
|
||||
return std::unexpected{std::move(*fault)};
|
||||
}
|
||||
|
||||
const auto* nonce = envelope.data();
|
||||
const auto* ciphertext = nonce + secret_nonce_bytes;
|
||||
const auto ciphertext_size = envelope.size() - secret_nonce_bytes;
|
||||
std::vector<unsigned char> plaintext(ciphertext_size -
|
||||
secret_authentication_bytes);
|
||||
std::vector<unsigned char> plaintext(plaintext_size);
|
||||
if (crypto_secretbox_open_easy(
|
||||
plaintext.data(), ciphertext,
|
||||
static_cast<unsigned long long>(ciphertext_size), nonce,
|
||||
key.data()) != 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::open_secret: authentication failed");
|
||||
wipe_bytes(plaintext);
|
||||
return std::unexpected{make_security_error(
|
||||
SecurityErrorCode::authentication_failed,
|
||||
"Security::open_secret: authentication failed")};
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
void_add_module(Security
|
||||
INTERNAL_DEPS Functional
|
||||
INTERNAL_DEPS Functional Time
|
||||
EXTERNAL_DEPS Sodium::Sodium
|
||||
EXCLUDE_HEADERS
|
||||
Void/Security/Authenticator.hpp
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
||||
void_add_module(SecurityAsync
|
||||
INTERNAL_DEPS Security Async Time Resilience Functional
|
||||
EXTERNAL_DEPS Threads::Threads
|
||||
EXTRA_HEADERS
|
||||
Void/Security/Authenticator.hpp
|
||||
)
|
||||
Reference in new issue
Block a user