A bit more optimization/cleanup.

This commit is contained in:
Adam Ierymenko 2020-07-02 13:57:19 -07:00
parent 97cd184211
commit 94c35d395e
No known key found for this signature in database
GPG key ID: C8877CF2D7A5D7F3
2 changed files with 10 additions and 11 deletions

View file

@ -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<volatile uint8_t *>(ptr)[0] | reinterpret_cast<volatile uint8_t *>(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)

View file

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