From 8075686eeeede4dfad1a312002c6889f27ea9edd Mon Sep 17 00:00:00 2001 From: Simon Rozman Date: Mon, 26 Aug 2024 15:50:33 +0200 Subject: [PATCH] memory: add sanitizing_allocator and sanitizing_blob Signed-off-by: Simon Rozman --- include/stdex/memory.hpp | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/include/stdex/memory.hpp b/include/stdex/memory.hpp index 7cd08b249..ce507150b 100644 --- a/include/stdex/memory.hpp +++ b/include/stdex/memory.hpp @@ -50,4 +50,88 @@ namespace stdex { return std::shared_ptr(p, no_delete{}); } + + // sanitizing_allocator::destroy() member generates p parameter not used warning for primitive datatypes T. + #pragma warning(push) + #pragma warning(disable: 4100) + + /// + /// An allocator template that sanitizes each memory block before it is destroyed or reallocated + /// + /// \note + /// `sanitizing_allocator` introduces a performance penalty. However, it provides an additional level of security. + /// Use for security sensitive data memory storage only. + /// + template + class sanitizing_allocator : public std::allocator + { + public: + /// + /// Convert this type to sanitizing_allocator + /// + template + struct rebind + { + typedef sanitizing_allocator other; ///< Other type + }; + + /// + /// Construct default allocator + /// + sanitizing_allocator() noexcept : std::allocator() + {} + + /// + /// Construct by copying + /// + sanitizing_allocator(_In_ const sanitizing_allocator &other) : std::allocator(other) + {} + + /// + /// Construct from a related allocator + /// + template + sanitizing_allocator(_In_ const sanitizing_allocator &other) noexcept : std::allocator(other) + {} + + /// + /// Deallocate object at p sanitizing its content first + /// + void deallocate(_In_ T* const p, _In_ const std::size_t n) + { +#ifdef _WIN32 + SecureZeroMemory(p, sizeof(T) * n); +#else + memset(p, 0, sizeof(T) * n); +#endif + std::allocator::deallocate(p, n); + } + }; + + #pragma warning(pop) + + /// + /// Sanitizing BLOB + /// + template + class sanitizing_blob + { + public: + sanitizing_blob() + { + memset(m_data, 0, N); + } + + ~sanitizing_blob() + { +#ifdef _WIN32 + SecureZeroMemory(m_data, N); +#else + memset(m_data, 0, N); +#endif + } + + public: + unsigned char m_data[N]; ///< BLOB data + }; }