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