85 lines
2.3 KiB
C++
85 lines
2.3 KiB
C++
#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
|