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
|
||||
Reference in new issue
Block a user