From 2ce8ce65e27237471499a34906fcef1da87e0f6e Mon Sep 17 00:00:00 2001 From: SChernykh <15806605+SChernykh@users.noreply.github.com> Date: Tue, 7 Oct 2025 12:53:20 +0200 Subject: [PATCH] Util: added secure_zero_memory with type safety checks --- CMakeLists.txt | 2 ++ src/p2pool.cpp | 3 +-- src/util.cpp | 26 ++++++++++++++++++++++++++ src/util.h | 11 +++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2acda21..bb6bada 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,8 @@ option(DEV_DEBUG "[Developer only] Compile a debug build" OFF) set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT p2pool) +set(BUILD_TESTING OFF CACHE BOOL "CMake's CTest module") + if (CMAKE_CXX_COMPILER_ID MATCHES MSVC) include(cmake/msvc_libs.cmake) endif() diff --git a/src/p2pool.cpp b/src/p2pool.cpp index 0167e54..6782265 100644 --- a/src/p2pool.cpp +++ b/src/p2pool.cpp @@ -806,6 +806,7 @@ void p2pool::send_aux_job_donation() } Params::AuthorKey key; + ON_SCOPE_LEAVE([&key](){ secure_zero_memory(key); }); if (f.tellg() != static_cast(sizeof(key))) { LOGERR(1, "send_aux_job_donation: " << m_params->m_authorKeyFile << " has an invalid size"); @@ -869,8 +870,6 @@ void p2pool::send_aux_job_donation() return; } - OPENSSL_cleanse(&key, sizeof(key)); - job.insert(job.end(), signature, signature + sizeof(signature)); m_p2pServer->broadcast_aux_job_donation_async(job.data(), static_cast(job.size()), timestamp); diff --git a/src/util.cpp b/src/util.cpp index 7f1b2ba..f22b84f 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -124,6 +124,32 @@ void fixup_path(std::string& path) } } +// Tell the compiler to not optimize secure_zero_memory and hope that it listens + +#ifdef _MSC_VER +#pragma optimize("", off) +#endif + +void +#if defined(__clang__) +__attribute__((optnone)) +#elif defined(__GNUC__) +__attribute__((optimize("O0"))) +#endif +secure_zero_memory(volatile void* data, size_t size) +{ + volatile uint8_t* p = reinterpret_cast(data); + volatile uint8_t* e = reinterpret_cast(data) + size; + + while (p < e) { + *(p++) = 0; + } +} + +#ifdef _MSC_VER +#pragma optimize("", on) +#endif + const uint8_t ED25519_MASTER_PUBLIC_KEY[32] = {51,175,37,73,203,241,188,115,195,255,123,53,218,120,90,74,186,240,82,178,67,139,124,91,180,106,188,181,187,51,236,10}; std::string DATA_DIR; diff --git a/src/util.h b/src/util.h index ef5223f..e40acf6 100644 --- a/src/util.h +++ b/src/util.h @@ -386,6 +386,17 @@ std::string p2pool_version(); void fixup_path(std::string& path); +void secure_zero_memory(volatile void* data, size_t size); + +template +FORCEINLINE void secure_zero_memory(T& value) +{ + static_assert(!std::is_pointer_v, "Trying to zero a pointer instead of data it points to"); + static_assert(std::is_trivially_copyable_v, "Trying to zero a complex data type"); + + secure_zero_memory(&value, sizeof(T)); +} + } // namespace p2pool void memory_tracking_start();