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,353 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Resilience/KeyedRateLimiter.hpp>
|
||||
#include <Void/Security/Authorization.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Security.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::SecurityAsync
|
||||
{
|
||||
struct AccountRecord {
|
||||
std::string subject{};
|
||||
std::string normalized_username{};
|
||||
std::string password_hash{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t credential_version{1};
|
||||
std::uint64_t revocation_generation{1};
|
||||
std::uint64_t policy_generation{1};
|
||||
bool enabled{true};
|
||||
};
|
||||
|
||||
struct SessionRecord {
|
||||
std::string session_id{};
|
||||
std::string token_digest{};
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t credential_version{1};
|
||||
std::uint64_t revocation_generation{1};
|
||||
std::uint64_t policy_generation{1};
|
||||
Void::Time::CivilClock::time_point created_at{};
|
||||
Void::Time::CivilClock::time_point expires_at{};
|
||||
bool revoked{false};
|
||||
};
|
||||
|
||||
class AccountSessionPort
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AccountSessionPort() = default;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<AccountRecord>>
|
||||
find_account_by_username(
|
||||
std::string_view normalized_username) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<AccountRecord>>
|
||||
find_account_by_subject(std::string_view subject) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
update_password_hash_if_version(
|
||||
std::string_view subject,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::string new_password_hash) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
create_session_if_version(
|
||||
const SessionRecord& session,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::size_t max_total_sessions,
|
||||
std::size_t max_per_subject,
|
||||
Void::Time::CivilClock::time_point now) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<
|
||||
std::optional<SessionRecord>>
|
||||
find_session_by_token_digest(std::string_view token_digest) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
revoke_session(std::string_view session_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<std::size_t>
|
||||
cleanup_expired_sessions(
|
||||
Void::Time::CivilClock::time_point now,
|
||||
std::size_t batch_limit) = 0;
|
||||
};
|
||||
|
||||
class InMemoryAccountSessionStore final : public AccountSessionPort
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
upsert_account(AccountRecord account);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
bump_credential_version(std::string_view subject,
|
||||
std::string new_password_hash = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
set_account_enabled(std::string_view subject, bool enabled);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
bump_revocation_generation(std::string_view subject);
|
||||
|
||||
void set_available(bool available) noexcept;
|
||||
[[nodiscard]] std::size_t session_count() const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
|
||||
find_account_by_username(
|
||||
std::string_view normalized_username) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<AccountRecord>>
|
||||
find_account_by_subject(std::string_view subject) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
update_password_hash_if_version(
|
||||
std::string_view subject,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::string new_password_hash) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> create_session_if_version(
|
||||
const SessionRecord& session,
|
||||
std::uint64_t expected_credential_version,
|
||||
std::size_t max_total_sessions, std::size_t max_per_subject,
|
||||
Void::Time::CivilClock::time_point now) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::optional<SessionRecord>>
|
||||
find_session_by_token_digest(
|
||||
std::string_view token_digest) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
revoke_session(std::string_view session_id) override;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
cleanup_expired_sessions(Void::Time::CivilClock::time_point now,
|
||||
std::size_t batch_limit) override;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mu{};
|
||||
bool m_available{true};
|
||||
std::map<std::string, AccountRecord, std::less<>>
|
||||
m_accounts_by_subject{};
|
||||
std::map<std::string, std::string, std::less<>>
|
||||
m_subject_by_username{};
|
||||
std::map<std::string, SessionRecord, std::less<>>
|
||||
m_sessions_by_id{};
|
||||
std::map<std::string, std::string, std::less<>>
|
||||
m_session_id_by_digest{};
|
||||
};
|
||||
|
||||
struct AuditEvent {
|
||||
std::string event_type{};
|
||||
std::string subject{};
|
||||
std::string internal_reason{};
|
||||
bool success{false};
|
||||
Void::Time::CivilClock::time_point timestamp{};
|
||||
};
|
||||
|
||||
class AuditSink
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~AuditSink() = default;
|
||||
[[nodiscard]] virtual Void::Result::Result<void>
|
||||
record(const AuditEvent& event) = 0;
|
||||
};
|
||||
|
||||
class InMemoryAuditSink final : public AuditSink
|
||||
{
|
||||
public:
|
||||
|
||||
explicit InMemoryAuditSink(std::size_t max_events = 1024) noexcept
|
||||
: m_max_events(max_events)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
record(const AuditEvent& event) override;
|
||||
|
||||
[[nodiscard]] std::vector<AuditEvent> snapshot() const;
|
||||
void clear();
|
||||
|
||||
private:
|
||||
|
||||
std::size_t m_max_events{1024};
|
||||
mutable std::mutex m_mu{};
|
||||
std::vector<AuditEvent> m_events{};
|
||||
};
|
||||
|
||||
enum class AuditFailurePolicy : std::uint8_t {
|
||||
FailClosed = 0,
|
||||
BestEffort
|
||||
};
|
||||
|
||||
struct PasswordJobBudget {
|
||||
std::size_t max_memory_bytes{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultPasswordJobMemoryBudgetBytes};
|
||||
std::size_t max_concurrent_jobs{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultMaxConcurrentPasswordJobs};
|
||||
std::size_t max_waiters{
|
||||
Void::Security::SecurityLimits::kDefaultMaxWaitingPasswordJobs};
|
||||
};
|
||||
|
||||
struct SessionPolicy {
|
||||
std::chrono::seconds ttl{
|
||||
Void::Security::SecurityLimits::kDefaultSessionTtl};
|
||||
std::size_t max_total_sessions{
|
||||
Void::Security::SecurityLimits::kDefaultMaxTotalSessions};
|
||||
std::size_t max_per_subject{
|
||||
Void::Security::SecurityLimits::kDefaultMaxSessionsPerSubject};
|
||||
std::chrono::seconds clock_rollback_tolerance{
|
||||
Void::Security::SecurityLimits::
|
||||
kDefaultClockRollbackTolerance};
|
||||
std::size_t expiry_cleanup_batch{
|
||||
Void::Security::SecurityLimits::kDefaultExpiryCleanupBatch};
|
||||
};
|
||||
|
||||
struct AuthenticatorOptions {
|
||||
SessionPolicy session{};
|
||||
PasswordJobBudget password_budget{};
|
||||
Void::Security::PasswordVerifyBudget verify_budget{};
|
||||
Void::Security::PasswordHashStrength dummy_hash_strength{
|
||||
Void::Security::PasswordHashStrength::Moderate};
|
||||
std::string precomputed_dummy_hash{};
|
||||
AuditFailurePolicy audit_policy{AuditFailurePolicy::FailClosed};
|
||||
Void::Resilience::KeyedBucketConfig rate_limit{
|
||||
.capacity = 20.0,
|
||||
.refill_per_second = 5.0,
|
||||
.max_keys = 4096,
|
||||
.max_key_bytes = 256,
|
||||
};
|
||||
std::optional<Void::Time::CivilClock::time_point>
|
||||
last_known_civil_time{};
|
||||
Void::Security::LockPolicy secret_lock_policy{
|
||||
Void::Security::LockPolicy::StandardWiped};
|
||||
std::function<void()> before_password_verify_hook{};
|
||||
};
|
||||
|
||||
class BearerToken
|
||||
{
|
||||
public:
|
||||
|
||||
BearerToken() noexcept = default;
|
||||
BearerToken(BearerToken&&) noexcept = default;
|
||||
BearerToken& operator=(BearerToken&&) noexcept = default;
|
||||
BearerToken(const BearerToken&) = delete;
|
||||
BearerToken& operator=(const BearerToken&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<BearerToken>
|
||||
from_string(std::string_view raw,
|
||||
Void::Security::LockPolicy policy =
|
||||
Void::Security::LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] std::string_view expose_secret() const noexcept
|
||||
{
|
||||
return m_buf.string_view();
|
||||
}
|
||||
|
||||
[[nodiscard]] bool empty() const noexcept { return m_buf.empty(); }
|
||||
void clear() noexcept { m_buf.clear(); }
|
||||
|
||||
private:
|
||||
|
||||
explicit BearerToken(Void::Security::SecureBuffer buf) noexcept
|
||||
: m_buf(std::move(buf))
|
||||
{
|
||||
}
|
||||
|
||||
Void::Security::SecureBuffer m_buf{};
|
||||
friend class Authenticator;
|
||||
};
|
||||
|
||||
struct LoginInput {
|
||||
std::string username{};
|
||||
std::string password{};
|
||||
};
|
||||
|
||||
struct SessionGrant {
|
||||
std::string session_id{};
|
||||
BearerToken bearer_token{};
|
||||
Void::Time::CivilClock::time_point expires_at{};
|
||||
Void::Security::Principal principal{};
|
||||
};
|
||||
|
||||
struct AuthenticatorStats {
|
||||
std::size_t active_password_jobs{0};
|
||||
std::size_t waiting_password_jobs{0};
|
||||
std::size_t reserved_password_memory_bytes{0};
|
||||
bool closing{false};
|
||||
};
|
||||
|
||||
class Authenticator
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<
|
||||
std::unique_ptr<Authenticator>>
|
||||
create(std::shared_ptr<AccountSessionPort> port,
|
||||
Void::Async::Executor& executor,
|
||||
AuthenticatorOptions options = {},
|
||||
std::shared_ptr<AuditSink> audit_sink = {},
|
||||
const Void::Time::MonotonicClock& monotonic_clock =
|
||||
Void::Time::SystemMonotonicClock::instance(),
|
||||
const Void::Time::CivilClock& civil_clock =
|
||||
Void::Time::SystemCivilClock::instance());
|
||||
|
||||
~Authenticator();
|
||||
Authenticator(const Authenticator&) = delete;
|
||||
Authenticator& operator=(const Authenticator&) = delete;
|
||||
Authenticator(Authenticator&&) = delete;
|
||||
Authenticator& operator=(Authenticator&&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<SessionGrant>>
|
||||
login(LoginInput input,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<
|
||||
Void::Result::Result<Void::Security::Principal>>
|
||||
authenticate(const BearerToken& token,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Void::Result::Result<void>>
|
||||
revoke(std::string session_id,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||
cleanup_expired_step();
|
||||
|
||||
void reconcile_clock(
|
||||
Void::Time::CivilClock::time_point new_watermark) noexcept;
|
||||
|
||||
void request_stop() noexcept;
|
||||
[[nodiscard]] Void::Result::Result<void> close_and_join();
|
||||
|
||||
[[nodiscard]] AuthenticatorStats stats() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit Authenticator(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::SecurityAsync
|
||||
@@ -0,0 +1,170 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
struct Principal {
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::uint64_t policy_generation{0};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
struct ResourceAttributes {
|
||||
std::string resource_type{};
|
||||
std::string resource_id{};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
enum class Effect : std::uint8_t { Deny = 0, Allow = 1 };
|
||||
|
||||
/// Native typed policy predicate AST with bounded depth (<= 16) and zero
|
||||
/// script/filesystem/network side effects.
|
||||
struct Predicate {
|
||||
enum class Kind : std::uint8_t {
|
||||
AlwaysTrue = 0,
|
||||
AlwaysFalse,
|
||||
HasRole,
|
||||
SubjectEquals,
|
||||
ResourceTypeEquals,
|
||||
ResourceIdEquals,
|
||||
ResourceAttrEquals,
|
||||
PrincipalAttrEquals,
|
||||
ResourceOwnerMatchesSubject,
|
||||
AllOf,
|
||||
AnyOf,
|
||||
Not
|
||||
};
|
||||
|
||||
Kind kind{Kind::AlwaysFalse};
|
||||
std::string key{};
|
||||
std::string value{};
|
||||
std::vector<Predicate> children{};
|
||||
|
||||
[[nodiscard]] static Predicate always_true()
|
||||
{
|
||||
return Predicate{.kind = Kind::AlwaysTrue};
|
||||
}
|
||||
[[nodiscard]] static Predicate always_false()
|
||||
{
|
||||
return Predicate{.kind = Kind::AlwaysFalse};
|
||||
}
|
||||
[[nodiscard]] static Predicate has_role(std::string role)
|
||||
{
|
||||
return Predicate{.kind = Kind::HasRole,
|
||||
.value = std::move(role)};
|
||||
}
|
||||
[[nodiscard]] static Predicate subject_equals(std::string subject)
|
||||
{
|
||||
return Predicate{.kind = Kind::SubjectEquals,
|
||||
.value = std::move(subject)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_type(std::string type)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceTypeEquals,
|
||||
.value = std::move(type)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_id(std::string id)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceIdEquals,
|
||||
.value = std::move(id)};
|
||||
}
|
||||
[[nodiscard]] static Predicate resource_attr(std::string k,
|
||||
std::string v)
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceAttrEquals,
|
||||
.key = std::move(k),
|
||||
.value = std::move(v)};
|
||||
}
|
||||
[[nodiscard]] static Predicate principal_attr(std::string k,
|
||||
std::string v)
|
||||
{
|
||||
return Predicate{.kind = Kind::PrincipalAttrEquals,
|
||||
.key = std::move(k),
|
||||
.value = std::move(v)};
|
||||
}
|
||||
[[nodiscard]] static Predicate
|
||||
owner_is_subject(std::string owner_attr = "owner")
|
||||
{
|
||||
return Predicate{.kind = Kind::ResourceOwnerMatchesSubject,
|
||||
.key = std::move(owner_attr)};
|
||||
}
|
||||
[[nodiscard]] static Predicate all_of(std::vector<Predicate> items)
|
||||
{
|
||||
return Predicate{.kind = Kind::AllOf,
|
||||
.children = std::move(items)};
|
||||
}
|
||||
[[nodiscard]] static Predicate any_of(std::vector<Predicate> items)
|
||||
{
|
||||
return Predicate{.kind = Kind::AnyOf,
|
||||
.children = std::move(items)};
|
||||
}
|
||||
[[nodiscard]] static Predicate negate(Predicate child)
|
||||
{
|
||||
Predicate p{.kind = Kind::Not};
|
||||
p.children.push_back(std::move(child));
|
||||
return p;
|
||||
}
|
||||
};
|
||||
|
||||
struct PolicyRule {
|
||||
std::string id{};
|
||||
Effect effect{Effect::Deny};
|
||||
std::string action{};
|
||||
Predicate condition{Predicate::always_false()};
|
||||
};
|
||||
|
||||
struct Decision {
|
||||
bool allowed{false};
|
||||
std::string matched_rule_id{};
|
||||
std::string reason{};
|
||||
std::uint64_t policy_generation{0};
|
||||
};
|
||||
|
||||
/// Immutable validated authorization policy snapshot.
|
||||
/// Enforces default-deny and deny-overrides-allow with bounded rules
|
||||
/// (<= 4096), roles (<= 64), and predicate nesting depth (<= 16).
|
||||
class PolicySnapshot
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<PolicySnapshot>
|
||||
create(std::uint64_t generation, std::vector<PolicyRule> rules);
|
||||
|
||||
[[nodiscard]] std::uint64_t generation() const noexcept
|
||||
{
|
||||
return m_generation;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t rule_count() const noexcept
|
||||
{
|
||||
return m_rules.size();
|
||||
}
|
||||
|
||||
[[nodiscard]] Decision
|
||||
authorize(const Principal& principal, std::string_view action,
|
||||
const ResourceAttributes& resource) const;
|
||||
|
||||
private:
|
||||
|
||||
PolicySnapshot(std::uint64_t generation,
|
||||
std::vector<PolicyRule> rules) noexcept
|
||||
: m_generation(generation), m_rules(std::move(rules))
|
||||
{
|
||||
}
|
||||
|
||||
std::uint64_t m_generation{0};
|
||||
std::vector<PolicyRule> m_rules{};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
inline constexpr std::uint8_t kEnvelopeVersionV1 = 1;
|
||||
inline constexpr std::uint8_t kEnvelopeAlgXChaCha20Poly1305Ietf = 1;
|
||||
inline constexpr std::size_t kEnvelopeKeyBytes = 32;
|
||||
inline constexpr std::size_t kEnvelopeNonceBytes = 24;
|
||||
inline constexpr std::size_t kEnvelopeTagBytes = 16;
|
||||
|
||||
struct EnvelopeHeader {
|
||||
std::uint8_t version{kEnvelopeVersionV1};
|
||||
std::uint8_t algorithm{kEnvelopeAlgXChaCha20Poly1305Ietf};
|
||||
std::string key_id{};
|
||||
std::uint32_t plaintext_size{0};
|
||||
};
|
||||
|
||||
/// Parse and validate a versioned VSEC envelope header without decrypting.
|
||||
/// Never falls back to legacy seal_secret framing.
|
||||
[[nodiscard]] Void::Result::Result<EnvelopeHeader>
|
||||
inspect_envelope(std::span<const unsigned char> envelope);
|
||||
|
||||
/// Versioned AEAD key ring supporting key rotation: writes use the single
|
||||
/// active key ID, reads resolve the key ID authenticated in the header, and
|
||||
/// retirement requires proving no ciphertext still depends on that key ID.
|
||||
class SecretKeyRing
|
||||
{
|
||||
public:
|
||||
|
||||
SecretKeyRing() = default;
|
||||
SecretKeyRing(SecretKeyRing&&) noexcept = default;
|
||||
SecretKeyRing& operator=(SecretKeyRing&&) noexcept = default;
|
||||
SecretKeyRing(const SecretKeyRing&) = delete;
|
||||
SecretKeyRing& operator=(const SecretKeyRing&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
add_key(std::string key_id,
|
||||
std::span<const unsigned char> raw_key,
|
||||
bool make_active = false,
|
||||
LockPolicy lock_policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> generate_and_add_key(
|
||||
std::string key_id, bool make_active = true,
|
||||
LockPolicy lock_policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
set_active_key(std::string_view key_id);
|
||||
|
||||
/// Retire a non-active key only after the caller supplies an
|
||||
/// inventory of remaining ciphertext key IDs proving none reference
|
||||
/// `key_id`.
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
retire_key(std::string_view key_id,
|
||||
std::span<const std::string>
|
||||
remaining_ciphertext_key_ids);
|
||||
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
active_key_id() const;
|
||||
[[nodiscard]] bool has_key(std::string_view key_id) const;
|
||||
[[nodiscard]] std::vector<std::string> key_ids() const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
|
||||
seal(std::span<const unsigned char> plaintext,
|
||||
std::span<const unsigned char> aad = {}) const;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<SecureBuffer>
|
||||
open(std::span<const unsigned char> envelope,
|
||||
std::span<const unsigned char> aad = {},
|
||||
LockPolicy out_policy = LockPolicy::StandardWiped) const;
|
||||
|
||||
private:
|
||||
|
||||
std::map<std::string, SecureBuffer, std::less<>> m_keys{};
|
||||
std::string m_active_key_id{};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
enum class LockPolicy : std::uint8_t {
|
||||
StandardWiped = 0,
|
||||
LockedOptional,
|
||||
LockedRequired
|
||||
};
|
||||
|
||||
/// Move-only secret byte buffer wiped with sodium_memzero on release.
|
||||
/// Supports optional or required libsodium locked allocation without
|
||||
/// silently downgrading a LockedRequired policy.
|
||||
class SecureBuffer
|
||||
{
|
||||
public:
|
||||
|
||||
SecureBuffer() noexcept = default;
|
||||
~SecureBuffer() noexcept;
|
||||
|
||||
SecureBuffer(SecureBuffer&& other) noexcept;
|
||||
SecureBuffer& operator=(SecureBuffer&& other) noexcept;
|
||||
|
||||
SecureBuffer(const SecureBuffer&) = delete;
|
||||
SecureBuffer& operator=(const SecureBuffer&) = delete;
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
allocate(std::size_t size,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
from_bytes(std::span<const unsigned char> data,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<SecureBuffer>
|
||||
from_string(std::string_view text,
|
||||
LockPolicy policy = LockPolicy::StandardWiped);
|
||||
|
||||
[[nodiscard]] std::span<const unsigned char> view() const noexcept
|
||||
{
|
||||
return m_data ? std::span<const unsigned char>{m_data, m_size}
|
||||
: std::span<const unsigned char>{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::span<unsigned char> writable() noexcept
|
||||
{
|
||||
return m_data ? std::span<unsigned char>{m_data, m_size}
|
||||
: std::span<unsigned char>{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view string_view() const noexcept
|
||||
{
|
||||
return m_data ? std::string_view{
|
||||
reinterpret_cast<const char*>(m_data),
|
||||
m_size}
|
||||
: std::string_view{};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return m_size; }
|
||||
[[nodiscard]] bool empty() const noexcept { return m_size == 0; }
|
||||
[[nodiscard]] bool is_locked() const noexcept { return m_locked; }
|
||||
|
||||
void clear() noexcept;
|
||||
|
||||
/// Total bytes wiped across SecureBuffer lifetimes (for
|
||||
/// sanitizer-safe wipe verification in tests).
|
||||
[[nodiscard]] static std::uint64_t total_wiped_bytes() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
unsigned char* m_data{nullptr};
|
||||
std::size_t m_size{0};
|
||||
bool m_locked{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Security/Types.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
@@ -23,6 +24,14 @@ namespace Void::Security
|
||||
inline constexpr std::size_t secret_authentication_bytes = 16;
|
||||
using SecretKey = std::array<unsigned char, secret_key_bytes>;
|
||||
|
||||
/// Wipe a mutable byte buffer with sodium_memzero.
|
||||
void wipe_bytes(std::span<unsigned char> buffer) noexcept;
|
||||
|
||||
/// Constant-time comparison using sodium_memcmp.
|
||||
[[nodiscard]] bool
|
||||
constant_time_equal(std::span<const unsigned char> lhs,
|
||||
std::span<const unsigned char> rhs) noexcept;
|
||||
|
||||
/// Generate a URL-safe, unpadded token containing `entropy_bytes` of
|
||||
/// cryptographically secure randomness.
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
@@ -44,6 +53,18 @@ namespace Void::Security
|
||||
std::string_view password,
|
||||
PasswordHashStrength strength = PasswordHashStrength::Moderate);
|
||||
|
||||
/// Parse Argon2id cost parameters (`$argon2id$v=19$m=...,t=...,p=...$...`)
|
||||
/// without executing Argon2id or allocating memory.
|
||||
[[nodiscard]] Void::Result::Result<Argon2idCost>
|
||||
parse_argon2id_cost(std::string_view encoded_hash);
|
||||
|
||||
/// Verify a password against an encoded Argon2id hash after enforcing input
|
||||
/// caps and operator-approved memory/iteration/parallelism cost budgets.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
verify_password_budgeted(std::string_view password,
|
||||
std::string_view encoded_hash,
|
||||
const PasswordVerifyBudget& budget = {});
|
||||
|
||||
/// Verify a password against a libsodium Argon2id encoded hash.
|
||||
/// Malformed hashes are treated as a non-match.
|
||||
[[nodiscard]] Void::Result::Result<bool>
|
||||
@@ -53,8 +74,8 @@ namespace Void::Security
|
||||
/// Generate a cryptographically random key for local secret encryption.
|
||||
[[nodiscard]] Void::Result::Result<SecretKey> random_secret_key();
|
||||
|
||||
/// Encrypt and authenticate bytes. The returned portable envelope is
|
||||
/// nonce || ciphertext || authentication tag.
|
||||
/// Encrypt and authenticate bytes using the legacy local secret format
|
||||
/// (24-byte nonce || crypto_secretbox_easy combined MAC + ciphertext).
|
||||
[[nodiscard]] Void::Result::Result<std::vector<unsigned char>>
|
||||
seal_secret(std::span<const unsigned char> plaintext,
|
||||
const SecretKey& key);
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
struct SecurityLimits {
|
||||
static constexpr std::size_t kMaxPasswordBytes = 1024;
|
||||
static constexpr std::size_t kMaxEncodedHashBytes = 1024;
|
||||
static constexpr std::size_t kMaxTokenBytes = 512;
|
||||
static constexpr std::size_t kMaxSecretPlaintextBytes =
|
||||
16ULL * 1024ULL * 1024ULL;
|
||||
static constexpr std::size_t kMaxKeyIdBytes = 128;
|
||||
static constexpr std::size_t kMaxAadBytes = 64ULL * 1024ULL;
|
||||
static constexpr std::size_t kMaxRolesPerPrincipal = 64;
|
||||
static constexpr std::size_t kMaxPolicyRules = 4096;
|
||||
static constexpr std::size_t kMaxPredicateDepth = 16;
|
||||
static constexpr std::size_t kDefaultPasswordJobMemoryBudgetBytes =
|
||||
512ULL * 1024ULL * 1024ULL;
|
||||
static constexpr std::size_t kDefaultMaxConcurrentPasswordJobs = 2;
|
||||
static constexpr std::size_t kDefaultMaxWaitingPasswordJobs = 32;
|
||||
static constexpr std::size_t kDefaultMaxTotalSessions = 10000;
|
||||
static constexpr std::size_t kDefaultMaxSessionsPerSubject = 16;
|
||||
static constexpr std::chrono::seconds kDefaultSessionTtl{3600};
|
||||
static constexpr std::chrono::seconds
|
||||
kDefaultClockRollbackTolerance{60};
|
||||
static constexpr std::size_t kDefaultExpiryCleanupBatch = 256;
|
||||
};
|
||||
|
||||
enum class SecurityErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
input_too_large = 2,
|
||||
malformed_hash = 3,
|
||||
cost_budget_exceeded = 4,
|
||||
authentication_failed = 5,
|
||||
denied = 6,
|
||||
rate_limited = 7,
|
||||
session_expired = 8,
|
||||
session_revoked = 9,
|
||||
session_capacity_exceeded = 10,
|
||||
clock_rollback = 11,
|
||||
conflict = 12,
|
||||
key_not_found = 13,
|
||||
key_in_use = 14,
|
||||
unsupported_version = 15,
|
||||
policy_invalid = 16,
|
||||
audit_failed = 17,
|
||||
locked_memory_unavailable = 18,
|
||||
backend_error = 19,
|
||||
store_unavailable = 20,
|
||||
cancelled = 21,
|
||||
timeout = 22,
|
||||
overloaded = 23,
|
||||
closed = 24
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_security_error(SecurityErrorCode code, std::string message = {},
|
||||
std::error_code sys_err = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SecurityErrorCode::none:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SecurityErrorCode::invalid_argument:
|
||||
case SecurityErrorCode::input_too_large:
|
||||
case SecurityErrorCode::policy_invalid:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SecurityErrorCode::malformed_hash:
|
||||
case SecurityErrorCode::authentication_failed:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SecurityErrorCode::cost_budget_exceeded:
|
||||
case SecurityErrorCode::session_capacity_exceeded:
|
||||
case SecurityErrorCode::locked_memory_unavailable:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SecurityErrorCode::denied:
|
||||
case SecurityErrorCode::session_expired:
|
||||
case SecurityErrorCode::session_revoked:
|
||||
case SecurityErrorCode::clock_rollback:
|
||||
case SecurityErrorCode::conflict:
|
||||
case SecurityErrorCode::key_in_use:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SecurityErrorCode::rate_limited:
|
||||
case SecurityErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case SecurityErrorCode::key_not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SecurityErrorCode::unsupported_version:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SecurityErrorCode::audit_failed:
|
||||
case SecurityErrorCode::backend_error:
|
||||
case SecurityErrorCode::store_unavailable:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SecurityErrorCode::cancelled:
|
||||
case SecurityErrorCode::closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case SecurityErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
}
|
||||
|
||||
const ErrorCode domain_code{Void::Result::kSecurityErrorDomain,
|
||||
static_cast<std::int32_t>(code)};
|
||||
return Error{kind, std::move(message), domain_code, sys_err};
|
||||
}
|
||||
|
||||
struct Argon2idCost {
|
||||
std::uint32_t version{19};
|
||||
std::uint64_t memory_kib{0};
|
||||
std::uint64_t iterations{0};
|
||||
std::uint32_t parallelism{0};
|
||||
|
||||
[[nodiscard]] std::optional<std::uint64_t>
|
||||
memory_bytes() const noexcept
|
||||
{
|
||||
if (memory_kib >
|
||||
std::numeric_limits<std::uint64_t>::max() / 1024ULL) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return memory_kib * 1024ULL;
|
||||
}
|
||||
};
|
||||
|
||||
struct PasswordVerifyBudget {
|
||||
std::uint64_t max_memory_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t max_iterations{16};
|
||||
std::uint32_t max_parallelism{4};
|
||||
};
|
||||
|
||||
enum class FaultOperation : std::uint8_t {
|
||||
none = 0,
|
||||
any,
|
||||
sodium_init,
|
||||
random_bytes,
|
||||
locked_alloc,
|
||||
password_hash,
|
||||
secret_seal,
|
||||
secret_open
|
||||
};
|
||||
|
||||
struct FaultConfig {
|
||||
FaultOperation op{FaultOperation::none};
|
||||
SecurityErrorCode code{SecurityErrorCode::backend_error};
|
||||
std::size_t fail_after{0};
|
||||
};
|
||||
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ScopedFaultGuard(FaultConfig config) noexcept;
|
||||
~ScopedFaultGuard() noexcept;
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard(ScopedFaultGuard&&) = delete;
|
||||
ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
FaultConfig m_previous{};
|
||||
std::size_t m_previous_hits{0};
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
[[nodiscard]] std::optional<Void::Result::Error>
|
||||
maybe_inject_fault(FaultOperation op, std::string_view operation);
|
||||
} // namespace Detail
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -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
|
||||
)
|
||||
@@ -179,6 +179,24 @@ if(_has_crypto_async)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_security Security Time Functional)
|
||||
if(_has_security)
|
||||
run_consumer(SecurityOnly "${install_prefix}" "SecurityOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_security_async SecurityAsync Security Async Time Resilience Functional)
|
||||
if(_has_security_async)
|
||||
run_consumer(SecurityAsyncOnly "${install_prefix}" "SecurityAsyncOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidSecurityAsyncOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS SecurityAsync)
|
||||
|
||||
add_executable(void_security_async_only_consumer main.cpp)
|
||||
target_link_libraries(void_security_async_only_consumer PRIVATE Void::SecurityAsync)
|
||||
target_compile_features(void_security_async_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME SecurityAsyncOnlyConsumer COMMAND void_security_async_only_consumer)
|
||||
@@ -0,0 +1,21 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Security/Authenticator.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
int main()
|
||||
{
|
||||
auto store = std::make_shared<Void::SecurityAsync::InMemoryAccountSessionStore>();
|
||||
Void::Async::ManualExecutor exec;
|
||||
Void::SecurityAsync::AuthenticatorOptions opts{};
|
||||
opts.dummy_hash_strength = Void::Security::PasswordHashStrength::Interactive;
|
||||
auto auth = Void::SecurityAsync::Authenticator::create(store, exec, opts);
|
||||
if (!auth.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
if ((*auth)->stats().active_password_jobs != 0) {
|
||||
return 2;
|
||||
}
|
||||
(void)(*auth)->close_and_join();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidSecurityOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS Security)
|
||||
|
||||
add_executable(void_security_only_consumer main.cpp)
|
||||
target_link_libraries(void_security_only_consumer PRIVATE Void::Security)
|
||||
target_compile_features(void_security_only_consumer PRIVATE cxx_std_26)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME SecurityOnlyConsumer COMMAND void_security_only_consumer)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/Security/Authorization.hpp>
|
||||
#include <Void/Security/Envelope.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Security.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Security::SecretKeyRing ring;
|
||||
if (!ring.generate_and_add_key("v1", true).has_value()) {
|
||||
return 1;
|
||||
}
|
||||
const std::vector<unsigned char> pt{'o', 'k'};
|
||||
auto env = ring.seal(pt);
|
||||
if (!env.has_value()) {
|
||||
return 2;
|
||||
}
|
||||
auto dec = ring.open(*env);
|
||||
if (!dec.has_value() || dec->size() != pt.size()) {
|
||||
return 3;
|
||||
}
|
||||
auto policy = Void::Security::PolicySnapshot::create(1, {});
|
||||
if (!policy.has_value()) {
|
||||
return 4;
|
||||
}
|
||||
const Void::Security::Principal p{.subject = "u1"};
|
||||
const Void::Security::ResourceAttributes r{.resource_type = "doc"};
|
||||
if (policy->authorize(p, "read", r).allowed) {
|
||||
return 5;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
#include <Void/Security/Authorization.hpp>
|
||||
#include <Void/Security/Envelope.hpp>
|
||||
#include <Void/Security/SecureBuffer.hpp>
|
||||
#include <Void/Security/Security.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
Void::Testing::Test security_secure_buffer_wipe_and_lock_policies()
|
||||
{
|
||||
using namespace Void::Security;
|
||||
|
||||
const auto wiped_before = SecureBuffer::total_wiped_bytes();
|
||||
{
|
||||
auto buf = SecureBuffer::from_string("top-secret-key-material");
|
||||
Void::Testing::require(buf.has_value());
|
||||
Void::Testing::expect_eq(buf->string_view(),
|
||||
std::string_view{"top-secret-key-material"});
|
||||
Void::Testing::expect(!buf->is_locked());
|
||||
|
||||
auto moved = std::move(*buf);
|
||||
Void::Testing::expect(buf->empty());
|
||||
Void::Testing::expect_eq(moved.size(), 23U);
|
||||
}
|
||||
Void::Testing::expect(SecureBuffer::total_wiped_bytes() >=
|
||||
wiped_before + 23U);
|
||||
|
||||
// LockedRequired fails closed on locked allocation failure (no downgrade).
|
||||
{
|
||||
ScopedFaultGuard fault{
|
||||
FaultConfig{FaultOperation::locked_alloc,
|
||||
SecurityErrorCode::locked_memory_unavailable, 0}};
|
||||
auto required = SecureBuffer::allocate(64, LockPolicy::LockedRequired);
|
||||
Void::Testing::require(!required.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
required.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
SecurityErrorCode::locked_memory_unavailable));
|
||||
|
||||
auto optional = SecureBuffer::allocate(64, LockPolicy::LockedOptional);
|
||||
Void::Testing::require(optional.has_value());
|
||||
Void::Testing::expect(!optional->is_locked());
|
||||
}
|
||||
|
||||
// Oversized allocation rejected before touching backend.
|
||||
auto huge =
|
||||
SecureBuffer::allocate(SecurityLimits::kMaxSecretPlaintextBytes + 1U);
|
||||
Void::Testing::require(!huge.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
huge.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
|
||||
}
|
||||
|
||||
Void::Testing::Test security_input_caps_cost_budget_and_fault_seams()
|
||||
{
|
||||
using namespace Void::Security;
|
||||
|
||||
// Excessive Argon2id memory/iteration cost rejected BEFORE allocation.
|
||||
const std::string malicious_mem =
|
||||
"$argon2id$v=19$m=4194304,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$"
|
||||
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
|
||||
auto parsed = parse_argon2id_cost(malicious_mem);
|
||||
Void::Testing::require(parsed.has_value());
|
||||
Void::Testing::expect_eq(parsed->memory_kib, 4194304ULL);
|
||||
|
||||
PasswordVerifyBudget tight_budget{
|
||||
.max_memory_bytes = 64ULL * 1024ULL * 1024ULL,
|
||||
.max_iterations = 4,
|
||||
.max_parallelism = 2,
|
||||
};
|
||||
auto rejected = verify_password_budgeted("pw", malicious_mem, tight_budget);
|
||||
Void::Testing::require(!rejected.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
rejected.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::cost_budget_exceeded));
|
||||
|
||||
// Malformed hash corpus rejected cleanly.
|
||||
for (const std::string_view bad : {
|
||||
"",
|
||||
"$argon2i$v=19$m=65536,t=2,p=1$aaaa$bbbb",
|
||||
"$argon2id$v=18$m=65536,t=2,p=1$aaaa$bbbb",
|
||||
"$argon2id$v=19$m=0,t=2,p=1$aaaa$bbbb",
|
||||
"$argon2id$v=19$m=99999999999999999999,t=2,p=1$aaaa$bbbb",
|
||||
"$argon2id$v=19$m=65536,t=2$aaaa$bbbb",
|
||||
"$argon2id$v=19$m=65536,t=2,p=1$aaaa$",
|
||||
}) {
|
||||
Void::Testing::expect(!parse_argon2id_cost(bad).has_value());
|
||||
}
|
||||
|
||||
// Input length caps: >1 KiB password, >512 B token.
|
||||
const std::string long_pw(SecurityLimits::kMaxPasswordBytes + 1U, 'p');
|
||||
auto pw_err = hash_password(long_pw, PasswordHashStrength::Interactive);
|
||||
Void::Testing::require(!pw_err.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
pw_err.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
|
||||
|
||||
const std::string long_tok(SecurityLimits::kMaxTokenBytes + 1U, 't');
|
||||
auto tok_err = hash_token(long_tok);
|
||||
Void::Testing::require(!tok_err.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
tok_err.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
|
||||
|
||||
// Sodium init / randomness failure publishes no token or key.
|
||||
{
|
||||
ScopedFaultGuard fault{FaultConfig{FaultOperation::sodium_init,
|
||||
SecurityErrorCode::backend_error, 0}};
|
||||
Void::Testing::expect(!random_token().has_value());
|
||||
Void::Testing::expect(!random_secret_key().has_value());
|
||||
}
|
||||
{
|
||||
ScopedFaultGuard fault{FaultConfig{FaultOperation::random_bytes,
|
||||
SecurityErrorCode::backend_error, 0}};
|
||||
Void::Testing::expect(!random_token().has_value());
|
||||
Void::Testing::expect(!random_secret_key().has_value());
|
||||
}
|
||||
|
||||
// Legacy envelope exact byte layout preserved: 24B nonce + 16B MAC + pt.
|
||||
auto key = random_secret_key();
|
||||
Void::Testing::require(key.has_value());
|
||||
const std::vector<unsigned char> pt{'v', 'o', 'i', 'd'};
|
||||
auto legacy = seal_secret(pt, *key);
|
||||
Void::Testing::require(legacy.has_value());
|
||||
Void::Testing::expect_eq(legacy->size(),
|
||||
secret_nonce_bytes + secret_authentication_bytes +
|
||||
pt.size());
|
||||
auto opened = open_secret(*legacy, *key);
|
||||
Void::Testing::require(opened.has_value());
|
||||
Void::Testing::expect_eq(*opened, pt);
|
||||
}
|
||||
|
||||
Void::Testing::Test security_versioned_envelope_rotation_and_no_legacy_fallback()
|
||||
{
|
||||
using namespace Void::Security;
|
||||
|
||||
SecretKeyRing ring;
|
||||
Void::Testing::require(ring.generate_and_add_key("k1", true).has_value());
|
||||
Void::Testing::expect_eq(ring.active_key_id().value_or(""),
|
||||
std::string{"k1"});
|
||||
|
||||
const std::vector<unsigned char> pt{'a', 'p', 'i', '-', 'k', 'e', 'y'};
|
||||
const std::vector<unsigned char> aad{'t', 'e', 'n', 'a', 'n', 't', ':', '1'};
|
||||
const std::vector<unsigned char> wrong_aad{'t', 'e', 'n', 'a',
|
||||
'n', 't', ':', '2'};
|
||||
|
||||
auto env_k1 = ring.seal(pt, aad);
|
||||
Void::Testing::require(env_k1.has_value());
|
||||
|
||||
auto hdr = inspect_envelope(*env_k1);
|
||||
Void::Testing::require(hdr.has_value());
|
||||
Void::Testing::expect_eq(hdr->version, kEnvelopeVersionV1);
|
||||
Void::Testing::expect_eq(hdr->algorithm, kEnvelopeAlgXChaCha20Poly1305Ietf);
|
||||
Void::Testing::expect_eq(hdr->key_id, std::string{"k1"});
|
||||
Void::Testing::expect_eq(hdr->plaintext_size,
|
||||
static_cast<std::uint32_t>(pt.size()));
|
||||
|
||||
// Rotate to k2: new writes use k2, old k1 envelopes still decrypt.
|
||||
Void::Testing::require(ring.generate_and_add_key("k2", true).has_value());
|
||||
Void::Testing::expect_eq(ring.active_key_id().value_or(""),
|
||||
std::string{"k2"});
|
||||
|
||||
auto env_k2 = ring.seal(pt, aad);
|
||||
Void::Testing::require(env_k2.has_value());
|
||||
auto hdr2 = inspect_envelope(*env_k2);
|
||||
Void::Testing::require(hdr2.has_value());
|
||||
Void::Testing::expect_eq(hdr2->key_id, std::string{"k2"});
|
||||
|
||||
auto dec1 = ring.open(*env_k1, aad);
|
||||
auto dec2 = ring.open(*env_k2, aad);
|
||||
Void::Testing::require(dec1.has_value() && dec2.has_value());
|
||||
Void::Testing::expect(constant_time_equal(dec1->view(), pt));
|
||||
Void::Testing::expect(constant_time_equal(dec2->view(), pt));
|
||||
|
||||
// Wrong AAD fails authentication.
|
||||
auto bad_aad = ring.open(*env_k1, wrong_aad);
|
||||
Void::Testing::require(!bad_aad.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_aad.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::authentication_failed));
|
||||
|
||||
// Tampering any header/key_id/ciphertext byte fails authentication.
|
||||
auto tampered = *env_k1;
|
||||
tampered.back() ^= 0x80U;
|
||||
Void::Testing::expect(!ring.open(tampered, aad).has_value());
|
||||
|
||||
auto bad_ver = *env_k1;
|
||||
bad_ver[4] = 99U;
|
||||
auto ver_res = ring.open(bad_ver, aad);
|
||||
Void::Testing::require(!ver_res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
ver_res.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::unsupported_version));
|
||||
|
||||
// Legacy secretbox envelope MUST NOT silently fall back in SecretKeyRing.
|
||||
auto legacy_key = random_secret_key();
|
||||
Void::Testing::require(legacy_key.has_value());
|
||||
auto legacy_env = seal_secret(pt, *legacy_key);
|
||||
Void::Testing::require(legacy_env.has_value());
|
||||
auto no_fallback = ring.open(*legacy_env, {});
|
||||
Void::Testing::require(!no_fallback.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
no_fallback.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::unsupported_version));
|
||||
|
||||
// Key retirement guards: cannot retire active key or key still in inventory.
|
||||
const std::vector<std::string> empty_inv{};
|
||||
auto retire_active = ring.retire_key("k2", empty_inv);
|
||||
Void::Testing::require(!retire_active.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
retire_active.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::key_in_use));
|
||||
|
||||
const std::vector<std::string> still_used{"k1", "k2"};
|
||||
auto retire_in_use = ring.retire_key("k1", still_used);
|
||||
Void::Testing::require(!retire_in_use.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
retire_in_use.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::key_in_use));
|
||||
|
||||
const std::vector<std::string> migrated_inv{"k2"};
|
||||
Void::Testing::require(ring.retire_key("k1", migrated_inv).has_value());
|
||||
Void::Testing::expect(!ring.has_key("k1"));
|
||||
auto retired_open = ring.open(*env_k1, aad);
|
||||
Void::Testing::require(!retired_open.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
retired_open.error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::key_not_found));
|
||||
}
|
||||
|
||||
Void::Testing::Test security_authorization_default_deny_and_limits()
|
||||
{
|
||||
using namespace Void::Security;
|
||||
|
||||
auto policy = PolicySnapshot::create(
|
||||
7,
|
||||
{
|
||||
PolicyRule{
|
||||
.id = "allow-owner-read",
|
||||
.effect = Effect::Allow,
|
||||
.action = "doc:read",
|
||||
.condition = Predicate::all_of(
|
||||
{Predicate::resource_type("document"),
|
||||
Predicate::owner_is_subject()}),
|
||||
},
|
||||
PolicyRule{
|
||||
.id = "allow-admin-all",
|
||||
.effect = Effect::Allow,
|
||||
.action = "*",
|
||||
.condition = Predicate::has_role("admin"),
|
||||
},
|
||||
PolicyRule{
|
||||
.id = "deny-classified",
|
||||
.effect = Effect::Deny,
|
||||
.action = "*",
|
||||
.condition = Predicate::resource_attr("tier", "classified"),
|
||||
},
|
||||
});
|
||||
Void::Testing::require(policy.has_value());
|
||||
|
||||
Principal alice{
|
||||
.subject = "alice", .roles = {"editor"}, .policy_generation = 7};
|
||||
Principal admin{
|
||||
.subject = "root", .roles = {"admin"}, .policy_generation = 7};
|
||||
ResourceAttributes doc{
|
||||
.resource_type = "document",
|
||||
.resource_id = "d1",
|
||||
.attributes = {{"owner", "alice"}, {"tier", "standard"}},
|
||||
};
|
||||
ResourceAttributes secret_doc{
|
||||
.resource_type = "document",
|
||||
.resource_id = "d2",
|
||||
.attributes = {{"owner", "alice"}, {"tier", "classified"}},
|
||||
};
|
||||
|
||||
// Explicit allow for owner.
|
||||
auto d1 = policy->authorize(alice, "doc:read", doc);
|
||||
Void::Testing::expect(d1.allowed);
|
||||
Void::Testing::expect_eq(d1.matched_rule_id,
|
||||
std::string{"allow-owner-read"});
|
||||
|
||||
// Default deny for unmatched action.
|
||||
auto d2 = policy->authorize(alice, "doc:delete", doc);
|
||||
Void::Testing::expect(!d2.allowed);
|
||||
|
||||
// Deny overrides allow even for admin.
|
||||
auto d3 = policy->authorize(admin, "doc:read", secret_doc);
|
||||
Void::Testing::expect(!d3.allowed);
|
||||
Void::Testing::expect_eq(d3.matched_rule_id,
|
||||
std::string{"deny-classified"});
|
||||
|
||||
// Principal exceeding 64 roles fails closed.
|
||||
Principal bloated{.subject = "bob"};
|
||||
bloated.roles.assign(SecurityLimits::kMaxRolesPerPrincipal + 1U, "admin");
|
||||
Void::Testing::expect(!policy->authorize(bloated, "doc:read", doc).allowed);
|
||||
|
||||
// Rule count > 4096 rejected.
|
||||
std::vector<PolicyRule> too_many(
|
||||
SecurityLimits::kMaxPolicyRules + 1U,
|
||||
PolicyRule{.id = "r",
|
||||
.effect = Effect::Allow,
|
||||
.action = "x",
|
||||
.condition = Predicate::always_true()});
|
||||
Void::Testing::expect(!PolicySnapshot::create(1, std::move(too_many)).has_value());
|
||||
|
||||
// Predicate depth > 16 rejected.
|
||||
Predicate deep = Predicate::always_true();
|
||||
for (std::size_t i = 0; i < SecurityLimits::kMaxPredicateDepth + 1U; ++i) {
|
||||
deep = Predicate::negate(std::move(deep));
|
||||
}
|
||||
Void::Testing::expect(
|
||||
!PolicySnapshot::create(
|
||||
1, {PolicyRule{.id = "deep",
|
||||
.effect = Effect::Allow,
|
||||
.action = "x",
|
||||
.condition = std::move(deep)}})
|
||||
.has_value());
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/Security/Authenticator.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Void::Security;
|
||||
using namespace Void::SecurityAsync;
|
||||
|
||||
Void::Coro::Task<void> run_login(
|
||||
Authenticator& auth, LoginInput input,
|
||||
Void::Async::OperationOptions opts,
|
||||
std::optional<Void::Result::Result<SessionGrant>>& out,
|
||||
std::atomic<int>* done = nullptr)
|
||||
{
|
||||
out = co_await auth.login(std::move(input), std::move(opts));
|
||||
if (done != nullptr) {
|
||||
done->fetch_add(1, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> run_authenticate(
|
||||
Authenticator& auth, const BearerToken& token,
|
||||
Void::Async::OperationOptions opts,
|
||||
std::optional<Void::Result::Result<Principal>>& out)
|
||||
{
|
||||
out = co_await auth.authenticate(token, std::move(opts));
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> run_revoke(
|
||||
Authenticator& auth, std::string session_id,
|
||||
Void::Async::OperationOptions opts,
|
||||
std::optional<Void::Result::Result<void>>& out)
|
||||
{
|
||||
out = co_await auth.revoke(std::move(session_id), std::move(opts));
|
||||
}
|
||||
|
||||
void pump_until(Void::Async::ManualExecutor& exec,
|
||||
const std::atomic<int>& counter, int target)
|
||||
{
|
||||
const auto deadline =
|
||||
std::chrono::steady_clock::now() + std::chrono::seconds{15};
|
||||
while (counter.load(std::memory_order_acquire) < target &&
|
||||
std::chrono::steady_clock::now() < deadline) {
|
||||
if (exec.drain() == 0) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{1});
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test security_async_login_auth_revoke_expiry_and_clock_rollback()
|
||||
{
|
||||
auto store = std::make_shared<InMemoryAccountSessionStore>();
|
||||
auto audit = std::make_shared<InMemoryAuditSink>(64);
|
||||
Void::Async::ManualExecutor exec;
|
||||
Void::Time::ManualClock mono_clock;
|
||||
Void::Time::ManualCivilClock civil_clock{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1000000}}};
|
||||
|
||||
auto alice_hash =
|
||||
hash_password("correct-pw", PasswordHashStrength::Interactive);
|
||||
Void::Testing::require(alice_hash.has_value());
|
||||
Void::Testing::require(
|
||||
store
|
||||
->upsert_account(AccountRecord{
|
||||
.subject = "sub-alice",
|
||||
.normalized_username = "alice",
|
||||
.password_hash = *alice_hash,
|
||||
.roles = {"user"},
|
||||
.credential_version = 1,
|
||||
.revocation_generation = 1,
|
||||
.policy_generation = 3,
|
||||
.enabled = true,
|
||||
})
|
||||
.has_value());
|
||||
|
||||
AuthenticatorOptions opts{};
|
||||
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
|
||||
opts.precomputed_dummy_hash = *alice_hash;
|
||||
opts.session.ttl = std::chrono::seconds{3600};
|
||||
opts.session.max_total_sessions = 4;
|
||||
opts.session.max_per_subject = 2;
|
||||
opts.session.clock_rollback_tolerance = std::chrono::seconds{60};
|
||||
|
||||
auto auth = Authenticator::create(store, exec, opts, audit, mono_clock,
|
||||
civil_clock);
|
||||
Void::Testing::require(auth.has_value());
|
||||
|
||||
// 1. Unknown account and wrong password produce identical public denial but
|
||||
// distinct internal audit reasons.
|
||||
{
|
||||
std::optional<Void::Result::Result<SessionGrant>> unknown_res;
|
||||
std::optional<Void::Result::Result<SessionGrant>> wrong_pw_res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"ghost", "any"}, {}, unknown_res,
|
||||
&done))
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"ALICE", "wrong-pw"}, {},
|
||||
wrong_pw_res, &done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 2);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
|
||||
Void::Testing::require(unknown_res.has_value() &&
|
||||
!unknown_res->has_value());
|
||||
Void::Testing::require(wrong_pw_res.has_value() &&
|
||||
!wrong_pw_res->has_value());
|
||||
Void::Testing::expect_eq(unknown_res->error().code().value,
|
||||
wrong_pw_res->error().code().value);
|
||||
Void::Testing::expect_eq(unknown_res->error().message(),
|
||||
wrong_pw_res->error().message());
|
||||
|
||||
const auto events = audit->snapshot();
|
||||
bool saw_not_found = false;
|
||||
bool saw_invalid_pw = false;
|
||||
for (const auto& ev : events) {
|
||||
if (ev.internal_reason == "account_not_found") {
|
||||
saw_not_found = true;
|
||||
}
|
||||
if (ev.internal_reason == "invalid_password") {
|
||||
saw_invalid_pw = true;
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(saw_not_found);
|
||||
Void::Testing::expect(saw_invalid_pw);
|
||||
}
|
||||
|
||||
// 2. Successful login (case-insensitive username) + authoritative
|
||||
// authenticate + immediate revocation (zero positive cache).
|
||||
std::optional<SessionGrant> grant1;
|
||||
{
|
||||
std::optional<Void::Result::Result<SessionGrant>> res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {" Alice ", "correct-pw"}, {}, res,
|
||||
&done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(res.has_value() && res->has_value());
|
||||
grant1.emplace(std::move(**res));
|
||||
}
|
||||
|
||||
{
|
||||
std::optional<Void::Result::Result<Principal>> principal;
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_authenticate(**auth, grant1->bearer_token, {},
|
||||
principal))
|
||||
.has_value());
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(principal.has_value() && principal->has_value());
|
||||
Void::Testing::expect_eq((*principal)->subject,
|
||||
std::string{"sub-alice"});
|
||||
Void::Testing::expect_eq((*principal)->policy_generation, 3ULL);
|
||||
}
|
||||
|
||||
// Revoke takes effect immediately on next authenticate call.
|
||||
{
|
||||
std::optional<Void::Result::Result<void>> rev_res;
|
||||
std::optional<Void::Result::Result<Principal>> after_rev;
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_revoke(**auth, grant1->session_id, {}, rev_res))
|
||||
.has_value());
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(rev_res.has_value() && rev_res->has_value());
|
||||
|
||||
Void::Async::TaskScope scope2{exec};
|
||||
Void::Testing::require(
|
||||
scope2
|
||||
.spawn(run_authenticate(**auth, grant1->bearer_token, {},
|
||||
after_rev))
|
||||
.has_value());
|
||||
Void::Testing::require(scope2.join_pumping(exec).has_value());
|
||||
Void::Testing::require(after_rev.has_value() && !after_rev->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
after_rev->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::session_revoked));
|
||||
}
|
||||
|
||||
// 3. Per-subject session capacity (max_per_subject = 2) enforced, and
|
||||
// expiry + bounded cleanup reclaims slots.
|
||||
std::optional<SessionGrant> g2;
|
||||
std::optional<SessionGrant> g3;
|
||||
for (auto* target : {&g2, &g3}) {
|
||||
std::optional<Void::Result::Result<SessionGrant>> res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, res, &done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(res.has_value() && res->has_value());
|
||||
target->emplace(std::move(**res));
|
||||
}
|
||||
{
|
||||
std::optional<Void::Result::Result<SessionGrant>> over_cap;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, over_cap,
|
||||
&done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(over_cap.has_value() && !over_cap->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
over_cap->error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
SecurityErrorCode::session_capacity_exceeded));
|
||||
}
|
||||
|
||||
// Advance civil clock past TTL -> authenticate denies expired, cleanup
|
||||
// removes sessions.
|
||||
Void::Testing::require(
|
||||
civil_clock.advance(std::chrono::seconds{3601}).has_value());
|
||||
{
|
||||
std::optional<Void::Result::Result<Principal>> expired;
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_authenticate(**auth, g2->bearer_token, {}, expired))
|
||||
.has_value());
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(expired.has_value() && !expired->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
expired->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::session_expired));
|
||||
}
|
||||
auto cleaned = (*auth)->cleanup_expired_step();
|
||||
Void::Testing::require(cleaned.has_value());
|
||||
Void::Testing::expect_eq(*cleaned, 3U);
|
||||
|
||||
// 4. Civil-clock rollback beyond 60s tolerance halts admission until
|
||||
// explicitly reconciled.
|
||||
civil_clock.set(civil_clock.now() - std::chrono::seconds{120});
|
||||
{
|
||||
std::optional<Void::Result::Result<SessionGrant>> halted;
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, halted))
|
||||
.has_value());
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(halted.has_value() && !halted->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
halted->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::clock_rollback));
|
||||
}
|
||||
(*auth)->reconcile_clock(civil_clock.now());
|
||||
|
||||
// 5. Store outage fails closed.
|
||||
store->set_available(false);
|
||||
{
|
||||
std::optional<Void::Result::Result<SessionGrant>> outage;
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, outage))
|
||||
.has_value());
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(outage.has_value() && !outage->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
outage->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::store_unavailable));
|
||||
}
|
||||
store->set_available(true);
|
||||
|
||||
Void::Testing::require((*auth)->close_and_join().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test security_async_version_race_hash_stop_and_mandatory_audit()
|
||||
{
|
||||
auto store = std::make_shared<InMemoryAccountSessionStore>();
|
||||
auto audit = std::make_shared<InMemoryAuditSink>(1); // capacity 1!
|
||||
Void::Async::ManualExecutor exec;
|
||||
Void::Time::ManualClock mono_clock;
|
||||
Void::Time::ManualCivilClock civil_clock{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{2000000}}};
|
||||
|
||||
auto pw_hash =
|
||||
hash_password("hunter2", PasswordHashStrength::Interactive);
|
||||
Void::Testing::require(pw_hash.has_value());
|
||||
Void::Testing::require(
|
||||
store
|
||||
->upsert_account(AccountRecord{
|
||||
.subject = "sub-bob",
|
||||
.normalized_username = "bob",
|
||||
.password_hash = *pw_hash,
|
||||
.roles = {"member"},
|
||||
.credential_version = 1,
|
||||
.revocation_generation = 1,
|
||||
.policy_generation = 1,
|
||||
.enabled = true,
|
||||
})
|
||||
.has_value());
|
||||
|
||||
// 1. Stop during in-flight password hash: worker drains to completion,
|
||||
// releases memory budget, discards outcome, and creates zero sessions.
|
||||
{
|
||||
std::promise<void> entered_hash;
|
||||
std::promise<void> release_hash;
|
||||
auto entered_fut = entered_hash.get_future();
|
||||
auto release_fut = release_hash.get_future().share();
|
||||
|
||||
AuthenticatorOptions opts{};
|
||||
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
|
||||
opts.precomputed_dummy_hash = *pw_hash;
|
||||
opts.before_password_verify_hook = [&]() {
|
||||
entered_hash.set_value();
|
||||
release_fut.wait();
|
||||
};
|
||||
|
||||
auto auth = Authenticator::create(store, exec, opts, nullptr,
|
||||
mono_clock, civil_clock);
|
||||
Void::Testing::require(auth.has_value());
|
||||
|
||||
std::stop_source ss;
|
||||
std::optional<Void::Result::Result<SessionGrant>> res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"bob", "hunter2"},
|
||||
Void::Async::OperationOptions{
|
||||
.stop = ss.get_token()},
|
||||
res, &done))
|
||||
.has_value());
|
||||
(void)exec.drain();
|
||||
|
||||
// Wait until worker actually holds password job budget.
|
||||
entered_fut.wait();
|
||||
Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 1U);
|
||||
Void::Testing::expect((*auth)->stats().reserved_password_memory_bytes >
|
||||
0U);
|
||||
|
||||
ss.request_stop();
|
||||
release_hash.set_value();
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
|
||||
Void::Testing::require(res.has_value() && !res->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::cancelled));
|
||||
Void::Testing::expect_eq(store->session_count(), 0U);
|
||||
Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 0U);
|
||||
Void::Testing::expect_eq(
|
||||
(*auth)->stats().reserved_password_memory_bytes, 0U);
|
||||
Void::Testing::require((*auth)->close_and_join().has_value());
|
||||
}
|
||||
|
||||
// 2. Credential version change racing with login invalidates session write.
|
||||
{
|
||||
AuthenticatorOptions opts{};
|
||||
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
|
||||
opts.precomputed_dummy_hash = *pw_hash;
|
||||
opts.before_password_verify_hook = [&]() {
|
||||
(void)store->bump_credential_version("sub-bob");
|
||||
};
|
||||
|
||||
auto auth = Authenticator::create(store, exec, opts, nullptr,
|
||||
mono_clock, civil_clock);
|
||||
Void::Testing::require(auth.has_value());
|
||||
|
||||
std::optional<Void::Result::Result<SessionGrant>> res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(res.has_value() && !res->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::conflict));
|
||||
Void::Testing::expect_eq(store->session_count(), 0U);
|
||||
Void::Testing::require((*auth)->close_and_join().has_value());
|
||||
}
|
||||
|
||||
// 3. Mandatory fail-closed audit queue full revokes session and fails login.
|
||||
{
|
||||
// Pre-fill the 1-slot audit sink.
|
||||
Void::Testing::require(
|
||||
audit->record(AuditEvent{.event_type = "fill"}).has_value());
|
||||
|
||||
AuthenticatorOptions opts{};
|
||||
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
|
||||
opts.precomputed_dummy_hash = *pw_hash;
|
||||
opts.audit_policy = AuditFailurePolicy::FailClosed;
|
||||
|
||||
auto auth = Authenticator::create(store, exec, opts, audit, mono_clock,
|
||||
civil_clock);
|
||||
Void::Testing::require(auth.has_value());
|
||||
|
||||
std::optional<Void::Result::Result<SessionGrant>> res;
|
||||
std::atomic<int> done{0};
|
||||
Void::Async::TaskScope scope{exec};
|
||||
Void::Testing::require(
|
||||
scope
|
||||
.spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done))
|
||||
.has_value());
|
||||
pump_until(exec, done, 1);
|
||||
Void::Testing::require(scope.join_pumping(exec).has_value());
|
||||
Void::Testing::require(res.has_value() && !res->has_value());
|
||||
Void::Testing::expect_eq(
|
||||
res->error().code().value,
|
||||
static_cast<std::int32_t>(SecurityErrorCode::audit_failed));
|
||||
Void::Testing::require((*auth)->close_and_join().has_value());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user