Constant time comparison for mac

This commit is contained in:
Mark Haines 2015-03-03 15:08:56 +00:00
parent 2f2e0340ae
commit 8123ce6209
3 changed files with 27 additions and 6 deletions

View file

@ -1,17 +1,24 @@
#include <cstddef> #include <cstddef>
#include <cstdint>
namespace axolotl { namespace axolotl {
/** Clear the memory held in the buffer */ /** Clear the memory held in the buffer */
void unset( void unset(
volatile void * buffer, std::size_t buffer_length void volatile * buffer, std::size_t buffer_length
); );
/** Clear the memory backing an object */ /** Clear the memory backing an object */
template<typename T> template<typename T>
void unset(T & value) { void unset(T & value) {
unset(reinterpret_cast<volatile void *>(&value), sizeof(T)); unset(reinterpret_cast<void volatile *>(&value), sizeof(T));
} }
/** Check if two buffers are equal in constant time. */
bool is_equal(
std::uint8_t const * buffer_a,
std::uint8_t const * buffer_b,
std::size_t length
);
} // namespace axolotl } // namespace axolotl

View file

@ -1,11 +1,25 @@
#include "axolotl/memory.hh" #include "axolotl/memory.hh"
void axolotl::unset( void axolotl::unset(
volatile void * buffer, std::size_t buffer_length void volatile * buffer, std::size_t buffer_length
) { ) {
volatile char * pos = reinterpret_cast<volatile char *>(buffer); char volatile * pos = reinterpret_cast<char volatile *>(buffer);
volatile char * end = pos + buffer_length; char volatile * end = pos + buffer_length;
while (pos != end) { while (pos != end) {
*(pos++) = 0; *(pos++) = 0;
} }
} }
bool axolotl::is_equal(
std::uint8_t const * buffer_a,
std::uint8_t const * buffer_b,
std::size_t length
) {
std::uint8_t volatile result = 0;
while (length--) {
result |= (*(buffer_a++)) ^ (*(buffer_b++));
}
return result == 0;
}

View file

@ -104,7 +104,7 @@ bool verify_mac(
mac mac
); );
bool result = std::memcmp(mac, reader.mac, MAC_LENGTH) == 0; bool result = axolotl::is_equal(mac, reader.mac, MAC_LENGTH);
axolotl::unset(mac); axolotl::unset(mac);
return result; return result;
} }