Files
Library/src/Security/Security.cpp

549 lines
18 KiB
C++

#include <Void/Security/Security.hpp>
#include <sodium.h>
#include <array>
#include <charconv>
#include <cstring>
#include <format>
#include <limits>
#include <optional>
#include <vector>
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;
};
[[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 std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security: libsodium initialization failed")};
}
return {};
}
[[nodiscard]] std::optional<PasswordLimits>
password_limits(PasswordHashStrength strength) noexcept
{
switch (strength) {
case PasswordHashStrength::Interactive:
return PasswordLimits{crypto_pwhash_OPSLIMIT_INTERACTIVE,
crypto_pwhash_MEMLIMIT_INTERACTIVE};
case PasswordHashStrength::Moderate:
return PasswordLimits{crypto_pwhash_OPSLIMIT_MODERATE,
crypto_pwhash_MEMLIMIT_MODERATE};
case PasswordHashStrength::Sensitive:
return PasswordLimits{crypto_pwhash_OPSLIMIT_SENSITIVE,
crypto_pwhash_MEMLIMIT_SENSITIVE};
}
return std::nullopt;
}
[[nodiscard]] std::array<unsigned char, crypto_generichash_BYTES>
token_digest(std::string_view token) noexcept
{
std::array<unsigned char, crypto_generichash_BYTES> digest{};
(void)crypto_generichash(
digest.data(), digest.size(),
reinterpret_cast<const unsigned char*>(token.data()),
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 std::unexpected{initialized.error()};
}
if (entropy_bytes == 0) {
return std::unexpected{make_security_error(
SecurityErrorCode::invalid_argument,
"Security::random_token: entropy must be greater than zero")};
}
// 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);
randombytes_buf(random.data(), random.size());
const auto encoded_size = sodium_base64_ENCODED_LEN(
random.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
std::string encoded(encoded_size, '\0');
const auto* result = sodium_bin2base64(
encoded.data(), encoded.size(), random.data(), random.size(),
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
sodium_memzero(random.data(), random.size());
if (result == nullptr) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::random_token: base64 encoding failed")};
}
encoded.resize(std::strlen(encoded.c_str()));
return encoded;
}
Void::Result::Result<std::string> hash_token(std::string_view token)
{
if (const auto initialized = ensure_sodium(); !initialized) {
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);
std::array<char, crypto_generichash_BYTES * 2 + 1> encoded{};
(void)sodium_bin2hex(encoded.data(), encoded.size(), digest.data(),
digest.size());
return std::string{encoded.data(), encoded.size() - 1};
}
Void::Result::Result<bool> verify_token(std::string_view token,
std::string_view encoded_hash)
{
if (const auto initialized = ensure_sodium(); !initialized) {
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;
if (encoded_hash.size() != encoded_length) {
return false;
}
std::array<unsigned char, crypto_generichash_BYTES> expected{};
std::size_t decoded_length = 0;
if (sodium_hex2bin(expected.data(), expected.size(),
encoded_hash.data(), encoded_hash.size(), nullptr,
&decoded_length, nullptr) != 0 ||
decoded_length != expected.size()) {
return false;
}
const auto actual = token_digest(token);
return sodium_memcmp(actual.data(), expected.data(), actual.size()) ==
0;
}
Void::Result::Result<std::string>
hash_password(std::string_view password, PasswordHashStrength strength)
{
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::hash_password: password exceeds 1 KiB cap")};
}
const auto limits = password_limits(strength);
if (!limits) {
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{};
if (crypto_pwhash_str_alg(
encoded.data(), password.data(),
static_cast<unsigned long long>(password.size()),
limits->operations, limits->memory,
crypto_pwhash_ALG_ARGON2ID13) != 0) {
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 std::unexpected{initialized.error()};
}
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(
terminated_hash.c_str(), password.data(),
static_cast<unsigned long long>(password.size())) == 0;
}
Void::Result::Result<SecretKey> random_secret_key()
{
if (const auto initialized = ensure_sodium(); !initialized) {
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);
SecretKey key{};
crypto_secretbox_keygen(key.data());
return key;
}
Void::Result::Result<std::vector<unsigned char>>
seal_secret(std::span<const unsigned char> plaintext,
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return std::unexpected{initialized.error()};
}
static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES);
static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES);
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 +
secret_authentication_bytes +
plaintext.size());
auto* nonce = envelope.data();
auto* ciphertext = nonce + secret_nonce_bytes;
randombytes_buf(nonce, secret_nonce_bytes);
if (crypto_secretbox_easy(
ciphertext, plaintext.data(),
static_cast<unsigned long long>(plaintext.size()), nonce,
key.data()) != 0) {
return std::unexpected{make_security_error(
SecurityErrorCode::backend_error,
"Security::seal_secret: encryption failed")};
}
return envelope;
}
Void::Result::Result<std::vector<unsigned char>>
open_secret(std::span<const unsigned char> envelope,
const SecretKey& key)
{
if (const auto initialized = ensure_sodium(); !initialized) {
return std::unexpected{initialized.error()};
}
if (envelope.size() <
secret_nonce_bytes + secret_authentication_bytes) {
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;
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) {
wipe_bytes(plaintext);
return std::unexpected{make_security_error(
SecurityErrorCode::authentication_failed,
"Security::open_secret: authentication failed")};
}
return plaintext;
}
} // namespace Void::Security