Skip to content

feat(auth): Secure memory for key material — v1.2.0 (#10) - #4112

Merged
makr-code merged 4 commits into
developfrom
copilot/secure-memory-key-material
Mar 12, 2026
Merged

makr-code merged 4 commits into
developfrom
copilot/secure-memory-key-material

Conversation

Copilot AI commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

std::string/std::vector<uint8_t> key fields in JWKSSecurityConfig, TOTPSecretEncryption, and JWTKeyRotationManager were 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.h

Two 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:

  • call mlock(2) / VirtualLock() per allocation (prevents OS paging; Windows requires SeLockMemoryPrivilege)
  • call OPENSSL_cleanse() before delete[] (guaranteed zero-on-free, not elided by the compiler)
  • use CRYPTO_memcmp in all equality operators for constant-time comparison, preventing timing side-channels
  • have no operator<< and no implicit conversion to std::string/std::vector (blocks accidental serialisation/logging)
  • are copyable (each copy gets its own locked allocation)
  • expose a writable data() accessor on SecureString to allow in-place cleansing without const_cast

Field type replacements

Location Field Before After
JWKSSecurityConfig::Config client_key_password std::string SecureString
TOTPSecretEncryption::Config master_key std::vector<uint8_t> SecureBuffer<uint8_t>

SecureBuffer is implicitly constructible from std::vector<T>, so existing test call-sites (rotateKey(new_key, 2)) need no changes.

Explicit OPENSSL_cleanse in destructors (defence-in-depth)

  • JWKSSecureFetcher::Impl::~Impl() — uses SecureString::data() to zero client_key_password (including null terminator) before CURL cleanup
  • TOTPSecretEncryption::Impl::~Impl() — zeroes master_key with explicit size() * sizeof(uint8_t) byte length before deallocation
  • JWTKeyRotationManager::~JWTKeyRotationManager() — iterates keys_ and zeroes each kid value string via &info.kid[0] (no const_cast)

Derived key scope-zeroing

deriveKey() return type changed from std::vector<uint8_t> → SecureBuffer<uint8_t>. The 256-bit AES derived key in encrypt()/decrypt() is now automatically zeroed when it goes out of scope.

// Before: derived key lingers in heap until allocator reuse
std::vector<uint8_t> derived_key = deriveKey(salt);

// After: zeroed + unlocked when scope exits
SecureBuffer<uint8_t> derived_key = deriveKey(salt);  // ~SecureBuffer → OPENSSL_cleanse + munlock

Type of Change

  • Bug fix
  • New feature
  • Refactoring
  • Documentation
  • Other:

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

All existing tests in test_jwks_security.cpp and test_totp_secret_encryption.cpp remain compatible without modification — SecureString::operator==(const char*), empty(), and SecureBuffer::operator=(const std::vector<T>&) preserve the existing test assertions.

📚 Research & Knowledge (wenn applicable)

  • Diese PR basiert auf wissenschaftlichen Paper(s) oder Best Practices?
    • Falls JA: Research-Dateien in /docs/research/ angelegt?
    • Falls JA: Im Modul-README unter "Wissenschaftliche Grundlagen" verlinkt?
    • Falls JA: In /docs/research/implementation_influence/ eingetragen?

Relevante Quellen:

  • Paper:
  • Best Practice:
  • Architecture Decision:

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No new warnings introduced
Original prompt

This section details on the original issue you should resolve

<issue_title>Secure Memory for Key Material in jwks_security.cpp</issue_title>
<issue_description>### Context

This issue implements the roadmap item 'Secure Memory for Key Material in jwks_security.cpp' for the auth domain. It is sourced from the consolidated roadmap under 🟠 High Priority — Immediate (≤ v1.4.0) and targets milestone v1.2.0.

Primary detail section: 10. Secure Memory for Key Material in jwks_security.cpp

Goal

Deliver the scoped changes for Secure Memory for Key Material in jwks_security.cpp in src/auth/ and complete the linked detail section in a release-ready state for v1.2.0.

Detailed Scope

10. Secure Memory for Key Material in jwks_security.cpp

Priority: High (Security)
Target Version: v1.2.0

jwks_security.cpp:276 passes impl_->config.client_key_password as a plain std::string to CURLOPT_KEYPASSWD. std::string stores content in allocator-managed heap memory that may be swapped to disk, appear in core dumps, or be left in freed pages readable by a later allocation. Similarly, private key bytes loaded into memory in jwt_key_rotation_manager.cpp and totp_secret_encryption.cpp are held in plain std::string or std::vector<uint8_t>.

Implementation Notes:

  • [ ] Introduce SecureString wrapper (or use sodium_malloc / sodium_mlock from libsodium) for all password and private-key fields in JWKSSecurityConfig (include/auth/jwks_security.h) and TOTPSecretEncryption (include/auth/totp_secret_encryption.h)
  • [ ] Call OPENSSL_cleanse() (or sodium_memzero()) on key buffers in destructors of JWKSSecurityImpl, JWTKeyRotationManager, and TOTPSecretEncryption before freeing memory
  • [ ] Ensure mlockall(MCL_CURRENT) or per-allocation mlock() is called for pages holding key material on Linux; document Windows equivalent (VirtualLock)
  • [ ] Remove client_key_password from any struct that may be serialised, logged, or copied by value

Acceptance Criteria

  • Introduce SecureString wrapper (or use sodium_malloc / sodium_mlock from libsodium) for all password and private-key fields in JWKSSecurityConfig (include/auth/jwks_security.h) and TOTPSecretEncryption (include/auth/totp_secret_encryption.h)
  • Call OPENSSL_cleanse() (or sodium_memzero()) on key buffers in destructors of JWKSSecurityImpl, JWTKeyRotationManager, and TOTPSecretEncryption before freeing memory
  • Ensure mlockall(MCL_CURRENT) or per-allocation mlock() is called for pages holding key material on Linux; document Windows equivalent (VirtualLock)
  • Remove client_key_password from any struct that may be serialised, logged, or copied by value

Relationships

References

  • src/ROADMAP.md
  • src/auth/FUTURE_ENHANCEMENTS.md#10-secure-memory-for-key-material-in-jwks_securitycpp
  • Source key: roadmap:7:auth:v1.2.0:10-secure-memory-for-key-material-in-jwks-securitycpp

Generated from the consolidated source roadmap. Keep the roadmap and issue in sync when scope changes.

</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 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.

Copilot AI and others added 2 commits March 12, 2026 14:56
- 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]>
Copilot AI changed the title [WIP] Implement secure memory for key material in jwks_security.cpp feat(auth): Secure memory for key material — v1.2.0 (#10) Mar 12, 2026
@makr-code
makr-code marked this pull request as ready for review March 12, 2026 15:18
@makr-code
makr-code requested review from Copilot and makr-code March 12, 2026 15:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 and OPENSSL_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>

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Suggested change
#include <vector>
#include <vector>
#include <algorithm>

Copilot uses AI. Check for mistakes.
Comment thread include/auth/secure_memory.h Outdated
Comment on lines +39 to +43
* 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).

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
* 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.

Copilot uses AI. Check for mistakes.
Comment thread include/auth/secure_memory.h Outdated
Comment on lines +165 to +173
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;

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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;

Copilot uses AI. Check for mistakes.
Comment thread include/auth/secure_memory.h Outdated
Comment on lines +282 to +286
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;

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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;

Copilot uses AI. Check for mistakes.
Comment thread src/auth/jwt_key_rotation_manager.cpp Outdated
Comment on lines +41 to +50
// 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());

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
// 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());

Copilot uses AI. Check for mistakes.
Comment thread src/auth/jwks_security.cpp Outdated
Comment on lines +205 to +207
OPENSSL_cleanse(
const_cast<char*>(config.client_key_password.c_str()),
config.client_key_password.size());

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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);

Copilot uses AI. Check for mistakes.
Comment thread src/auth/totp_secret_encryption.cpp Outdated
// 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());

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
OPENSSL_cleanse(config.master_key.data(), config.master_key.size());
OPENSSL_cleanse(
config.master_key.data(),
config.master_key.size() * sizeof(uint8_t));

Copilot uses AI. Check for mistakes.
@makr-code

Copy link
Copy Markdown
Owner

@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]>

Copilot AI commented Mar 12, 2026

Copy link
Copy Markdown
Contributor Author

@copilot apply changes based on the comments in this thread

Applied all 7 review comments in commit 6be7ad5:

  • secure_memory.h: Added #include <algorithm>; corrected Windows privilege name to SeLockMemoryPrivilege; added SecureString::data() writable accessor; switched all equality operators in both SecureString and SecureBuffer to CRYPTO_memcmp for constant-time comparisons.
  • jwks_security.cpp: Replaced const_cast<char*>(c_str()) with data() accessor; wiping size() + 1 bytes to cover the null terminator consistently with the destructor.
  • jwt_key_rotation_manager.cpp: Replaced const_cast<char*>(info.kid.data()) with &info.kid[0].
  • totp_secret_encryption.cpp: Changed to size() * sizeof(uint8_t) for explicit byte-length clarity.

@makr-code
makr-code merged commit be8cb9e into develop Mar 12, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Secure Memory for Key Material in jwks_security.cpp

3 participants