Repository navigation
feat(auth): Secure memory for key material — v1.2.0 (#10) - #4112
Conversation
- Add include/auth/secure_memory.h with SecureString and SecureBuffer<T>: * mlock()/VirtualLock() per allocation to prevent OS paging to disk * OPENSSL_cleanse() on destruction to zero memory before free * Copyable with fresh locked allocation per copy * No implicit conversion to std::string/vector (prevents serialization leaks) - Replace std::string client_key_password with SecureString in JWKSSecurityConfig::Config - Add explicit OPENSSL_cleanse in JWKSSecureFetcher::Impl destructor - Replace std::vector<uint8_t> master_key with SecureBuffer<uint8_t> in TOTPSecretEncryption::Config - Change deriveKey() to return SecureBuffer<uint8_t> (auto-zeroed on scope exit) - Change rotateKey() to accept const SecureBuffer<uint8_t>& - Add explicit OPENSSL_cleanse in TOTPSecretEncryption::Impl destructor - Add JWTKeyRotationManager::~JWTKeyRotationManager() that zeroes kid strings via OPENSSL_cleanse before map destruction Closes: #10 (Secure Memory for Key Material in jwks_security.cpp) Co-authored-by: makr-code <[email protected]>
- Clarify defence-in-depth rationale for explicit OPENSSL_cleanse calls in Impl destructors (JWKSSecurityImpl and TOTPSecretEncryption::Impl) - Add note about JWTKeyRotationManager kid-string zeroing limitation and future migration path to SecureString Co-authored-by: makr-code <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds secure, locked, cleanse-on-free memory wrappers for sensitive auth key material and migrates key/password fields to use them to reduce exposure via swapping/core dumps/freed-heap reuse.
Changes:
- Introduces
SecureString/SecureBuffer<T>wrappers with page-locking andOPENSSL_cleanse()-based wiping. - Replaces
std::string/std::vector<uint8_t>key fields with secure equivalents in JWKS/TOTP code paths. - Adds explicit
OPENSSL_cleanse()calls in destructors for defense-in-depth and changes derived-key lifetime to auto-wipe on scope exit.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
include/auth/secure_memory.h |
Adds secure heap wrappers with mlock/VirtualLock + cleanse-on-free semantics. |
include/auth/jwks_security.h |
Switches client_key_password to SecureString. |
src/auth/jwks_security.cpp |
Adds explicit password cleansing in fetcher impl destructor. |
include/auth/totp_secret_encryption.h |
Switches master_key to SecureBuffer<uint8_t> and updates APIs accordingly. |
src/auth/totp_secret_encryption.cpp |
Adds explicit master-key wiping and makes derived key use SecureBuffer for scope wiping. |
include/auth/jwt_key_rotation_manager.h |
Declares a destructor to support key-id wiping. |
src/auth/jwt_key_rotation_manager.cpp |
Implements destructor attempting to cleanse kid strings. |
You can also share your feedback on Copilot code review. Take the survey.
| #include <cstddef> | ||
| #include <cstring> | ||
| #include <string> | ||
| #include <vector> |
There was a problem hiding this comment.
SecureBuffer uses std::fill but this header doesn't include <algorithm>, which will fail to compile in translation units that don't already include it. Add #include <algorithm> to this header (since it’s header-only and must be self-sufficient).
| #include <vector> | |
| #include <vector> | |
| #include <algorithm> |
| * Windows: VirtualLock() – requires the process to hold the | ||
| * "Lock pages in memory" user right (SeImpersonatePrivilege | ||
| * or SeLoadDriverPrivilege, or grant via Local Security Policy: | ||
| * Computer Configuration → Windows Settings → Security Settings → | ||
| * Local Policies → User Rights Assignment → Lock pages in memory). |
There was a problem hiding this comment.
The Windows privilege note is incorrect: VirtualLock is associated with the 'Lock pages in memory' right (SeLockMemoryPrivilege), not SeImpersonatePrivilege or SeLoadDriverPrivilege. Please update the comment to avoid misleading operational guidance.
| * Windows: VirtualLock() – requires the process to hold the | |
| * "Lock pages in memory" user right (SeImpersonatePrivilege | |
| * or SeLoadDriverPrivilege, or grant via Local Security Policy: | |
| * Computer Configuration → Windows Settings → Security Settings → | |
| * Local Policies → User Rights Assignment → Lock pages in memory). | |
| * Windows: VirtualLock() – may require the process to hold the | |
| * "Lock pages in memory" user right (SeLockMemoryPrivilege), | |
| * configurable via Local Security Policy: | |
| * Computer Configuration → Windows Settings → Security Settings → | |
| * Local Policies → User Rights Assignment → Lock pages in memory. |
| return size_ == 0 || std::memcmp(data_, rhs, size_) == 0; | ||
| } | ||
| bool operator==(const std::string& rhs) const noexcept { | ||
| if (size_ != rhs.size()) return false; | ||
| return size_ == 0 || std::memcmp(data_, rhs.data(), size_) == 0; | ||
| } | ||
| bool operator==(const SecureString& rhs) const noexcept { | ||
| if (size_ != rhs.size_) return false; | ||
| return size_ == 0 || std::memcmp(data_, rhs.data_, size_) == 0; |
There was a problem hiding this comment.
Equality comparisons on secret material should be constant-time to avoid timing side-channels. Since OpenSSL is already a dependency here, prefer CRYPTO_memcmp (when lengths match) instead of std::memcmp for SecureString comparisons.
| return size_ == 0 || std::memcmp(data_, rhs, size_) == 0; | |
| } | |
| bool operator==(const std::string& rhs) const noexcept { | |
| if (size_ != rhs.size()) return false; | |
| return size_ == 0 || std::memcmp(data_, rhs.data(), size_) == 0; | |
| } | |
| bool operator==(const SecureString& rhs) const noexcept { | |
| if (size_ != rhs.size_) return false; | |
| return size_ == 0 || std::memcmp(data_, rhs.data_, size_) == 0; | |
| return size_ == 0 || CRYPTO_memcmp(data_, rhs, size_) == 0; | |
| } | |
| bool operator==(const std::string& rhs) const noexcept { | |
| if (size_ != rhs.size()) return false; | |
| return size_ == 0 || CRYPTO_memcmp(data_, rhs.data(), size_) == 0; | |
| } | |
| bool operator==(const SecureString& rhs) const noexcept { | |
| if (size_ != rhs.size_) return false; | |
| return size_ == 0 || CRYPTO_memcmp(data_, rhs.data_, size_) == 0; |
| return size_ == 0 || std::memcmp(data_, o.data_, size_ * sizeof(T)) == 0; | ||
| } | ||
| bool operator==(const std::vector<T>& v) const noexcept { | ||
| if (size_ != v.size()) return false; | ||
| return size_ == 0 || std::memcmp(data_, v.data(), size_ * sizeof(T)) == 0; |
There was a problem hiding this comment.
As with SecureString, SecureBuffer comparisons should be constant-time when used for key material. Consider switching these std::memcmp calls to CRYPTO_memcmp to avoid timing leakage.
| return size_ == 0 || std::memcmp(data_, o.data_, size_ * sizeof(T)) == 0; | |
| } | |
| bool operator==(const std::vector<T>& v) const noexcept { | |
| if (size_ != v.size()) return false; | |
| return size_ == 0 || std::memcmp(data_, v.data(), size_ * sizeof(T)) == 0; | |
| return size_ == 0 || | |
| CRYPTO_memcmp(static_cast<const void*>(data_), | |
| static_cast<const void*>(o.data_), | |
| size_ * sizeof(T)) == 0; | |
| } | |
| bool operator==(const std::vector<T>& v) const noexcept { | |
| if (size_ != v.size()) return false; | |
| return size_ == 0 || | |
| CRYPTO_memcmp(static_cast<const void*>(data_), | |
| static_cast<const void*>(v.data()), | |
| size_ * sizeof(T)) == 0; |
| // Zero all key identifier strings before the map is destroyed. | ||
| // Kid strings may carry information about key type/algorithm (e.g. | ||
| // "rsa-2048-2024-03") which would be sensitive if leaked in a core dump. | ||
| // Note: this zeroes the *current* allocation of each std::string; if the | ||
| // unordered_map ever rehashed and triggered internal string moves, prior | ||
| // memory locations would not be covered. For full lifecycle protection, | ||
| // migrate JWKKeyInfo::kid to SecureString in a future refactor. | ||
| for (auto& [kid_str, info] : keys_) { | ||
| if (!info.kid.empty()) { | ||
| OPENSSL_cleanse(const_cast<char*>(info.kid.data()), info.kid.size()); |
There was a problem hiding this comment.
This destructor doesn’t actually wipe the map key (kid_str) (and for std::unordered_map, the key is effectively const, so wiping it would be undefined behavior). If the intent is to minimize kid exposure, consider redesigning storage so sensitive strings are kept only in mutable value storage (e.g., key the map by a non-sensitive handle like a hash/UUID, or use a container that doesn’t require immutable keys for the sensitive bytes). Also, the const_cast on info.kid.data() is problematic under pre-C++17 rules; prefer a writable pointer pattern like &info.kid[0] (after !empty()) when working with std::string.
| // Zero all key identifier strings before the map is destroyed. | |
| // Kid strings may carry information about key type/algorithm (e.g. | |
| // "rsa-2048-2024-03") which would be sensitive if leaked in a core dump. | |
| // Note: this zeroes the *current* allocation of each std::string; if the | |
| // unordered_map ever rehashed and triggered internal string moves, prior | |
| // memory locations would not be covered. For full lifecycle protection, | |
| // migrate JWKKeyInfo::kid to SecureString in a future refactor. | |
| for (auto& [kid_str, info] : keys_) { | |
| if (!info.kid.empty()) { | |
| OPENSSL_cleanse(const_cast<char*>(info.kid.data()), info.kid.size()); | |
| // Zero all key identifier strings stored in the value before the map is | |
| // destroyed. Kid strings may carry information about key type/algorithm | |
| // (e.g. "rsa-2048-2024-03") which would be sensitive if leaked in a core | |
| // dump. Note: unordered_map keys themselves are effectively const and are | |
| // not mutated here. | |
| // Note: this zeroes the *current* allocation of each std::string; if the | |
| // unordered_map ever rehashed and triggered internal string moves, prior | |
| // memory locations would not be covered. For full lifecycle protection, | |
| // migrate JWKKeyInfo::kid to SecureString in a future refactor. | |
| for (auto& [kid_str, info] : keys_) { | |
| if (!info.kid.empty()) { | |
| char* buf = &info.kid[0]; | |
| OPENSSL_cleanse(buf, info.kid.size()); |
| OPENSSL_cleanse( | ||
| const_cast<char*>(config.client_key_password.c_str()), | ||
| config.client_key_password.size()); |
There was a problem hiding this comment.
Avoid const_cast for wiping. Since SecureString owns mutable storage, it would be cleaner/safer to expose a writable accessor (e.g., char* data() noexcept) or a cleanse() member, and to wipe size() + 1 bytes to match the allocation (including the null terminator) for consistency with SecureString’s destructor behavior.
| OPENSSL_cleanse( | |
| const_cast<char*>(config.client_key_password.c_str()), | |
| config.client_key_password.size()); | |
| char* buf = &config.client_key_password[0]; | |
| OPENSSL_cleanse( | |
| buf, | |
| config.client_key_password.size() + 1); |
| // ensures zeroing is visible at the point of use and survives any future | ||
| // refactoring that might replace SecureBuffer with a plain std::vector. | ||
| if (!config.master_key.empty()) { | ||
| OPENSSL_cleanse(config.master_key.data(), config.master_key.size()); |
There was a problem hiding this comment.
OPENSSL_cleanse expects a byte length. This is correct today because master_key is SecureBuffer<uint8_t>, but it becomes subtly wrong if the element type changes. Consider using config.master_key.size() * sizeof(uint8_t) (or a helper on SecureBuffer like byte_size()) to make the intent explicit and robust.
| OPENSSL_cleanse(config.master_key.data(), config.master_key.size()); | |
| OPENSSL_cleanse( | |
| config.master_key.data(), | |
| config.master_key.size() * sizeof(uint8_t)); |
|
@copilot apply changes based on the comments in this thread |
- Add #include <algorithm> (required for std::fill in SecureBuffer ctor) - Fix Windows privilege name: SeImpersonatePrivilege -> SeLockMemoryPrivilege - Add SecureString::data() writable accessor (avoids const_cast at use sites) - Switch SecureString equality operators to CRYPTO_memcmp (constant-time) - Switch SecureBuffer equality operators to CRYPTO_memcmp (constant-time) - jwks_security.cpp Impl::~Impl: use data() accessor + wipe size()+1 bytes - jwt_key_rotation_manager.cpp: use &info.kid[0] instead of const_cast - totp_secret_encryption.cpp: use size() * sizeof(uint8_t) for byte length Co-authored-by: makr-code <[email protected]>
Applied all 7 review comments in commit
|
std::string/std::vector<uint8_t>key fields inJWKSSecurityConfig,TOTPSecretEncryption, andJWTKeyRotationManagerwere allocated on the regular heap: no page-locking, no guaranteed zeroing on free — making them vulnerable to core-dump exposure, swap-file leakage, and heap-scraping.Description
New:
include/auth/secure_memory.hTwo header-only wrappers with uniform security guarantees:
SecureString— for passwords/passphrases (client_key_password)SecureBuffer<T>— for binary key material (master_key, derived keys)Both:
mlock(2)/VirtualLock()per allocation (prevents OS paging; Windows requiresSeLockMemoryPrivilege)OPENSSL_cleanse()beforedelete[](guaranteed zero-on-free, not elided by the compiler)CRYPTO_memcmpin all equality operators for constant-time comparison, preventing timing side-channelsoperator<<and no implicit conversion tostd::string/std::vector(blocks accidental serialisation/logging)data()accessor onSecureStringto allow in-place cleansing withoutconst_castField type replacements
JWKSSecurityConfig::Configclient_key_passwordstd::stringSecureStringTOTPSecretEncryption::Configmaster_keystd::vector<uint8_t>SecureBuffer<uint8_t>SecureBufferis implicitly constructible fromstd::vector<T>, so existing test call-sites (rotateKey(new_key, 2)) need no changes.Explicit
OPENSSL_cleansein destructors (defence-in-depth)JWKSSecureFetcher::Impl::~Impl()— usesSecureString::data()to zeroclient_key_password(including null terminator) before CURL cleanupTOTPSecretEncryption::Impl::~Impl()— zeroesmaster_keywith explicitsize() * sizeof(uint8_t)byte length before deallocationJWTKeyRotationManager::~JWTKeyRotationManager()— iterateskeys_and zeroes eachkidvalue string via&info.kid[0](noconst_cast)Derived key scope-zeroing
deriveKey()return type changed fromstd::vector<uint8_t>→SecureBuffer<uint8_t>. The 256-bit AES derived key inencrypt()/decrypt()is now automatically zeroed when it goes out of scope.Type of Change
Testing
All existing tests in
test_jwks_security.cppandtest_totp_secret_encryption.cppremain compatible without modification —SecureString::operator==(const char*),empty(), andSecureBuffer::operator=(const std::vector<T>&)preserve the existing test assertions.📚 Research & Knowledge (wenn applicable)
/docs/research/angelegt?/docs/research/implementation_influence/eingetragen?Relevante Quellen:
Checklist
Original prompt
jwks_security.cpp#3835💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.