diff --git a/CHANGES.md b/CHANGES.md index a56587f..234b421 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -6,6 +6,19 @@ oqs::version(const std::string& version)` - Returns a tuple containing the (major, minor, patch) versions - A warning is issued only if the liboqs-cpp version's major and minor numbers differ from those of liboqs, ignoring the patch version +- Made secret-key handling in `oqs::KeyEncapsulation` and `oqs::Signature` + exception-safe, see https://github.com/open-quantum-safe/liboqs-cpp/pull/29 + - A secret key passed to a constructor is cleansed if construction throws + - Copy assignment, move assignment and `generate_keypair()` cleanse the key + they replace. If copy assignment or `generate_keypair()` throws, the object + keeps its previous algorithm and key + - Moves transfer the secret key's storage instead of copying the key and + zeroing the source, so a move can no longer terminate the program by + failing to allocate + - The constructors throw `std::bad_alloc` if liboqs fails to create the + mechanism object (`OQS_KEM_new()` or `OQS_SIG_new()` returns `NULL`) + - The private data layout of both classes changed, so rebuild all code that + includes `` # Version 0.12.0 - January 15, 2025 diff --git a/include/oqs_cpp.hpp b/include/oqs_cpp.hpp index 6927967..f28abd0 100644 --- a/include/oqs_cpp.hpp +++ b/include/oqs_cpp.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -35,6 +36,22 @@ extern "C" { } } // namespace C +namespace internal { +// Guards temporary secret storage, including partially generated keys. +class SecretKeyGuard { + bytes& key_; + + public: + explicit SecretKeyGuard(bytes& key) noexcept : key_{key} {} + SecretKeyGuard(const SecretKeyGuard&) = delete; + SecretKeyGuard& operator=(const SecretKeyGuard&) = delete; + ~SecretKeyGuard() noexcept { + if (!key_.empty()) + C::OQS_MEM_cleanse(key_.data(), key_.size()); + } +}; +} // namespace internal + /** * \class oqs::MechanismNotSupportedError * \brief Cryptographic scheme not supported @@ -164,10 +181,13 @@ class KEMs final : public internal::Singleton { * \brief Key encapsulation mechanisms */ class KeyEncapsulation { - std::shared_ptr kem_{nullptr, [](C::OQS_KEM* p) { - C::OQS_KEM_free(p); - }}; ///< liboqs smart pointer to C::OQS_KEM - bytes secret_key_{}; ///< secret key + std::shared_ptr kem_{}; ///< liboqs object + + static void cleanse_secret_key(bytes& secret_key) noexcept { + if (!secret_key.empty()) + C::OQS_MEM_cleanse(secret_key.data(), secret_key.size()); + } + public: /** * \brief KEM algorithm details @@ -185,6 +205,16 @@ class KeyEncapsulation { private: KeyEncapsulationDetails alg_details_{}; ///< KEM algorithm details + // Keep secret storage last: default copying must finish all potentially + // throwing metadata copies before copying any secret bytes. + bytes secret_key_{}; ///< secret key + + void swap_state(KeyEncapsulation& other) noexcept { + kem_.swap(other.kem_); + using std::swap; + swap(alg_details_, other.alg_details_); + secret_key_.swap(other.secret_key_); + } public: /** @@ -194,7 +224,7 @@ class KeyEncapsulation { */ explicit KeyEncapsulation(const std::string& alg_name, bytes secret_key = {}) - : secret_key_{std::move(secret_key)} { + try : secret_key_{} { // KEM not enabled if (!KEMs::is_KEM_enabled(alg_name)) { // Perhaps it's supported @@ -206,6 +236,8 @@ class KeyEncapsulation { kem_.reset(C::OQS_KEM_new(alg_name.c_str()), [](C::OQS_KEM* p) { C::OQS_KEM_free(p); }); + if (!kem_) + throw std::bad_alloc{}; alg_details_.name = kem_->method_name; alg_details_.version = kem_->alg_version; @@ -215,6 +247,11 @@ class KeyEncapsulation { alg_details_.length_secret_key = kem_->length_secret_key; alg_details_.length_ciphertext = kem_->length_ciphertext; alg_details_.length_shared_secret = kem_->length_shared_secret; + + secret_key_.swap(secret_key); + } catch (...) { + cleanse_secret_key(secret_key); + throw; } /** @@ -223,51 +260,47 @@ class KeyEncapsulation { KeyEncapsulation(const KeyEncapsulation&) = default; /** - * \brief Default copy assignment operator + * \brief Copy assignment operator * \return Reference to the current instance */ - KeyEncapsulation& operator=(const KeyEncapsulation&) = default; + KeyEncapsulation& operator=(const KeyEncapsulation& rhs) { + if (this != &rhs) { + KeyEncapsulation replacement{rhs}; + swap_state(replacement); + // replacement now owns and cleanses our previous secret key. + } + return *this; + } /** - * \brief Move constructor, guarantees that the rvalue secret key is always - * zeroed - * \param rhs oqs::KeyEncapsulation instance + * \brief Move constructor; transfers key ownership without allocation. + * The source no longer owns any secret bytes after the move. + * \param rhs KeyEncapsulation instance */ KeyEncapsulation(KeyEncapsulation&& rhs) noexcept - : kem_{std::move(rhs.kem_)}, alg_details_{std::move(rhs.alg_details_)} { - // Paranoid move via copy/clean/resize, see - // https://stackoverflow.com/questions/55054187/can-i-resize-a-vector-that-was-moved-from - secret_key_ = rhs.secret_key_; // copy - // Clean (zero) - C::OQS_MEM_cleanse(rhs.secret_key_.data(), rhs.secret_key_.size()); - rhs.secret_key_.resize(0); // resize + : kem_{std::move(rhs.kem_)}, + alg_details_{std::move(rhs.alg_details_)} { + secret_key_.swap(rhs.secret_key_); } + /** - * \brief Move assignment operator, guarantees that the rvalue secret key is - * always zeroed - * \param rhs oqs::KeyEncapsulation instance + * \brief Move assignment; cleanses the replaced key and transfers ownership. + * \param rhs KeyEncapsulation instance * \return Reference to the current instance */ KeyEncapsulation& operator=(KeyEncapsulation&& rhs) noexcept { - kem_ = std::move(rhs.kem_); - alg_details_ = std::move(rhs.alg_details_); - - // Paranoid move via copy/clean/resize, see - // https://stackoverflow.com/questions/55054187/can-i-resize-a-vector-that-was-moved-from - secret_key_ = rhs.secret_key_; // copy - // Clean (zero) - C::OQS_MEM_cleanse(rhs.secret_key_.data(), rhs.secret_key_.size()); - rhs.secret_key_.resize(0); // resize - + if (this != &rhs) { + KeyEncapsulation replacement{std::move(rhs)}; + swap_state(replacement); + } return *this; } /** - * \brief Virtual default destructor + * \brief Virtual destructor; cleanses the owned secret key */ virtual ~KeyEncapsulation() { - if (!secret_key_.empty()) - C::OQS_MEM_cleanse(secret_key_.data(), secret_key_.size()); + cleanse_secret_key(secret_key_); } /** @@ -288,13 +321,16 @@ class KeyEncapsulation { */ bytes generate_keypair() { bytes public_key(alg_details_.length_public_key, 0); - secret_key_ = bytes(alg_details_.length_secret_key, 0); + bytes new_secret_key(alg_details_.length_secret_key, 0); + internal::SecretKeyGuard guard{new_secret_key}; - OQS_STATUS rv_ = C::OQS_KEM_keypair(kem_.get(), public_key.data(), - secret_key_.data()); + OQS_STATUS rv_ = C::OQS_KEM_keypair( + kem_.get(), public_key.data(), new_secret_key.data()); if (rv_ != OQS_STATUS::OQS_SUCCESS) throw std::runtime_error("Can not generate keypair"); + // Commit only after success. The guard then cleanses the old key. + secret_key_.swap(new_secret_key); return public_key; } @@ -481,10 +517,12 @@ class Sigs final : public internal::Singleton { * \brief Signature mechanisms */ class Signature { - std::shared_ptr sig_{nullptr, [](C::OQS_SIG* p) { - C::OQS_SIG_free(p); - }}; ///< liboqs smart pointer to C::OQS_SIG - bytes secret_key_{}; ///< secret key + std::shared_ptr sig_{}; ///< liboqs object + + static void cleanse_secret_key(bytes& secret_key) noexcept { + if (!secret_key.empty()) + C::OQS_MEM_cleanse(secret_key.data(), secret_key.size()); + } public: /** @@ -503,6 +541,16 @@ class Signature { private: SignatureDetails alg_details_{}; ///< Signature algorithm details + // Keep secret storage last: default copying must finish all potentially + // throwing metadata copies before copying any secret bytes. + bytes secret_key_{}; ///< secret key + + void swap_state(Signature& other) noexcept { + sig_.swap(other.sig_); + using std::swap; + swap(alg_details_, other.alg_details_); + secret_key_.swap(other.secret_key_); + } public: /** @@ -511,7 +559,7 @@ class Signature { * \param secret_key Secret key (optional) */ explicit Signature(const std::string& alg_name, bytes secret_key = {}) - : secret_key_{std::move(secret_key)} { + try : secret_key_{} { // signature not enabled if (!Sigs::is_sig_enabled(alg_name)) { // perhaps it's supported @@ -523,6 +571,8 @@ class Signature { sig_.reset(C::OQS_SIG_new(alg_name.c_str()), [](C::OQS_SIG* p) { C::OQS_SIG_free(p); }); + if (!sig_) + throw std::bad_alloc{}; alg_details_.name = sig_->method_name; alg_details_.version = sig_->alg_version; @@ -532,6 +582,11 @@ class Signature { alg_details_.length_public_key = sig_->length_public_key; alg_details_.length_secret_key = sig_->length_secret_key; alg_details_.max_length_signature = sig_->length_signature; + + secret_key_.swap(secret_key); + } catch (...) { + cleanse_secret_key(secret_key); + throw; } /** @@ -540,51 +595,47 @@ class Signature { Signature(const Signature&) = default; /** - * \brief Default copy assignment operator + * \brief Copy assignment operator * \return Reference to the current instance */ - Signature& operator=(const Signature&) = default; + Signature& operator=(const Signature& rhs) { + if (this != &rhs) { + Signature replacement{rhs}; + swap_state(replacement); + // replacement now owns and cleanses our previous secret key. + } + return *this; + } /** - * \brief Move constructor, guarantees that the rvalue secret key is always - * zeroed - * \param rhs oqs::Signature instance + * \brief Move constructor; transfers key ownership without allocation. + * The source no longer owns any secret bytes after the move. + * \param rhs Signature instance */ Signature(Signature&& rhs) noexcept - : sig_{std::move(rhs.sig_)}, alg_details_{std::move(rhs.alg_details_)} { - // Paranoid move via copy/clean/resize, see - // https://stackoverflow.com/questions/55054187/can-i-resize-a-vector-that-was-moved-from - secret_key_ = rhs.secret_key_; // copy - // Clean (zero) - C::OQS_MEM_cleanse(rhs.secret_key_.data(), rhs.secret_key_.size()); - rhs.secret_key_.resize(0); // resize + : sig_{std::move(rhs.sig_)}, + alg_details_{std::move(rhs.alg_details_)} { + secret_key_.swap(rhs.secret_key_); } + /** - * \brief Move assignment operator, guarantees that the rvalue secret key is - * always zeroed - * \param rhs oqs::Signature instance + * \brief Move assignment; cleanses the replaced key and transfers ownership. + * \param rhs Signature instance * \return Reference to the current instance */ Signature& operator=(Signature&& rhs) noexcept { - sig_ = std::move(rhs.sig_); - alg_details_ = std::move(rhs.alg_details_); - - // Paranoid move via copy/clean/resize, see - // https://stackoverflow.com/questions/55054187/can-i-resize-a-vector-that-was-moved-from - secret_key_ = rhs.secret_key_; // copy - // Clean (zero) - C::OQS_MEM_cleanse(rhs.secret_key_.data(), rhs.secret_key_.size()); - rhs.secret_key_.resize(0); // resize - + if (this != &rhs) { + Signature replacement{std::move(rhs)}; + swap_state(replacement); + } return *this; } /** - * \brief Virtual default destructor + * \brief Virtual destructor; cleanses the owned secret key */ virtual ~Signature() { - if (!secret_key_.empty()) - C::OQS_MEM_cleanse(secret_key_.data(), secret_key_.size()); + cleanse_secret_key(secret_key_); } /** @@ -604,14 +655,17 @@ class Signature { * \return Public key */ bytes generate_keypair() { - bytes public_key(get_details().length_public_key, 0); - secret_key_ = bytes(alg_details_.length_secret_key, 0); + bytes public_key(alg_details_.length_public_key, 0); + bytes new_secret_key(alg_details_.length_secret_key, 0); + internal::SecretKeyGuard guard{new_secret_key}; - OQS_STATUS rv_ = C::OQS_SIG_keypair(sig_.get(), public_key.data(), - secret_key_.data()); + OQS_STATUS rv_ = C::OQS_SIG_keypair( + sig_.get(), public_key.data(), new_secret_key.data()); if (rv_ != OQS_STATUS::OQS_SUCCESS) throw std::runtime_error("Can not generate keypair"); + // Commit only after success. The guard then cleanses the old key. + secret_key_.swap(new_secret_key); return public_key; } diff --git a/unit_tests/tests/alloc_hooks.cpp b/unit_tests/tests/alloc_hooks.cpp new file mode 100644 index 0000000..c7d10d6 --- /dev/null +++ b/unit_tests/tests/alloc_hooks.cpp @@ -0,0 +1,139 @@ +// Replacements for the global operator new and operator delete that support +// the hooks declared in alloc_hooks.hpp + +#include "alloc_hooks.hpp" + +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#elif defined(_WIN32) || defined(__linux__) +#include +#endif + +namespace { + +#if defined(__APPLE__) +constexpr bool inspection_supported = true; +std::size_t block_size(void* p) { return malloc_size(p); } +#elif defined(_WIN32) +constexpr bool inspection_supported = true; +std::size_t block_size(void* p) { return _msize(p); } +#elif defined(__linux__) +constexpr bool inspection_supported = true; +std::size_t block_size(void* p) { return malloc_usable_size(p); } +#else +constexpr bool inspection_supported = false; +std::size_t block_size(void*) { return 0; } +#endif + +// All state is constant-initialized, so it is usable during static +// initialization and destruction. +std::atomic watched_data{nullptr}; +std::atomic watched_size{0}; +std::atomic watched_found{false}; + +std::atomic counting{false}; +std::atomic counted_size{0}; +std::atomic counted{0}; + +std::atomic fail_countdown{0}; // 0 means disabled + +void inspect_before_free(void* p) noexcept { + const unsigned char* needle = watched_data.load(std::memory_order_acquire); + if (needle == nullptr) + return; + const auto* begin = static_cast(p); + const auto* end = begin + block_size(p); + const auto* needle_end = + needle + watched_size.load(std::memory_order_relaxed); + if (std::search(begin, end, needle, needle_end) != end) + watched_found.store(true, std::memory_order_relaxed); +} + +} // namespace + +namespace alloc_hooks { + +bool can_inspect_freed_blocks() { return inspection_supported; } + +FreedSecretWatch::FreedSecretWatch(const std::vector& secret) { + watched_found.store(false, std::memory_order_relaxed); + watched_size.store(secret.size(), std::memory_order_relaxed); + // An empty needle would match every block, so leave the watch disarmed. + if (!secret.empty()) + watched_data.store(secret.data(), std::memory_order_release); +} + +FreedSecretWatch::~FreedSecretWatch() { + watched_data.store(nullptr, std::memory_order_release); +} + +bool FreedSecretWatch::secret_was_freed() const { + return watched_found.load(std::memory_order_relaxed); +} + +AllocationCounter::AllocationCounter(std::size_t size) { + counted.store(0, std::memory_order_relaxed); + counted_size.store(size, std::memory_order_relaxed); + counting.store(true, std::memory_order_release); +} + +AllocationCounter::~AllocationCounter() { + counting.store(false, std::memory_order_release); +} + +std::size_t AllocationCounter::count() const { + return counted.load(std::memory_order_relaxed); +} + +AllocationFailure::AllocationFailure(std::size_t n) { + fail_countdown.store(n, std::memory_order_release); +} + +AllocationFailure::~AllocationFailure() { + fail_countdown.store(0, std::memory_order_release); +} + +} // namespace alloc_hooks + +// The other replaceable forms (array, nothrow and, where applicable, sized) +// forward to these two by default. Over-aligned forms are separate and are not +// hooked. +void* operator new(std::size_t size) { + const std::size_t remaining = + fail_countdown.load(std::memory_order_acquire); + if (remaining != 0) { + fail_countdown.store(remaining - 1, std::memory_order_release); + if (remaining == 1) + throw std::bad_alloc{}; + } + if (counting.load(std::memory_order_acquire) && + size == counted_size.load(std::memory_order_relaxed)) + counted.fetch_add(1, std::memory_order_relaxed); + + if (size == 0) + size = 1; + for (;;) { + if (void* p = std::malloc(size)) + return p; + std::new_handler handler = std::get_new_handler(); + if (handler == nullptr) + throw std::bad_alloc{}; + handler(); + } +} + +void operator delete(void* p) noexcept { + if (p == nullptr) + return; + inspect_before_free(p); + std::free(p); +} + +#if defined(__cpp_sized_deallocation) +void operator delete(void* p, std::size_t) noexcept { ::operator delete(p); } +#endif diff --git a/unit_tests/tests/alloc_hooks.hpp b/unit_tests/tests/alloc_hooks.hpp new file mode 100644 index 0000000..72d9dae --- /dev/null +++ b/unit_tests/tests/alloc_hooks.hpp @@ -0,0 +1,61 @@ +// Test-only hooks on the global allocation functions, used to check how +// oqs::KeyEncapsulation and oqs::Signature manage secret-key storage. +// +// alloc_hooks.cpp replaces the global operator new and operator delete for the +// whole unit_tests executable. When no hook is active they forward to malloc +// and free. Hooks are not thread-safe; use them only from single-threaded +// tests. At most one hook of each type may be active at a time. + +#ifndef ALLOC_HOOKS_HPP +#define ALLOC_HOOKS_HPP + +#include +#include +#include + +namespace alloc_hooks { + +/// True if freed heap blocks can be inspected on this platform, which +/// FreedSecretWatch requires. +bool can_inspect_freed_blocks(); + +/// While alive, searches each heap block released through the global operator +/// delete for a copy of the watched secret. The secret's own storage must +/// outlive the watch and must not be released while the watch is active. +class FreedSecretWatch { + public: + explicit FreedSecretWatch(const std::vector& secret); + ~FreedSecretWatch(); + FreedSecretWatch(const FreedSecretWatch&) = delete; + FreedSecretWatch& operator=(const FreedSecretWatch&) = delete; + + /// True if a released block still held the secret, i.e., it was freed + /// without being cleansed. + bool secret_was_freed() const; +}; + +/// While alive, counts calls to the global operator new for exactly `size` +/// bytes. +class AllocationCounter { + public: + explicit AllocationCounter(std::size_t size); + ~AllocationCounter(); + AllocationCounter(const AllocationCounter&) = delete; + AllocationCounter& operator=(const AllocationCounter&) = delete; + + std::size_t count() const; +}; + +/// While alive, makes the n-th following call to the global operator new +/// (counting from 1) throw std::bad_alloc. +class AllocationFailure { + public: + explicit AllocationFailure(std::size_t n); + ~AllocationFailure(); + AllocationFailure(const AllocationFailure&) = delete; + AllocationFailure& operator=(const AllocationFailure&) = delete; +}; + +} // namespace alloc_hooks + +#endif // ALLOC_HOOKS_HPP diff --git a/unit_tests/tests/test_kem.cpp b/unit_tests/tests/test_kem.cpp index 4b3c028..65e0801 100644 --- a/unit_tests/tests/test_kem.cpp +++ b/unit_tests/tests/test_kem.cpp @@ -1,9 +1,13 @@ // Unit testing oqs::KeyEncapsulation +#include #include #include +#include +#include #include #include +#include #include #include @@ -11,6 +15,8 @@ #include "oqs_cpp.hpp" #include "rand/rand.hpp" +#include "alloc_hooks.hpp" + // no_thread_KEM_patterns lists KEM patterns that have issues running in a // separate thread static std::vector no_thread_KEM_patterns{"Classic-McEliece", @@ -132,3 +138,264 @@ TEST(oqs_KeyEncapsulation, NotSupported) { EXPECT_THROW(oqs::KeyEncapsulation{"unsupported_kem"}, oqs::MechanismNotSupportedError); } + +namespace { +// Exported key copies belong to the caller. Clean up these test-owned copies, +// including when an assertion returns early or an operation throws. +class TestSecret { + oqs::bytes value_; + + public: + explicit TestSecret(oqs::bytes value) noexcept { + value_.swap(value); + } + TestSecret(const TestSecret&) = delete; + TestSecret& operator=(const TestSecret&) = delete; + ~TestSecret() { + if (!value_.empty()) + oqs::C::OQS_MEM_cleanse(value_.data(), value_.size()); + } + const oqs::bytes& get() const { return value_; } +}; +} // namespace + +namespace { +void expect_kem_key_works(const oqs::KeyEncapsulation& key, + const oqs::bytes& public_key) { + oqs::KeyEncapsulation peer{key.get_details().name}; + auto encapsulated = peer.encap_secret(public_key); + TestSecret expected{std::move(encapsulated.second)}; + TestSecret actual{key.decap_secret(encapsulated.first)}; + EXPECT_EQ(actual.get(), expected.get()); +} +} // namespace + +namespace { +// Returns the KEM for the secret-key tests: ML-KEM-768 if enabled (it is fast +// and standard), otherwise the first enabled KEM, or "" if none is enabled. +std::string kem_for_secret_key_tests() { + const auto& enabled = oqs::KEMs::get_enabled_KEMs(); + if (enabled.empty()) + return {}; + const auto preferred = + std::find(enabled.begin(), enabled.end(), "ML-KEM-768"); + return preferred != enabled.end() ? *preferred : enabled.front(); +} +} // namespace + +TEST(oqs_KeyEncapsulation, FailedConstructionCleansesSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + + // The constructor takes its own copy of the key, which it must cleanse + // before releasing when it throws. + const TestSecret key{oqs::rand::randombytes(64)}; + alloc_hooks::FreedSecretWatch watch{key.get()}; + EXPECT_THROW((oqs::KeyEncapsulation{"unsupported_kem", key.get()}), + oqs::MechanismNotSupportedError); + EXPECT_FALSE(watch.secret_was_freed()); +} + +TEST(oqs_KeyEncapsulation, SecretKeyLifecycle) { + const auto& enabled = oqs::KEMs::get_enabled_KEMs(); + if (enabled.empty()) + GTEST_SKIP() << "No enabled KEM algorithms"; + + // Prefer a fast standard algorithm for repeated lifecycle operations. + // Run this test on the main thread, including the fallback algorithm. + const auto preferred = std::find(enabled.begin(), enabled.end(), + "ML-KEM-768"); + const auto& alg = preferred != enabled.end() ? *preferred : enabled.front(); + SCOPED_TRACE(alg); + + oqs::KeyEncapsulation source{alg}; + const auto public_key = source.generate_keypair(); + const TestSecret original_key{source.export_secret_key()}; + ASSERT_EQ(original_key.get().size(), source.get_details().length_secret_key); + + // Copy construction preserves the source and yields a usable key. + oqs::KeyEncapsulation copied{source}; + EXPECT_EQ(TestSecret{copied.export_secret_key()}.get(), original_key.get()); + expect_kem_key_works(copied, public_key); + + // Exercise replacement across algorithms when the alternative is enabled. + const auto alternative = std::find(enabled.begin(), enabled.end(), + "ML-KEM-512"); + const auto& target_alg = alternative != enabled.end() ? *alternative : alg; + oqs::KeyEncapsulation target{target_alg}; + target.generate_keypair(); + target = source; + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + EXPECT_EQ(target.get_details().name, source.get_details().name); + expect_kem_key_works(target, public_key); + + // Use an alias to exercise self-assignment without self-move warnings. + auto& same_target = target; + target = same_target; + target = std::move(same_target); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + expect_kem_key_works(target, public_key); + + oqs::KeyEncapsulation moved{std::move(copied)}; + EXPECT_TRUE(TestSecret{copied.export_secret_key()}.get().empty()); + EXPECT_EQ(TestSecret{moved.export_secret_key()}.get(), original_key.get()); + expect_kem_key_works(moved, public_key); + + // Replace a different, already initialized key via move assignment. + target = oqs::KeyEncapsulation{target_alg}; + target.generate_keypair(); + target = std::move(moved); + EXPECT_TRUE(TestSecret{moved.export_secret_key()}.get().empty()); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + expect_kem_key_works(target, public_key); + + const auto regenerated_public_key = target.generate_keypair(); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get().size(), + target.get_details().length_secret_key); + expect_kem_key_works(target, regenerated_public_key); + + // Regenerating the destination must not change the source's copied key. + EXPECT_EQ(TestSecret{source.export_secret_key()}.get(), original_key.get()); + expect_kem_key_works(source, public_key); + + // Moved-from wrappers remain assignable. + copied = source; + expect_kem_key_works(copied, public_key); +} + +TEST(oqs_KeyEncapsulation, EmptySecretKeyAssignment) { + const auto& enabled = oqs::KEMs::get_enabled_KEMs(); + if (enabled.empty()) + GTEST_SKIP() << "No enabled KEM algorithms"; + const auto preferred = std::find(enabled.begin(), enabled.end(), + "ML-KEM-768"); + const auto& alg = preferred != enabled.end() ? *preferred : enabled.front(); + SCOPED_TRACE(alg); + + oqs::KeyEncapsulation empty{alg}; + oqs::KeyEncapsulation copied_empty{empty}; + EXPECT_TRUE(TestSecret{copied_empty.export_secret_key()}.get().empty()); + + oqs::KeyEncapsulation target{alg}; + target.generate_keypair(); + target = empty; + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get().empty()); + EXPECT_EQ(target.get_details().name, alg); + + target.generate_keypair(); + target = std::move(copied_empty); + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get().empty()); + EXPECT_TRUE(TestSecret{copied_empty.export_secret_key()}.get().empty()); + const auto public_key = target.generate_keypair(); + expect_kem_key_works(target, public_key); +} + +TEST(oqs_KeyEncapsulation, RegeneratingCleansesReplacedSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + const std::string alg = kem_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled KEM algorithms"; + SCOPED_TRACE(alg); + + oqs::KeyEncapsulation kem{alg}; + kem.generate_keypair(); + const TestSecret old_key{kem.export_secret_key()}; + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + kem.generate_keypair(); + EXPECT_FALSE(watch.secret_was_freed()); +} + +TEST(oqs_KeyEncapsulation, AssignmentCleansesReplacedSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + const std::string alg = kem_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled KEM algorithms"; + SCOPED_TRACE(alg); + + oqs::KeyEncapsulation keyed{alg}; + keyed.generate_keypair(); + const TestSecret old_key{keyed.export_secret_key()}; + const oqs::KeyEncapsulation empty{alg}; + + // Assigning from a wrapper without a key leaves the old key nothing to be + // overwritten by. Destroy the target inside the watch, so that storage + // released after the assignment is also inspected. + { + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + { + oqs::KeyEncapsulation target{alg, old_key.get()}; + target = empty; + } + EXPECT_FALSE(watch.secret_was_freed()) << "copy assignment"; + } + { + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + { + oqs::KeyEncapsulation target{alg, old_key.get()}; + target = oqs::KeyEncapsulation{alg}; + } + EXPECT_FALSE(watch.secret_was_freed()) << "move assignment"; + } +} + +TEST(oqs_KeyEncapsulation, MovesDoNotCopySecretKey) { + const std::string alg = kem_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled KEM algorithms"; + SCOPED_TRACE(alg); + + oqs::KeyEncapsulation source{alg}; + source.generate_keypair(); + oqs::KeyEncapsulation target{alg}; + + // Moves are noexcept, so copying the key there would terminate the + // process if the allocation failed. + alloc_hooks::AllocationCounter key_allocations{ + source.get_details().length_secret_key}; + oqs::KeyEncapsulation moved{std::move(source)}; + EXPECT_EQ(key_allocations.count(), 0u) << "move construction"; + target = std::move(moved); + EXPECT_EQ(key_allocations.count(), 0u) << "move assignment"; +} + +TEST(oqs_KeyEncapsulation, FailedCopyAssignmentKeepsDestination) { + // The source key is larger than the destination's, so copying it always + // allocates, even if the destination's storage were reused. + const std::string small_alg = "ML-KEM-512"; + const std::string large_alg = "ML-KEM-768"; + if (!oqs::KEMs::is_KEM_enabled(small_alg) || + !oqs::KEMs::is_KEM_enabled(large_alg)) + GTEST_SKIP() << small_alg << " and " << large_alg + << " must both be enabled"; + + oqs::KeyEncapsulation target{small_alg}; + target.generate_keypair(); + const TestSecret target_key{target.export_secret_key()}; + oqs::KeyEncapsulation source{large_alg}; + source.generate_keypair(); + + // Fail each allocation made by the assignment in turn, until it succeeds. + std::size_t failures = 0; + for (std::size_t n = 1; n <= 100; ++n) { + bool threw = false; + { + alloc_hooks::AllocationFailure fail{n}; + try { + target = source; + } catch (const std::bad_alloc&) { + threw = true; + } + } + if (!threw) + break; + ++failures; + EXPECT_EQ(target.get_details().name, small_alg) << "allocation " << n; + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get() == + target_key.get()) + << "allocation " << n; + } + EXPECT_GT(failures, 0u); + EXPECT_EQ(target.get_details().name, large_alg); +} diff --git a/unit_tests/tests/test_sig.cpp b/unit_tests/tests/test_sig.cpp index 966587c..1b2cb93 100644 --- a/unit_tests/tests/test_sig.cpp +++ b/unit_tests/tests/test_sig.cpp @@ -1,8 +1,12 @@ // Unit testing oqs::Signature +#include #include #include +#include +#include #include +#include #include #include @@ -10,6 +14,8 @@ #include "oqs_cpp.hpp" #include "rand/rand.hpp" +#include "alloc_hooks.hpp" + // no_thread_sig_patterns lists sig patterns that have issues running in a // separate thread static std::vector no_thread_sig_patterns{ @@ -247,3 +253,263 @@ TEST(oqs_Signature, NotSupported) { EXPECT_THROW(oqs::Signature{"unsupported_sig"}, oqs::MechanismNotSupportedError); } + +namespace { +// Exported key copies belong to the caller. Clean up these test-owned copies, +// including when an assertion returns early or an operation throws. +class TestSecret { + oqs::bytes value_; + + public: + explicit TestSecret(oqs::bytes value) noexcept { + value_.swap(value); + } + TestSecret(const TestSecret&) = delete; + TestSecret& operator=(const TestSecret&) = delete; + ~TestSecret() { + if (!value_.empty()) + oqs::C::OQS_MEM_cleanse(value_.data(), value_.size()); + } + const oqs::bytes& get() const { return value_; } +}; +} // namespace + +namespace { +void expect_sig_key_works(const oqs::Signature& key, + const oqs::bytes& public_key) { + const auto message = test_message(key.get_details().name); + const auto signature = key.sign(message); + oqs::Signature verifier{key.get_details().name}; + EXPECT_TRUE(verifier.verify(message, signature, public_key)); +} +} // namespace + +namespace { +// Returns the signature for the secret-key tests: ML-DSA-65 if enabled (it is +// fast and standard), otherwise the first enabled one, or "" if none is. +std::string sig_for_secret_key_tests() { + const auto& enabled = oqs::Sigs::get_enabled_sigs(); + if (enabled.empty()) + return {}; + const auto preferred = + std::find(enabled.begin(), enabled.end(), "ML-DSA-65"); + return preferred != enabled.end() ? *preferred : enabled.front(); +} +} // namespace + +TEST(oqs_Signature, FailedConstructionCleansesSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + + // The constructor takes its own copy of the key, which it must cleanse + // before releasing when it throws. + const TestSecret key{oqs::rand::randombytes(64)}; + alloc_hooks::FreedSecretWatch watch{key.get()}; + EXPECT_THROW((oqs::Signature{"unsupported_sig", key.get()}), + oqs::MechanismNotSupportedError); + EXPECT_FALSE(watch.secret_was_freed()); +} + +TEST(oqs_Signature, SecretKeyLifecycle) { + const auto& enabled = oqs::Sigs::get_enabled_sigs(); + if (enabled.empty()) + GTEST_SKIP() << "No enabled signature algorithms"; + + // Prefer a fast standard algorithm for repeated lifecycle operations. + // Run this test on the main thread, including the fallback algorithm. + const auto preferred = std::find(enabled.begin(), enabled.end(), + "ML-DSA-65"); + const auto& alg = preferred != enabled.end() ? *preferred : enabled.front(); + SCOPED_TRACE(alg); + + oqs::Signature source{alg}; + const auto public_key = source.generate_keypair(); + const TestSecret original_key{source.export_secret_key()}; + ASSERT_EQ(original_key.get().size(), source.get_details().length_secret_key); + + // Copy construction preserves the source and yields a usable key. + oqs::Signature copied{source}; + EXPECT_EQ(TestSecret{copied.export_secret_key()}.get(), original_key.get()); + expect_sig_key_works(copied, public_key); + + // Exercise replacement across algorithms when the alternative is enabled. + const auto alternative = std::find(enabled.begin(), enabled.end(), + "ML-DSA-44"); + const auto& target_alg = alternative != enabled.end() ? *alternative : alg; + oqs::Signature target{target_alg}; + target.generate_keypair(); + target = source; + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + EXPECT_EQ(target.get_details().name, source.get_details().name); + expect_sig_key_works(target, public_key); + + // Use an alias to exercise self-assignment without self-move warnings. + auto& same_target = target; + target = same_target; + target = std::move(same_target); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + expect_sig_key_works(target, public_key); + + oqs::Signature moved{std::move(copied)}; + EXPECT_TRUE(TestSecret{copied.export_secret_key()}.get().empty()); + EXPECT_EQ(TestSecret{moved.export_secret_key()}.get(), original_key.get()); + expect_sig_key_works(moved, public_key); + + // Replace a different, already initialized key via move assignment. + target = oqs::Signature{target_alg}; + target.generate_keypair(); + target = std::move(moved); + EXPECT_TRUE(TestSecret{moved.export_secret_key()}.get().empty()); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get(), original_key.get()); + expect_sig_key_works(target, public_key); + + const auto regenerated_public_key = target.generate_keypair(); + EXPECT_EQ(TestSecret{target.export_secret_key()}.get().size(), + target.get_details().length_secret_key); + expect_sig_key_works(target, regenerated_public_key); + + // Regenerating the destination must not change the source's copied key. + EXPECT_EQ(TestSecret{source.export_secret_key()}.get(), original_key.get()); + expect_sig_key_works(source, public_key); + + // Moved-from wrappers remain assignable. + copied = source; + expect_sig_key_works(copied, public_key); +} + +TEST(oqs_Signature, EmptySecretKeyAssignment) { + const auto& enabled = oqs::Sigs::get_enabled_sigs(); + if (enabled.empty()) + GTEST_SKIP() << "No enabled signature algorithms"; + const auto preferred = std::find(enabled.begin(), enabled.end(), + "ML-DSA-65"); + const auto& alg = preferred != enabled.end() ? *preferred : enabled.front(); + SCOPED_TRACE(alg); + + oqs::Signature empty{alg}; + oqs::Signature copied_empty{empty}; + EXPECT_TRUE(TestSecret{copied_empty.export_secret_key()}.get().empty()); + + oqs::Signature target{alg}; + target.generate_keypair(); + target = empty; + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get().empty()); + EXPECT_EQ(target.get_details().name, alg); + + target.generate_keypair(); + target = std::move(copied_empty); + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get().empty()); + EXPECT_TRUE(TestSecret{copied_empty.export_secret_key()}.get().empty()); + const auto public_key = target.generate_keypair(); + expect_sig_key_works(target, public_key); +} + +TEST(oqs_Signature, RegeneratingCleansesReplacedSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + const std::string alg = sig_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled signature algorithms"; + SCOPED_TRACE(alg); + + oqs::Signature sig{alg}; + sig.generate_keypair(); + const TestSecret old_key{sig.export_secret_key()}; + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + sig.generate_keypair(); + EXPECT_FALSE(watch.secret_was_freed()); +} + +TEST(oqs_Signature, AssignmentCleansesReplacedSecretKey) { + if (!alloc_hooks::can_inspect_freed_blocks()) + GTEST_SKIP() << "Freed heap blocks cannot be inspected here"; + const std::string alg = sig_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled signature algorithms"; + SCOPED_TRACE(alg); + + oqs::Signature keyed{alg}; + keyed.generate_keypair(); + const TestSecret old_key{keyed.export_secret_key()}; + const oqs::Signature empty{alg}; + + // Assigning from a wrapper without a key leaves the old key nothing to be + // overwritten by. Destroy the target inside the watch, so that storage + // released after the assignment is also inspected. + { + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + { + oqs::Signature target{alg, old_key.get()}; + target = empty; + } + EXPECT_FALSE(watch.secret_was_freed()) << "copy assignment"; + } + { + alloc_hooks::FreedSecretWatch watch{old_key.get()}; + { + oqs::Signature target{alg, old_key.get()}; + target = oqs::Signature{alg}; + } + EXPECT_FALSE(watch.secret_was_freed()) << "move assignment"; + } +} + +TEST(oqs_Signature, MovesDoNotCopySecretKey) { + const std::string alg = sig_for_secret_key_tests(); + if (alg.empty()) + GTEST_SKIP() << "No enabled signature algorithms"; + SCOPED_TRACE(alg); + + oqs::Signature source{alg}; + source.generate_keypair(); + oqs::Signature target{alg}; + + // Moves are noexcept, so copying the key there would terminate the + // process if the allocation failed. + alloc_hooks::AllocationCounter key_allocations{ + source.get_details().length_secret_key}; + oqs::Signature moved{std::move(source)}; + EXPECT_EQ(key_allocations.count(), 0u) << "move construction"; + target = std::move(moved); + EXPECT_EQ(key_allocations.count(), 0u) << "move assignment"; +} + +TEST(oqs_Signature, FailedCopyAssignmentKeepsDestination) { + // The source key is larger than the destination's, so copying it always + // allocates, even if the destination's storage were reused. + const std::string small_alg = "ML-DSA-44"; + const std::string large_alg = "ML-DSA-65"; + if (!oqs::Sigs::is_sig_enabled(small_alg) || + !oqs::Sigs::is_sig_enabled(large_alg)) + GTEST_SKIP() << small_alg << " and " << large_alg + << " must both be enabled"; + + oqs::Signature target{small_alg}; + target.generate_keypair(); + const TestSecret target_key{target.export_secret_key()}; + oqs::Signature source{large_alg}; + source.generate_keypair(); + + // Fail each allocation made by the assignment in turn, until it succeeds. + std::size_t failures = 0; + for (std::size_t n = 1; n <= 100; ++n) { + bool threw = false; + { + alloc_hooks::AllocationFailure fail{n}; + try { + target = source; + } catch (const std::bad_alloc&) { + threw = true; + } + } + if (!threw) + break; + ++failures; + EXPECT_EQ(target.get_details().name, small_alg) << "allocation " << n; + EXPECT_TRUE(TestSecret{target.export_secret_key()}.get() == + target_key.get()) + << "allocation " << n; + } + EXPECT_GT(failures, 0u); + EXPECT_EQ(target.get_details().name, large_alg); +}