From 94c35d395e583b37a5b8ea40aa1efe8a6a59f5bc Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 2 Jul 2020 13:57:19 -0700 Subject: [PATCH] A bit more optimization/cleanup. --- core/Utils.cpp | 16 +++++++--------- core/Utils.hpp | 5 +++-- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/core/Utils.cpp b/core/Utils.cpp index c36ecc2a9..5ff7063fb 100644 --- a/core/Utils.cpp +++ b/core/Utils.cpp @@ -99,18 +99,16 @@ bool secureEq(const void *a, const void *b, unsigned int len) noexcept return (diff == 0); } -// Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers. -static void _Utils_doBurn(volatile uint8_t *ptr, unsigned int len) +void burn(volatile void *ptr, unsigned int len) { - for (unsigned int i = 0; i < len; ++i) - ptr[i] = 0; + Utils::zero((void *)ptr, len); + // This line is present to force the compiler not to optimize out the memory + // zeroing operation above, as burn() is used to erase secrets and other + // sensitive data. + if ((reinterpret_cast(ptr)[0] | reinterpret_cast(ptr)[len-1]) != 0) + throw BadAllocException; } -static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *, unsigned int) = _Utils_doBurn; - -void burn(void *ptr, unsigned int len) -{ (_Utils_doBurn_ptr)((volatile uint8_t *)ptr, len); } - static unsigned long _Utils_itoa(unsigned long n, char *s) { if (n == 0) diff --git a/core/Utils.hpp b/core/Utils.hpp index 46e7dcb0f..116688402 100644 --- a/core/Utils.hpp +++ b/core/Utils.hpp @@ -137,12 +137,13 @@ bool secureEq(const void *a, const void *b, unsigned int len) noexcept; /** * Be absolutely sure to zero memory * - * This uses some hacks to be totally sure the compiler does not optimize it out. + * This uses a few tricks to make sure the compiler doesn't optimize it + * out, including passing the memory as volatile. * * @param ptr Memory to zero * @param len Length of memory in bytes */ -void burn(void *ptr, unsigned int len); +void burn(volatile void *ptr, unsigned int len); /** * @param n Number to convert