mirror of
https://gitlab.com/chrony/chrony.git
synced 2025-12-03 18:05:06 -05:00
util: add function for constant-time memory comparison
Add a function to check if two buffers of the same length contain the same data, but do the comparison in a constant time with respect to the returned value to avoid creating a timing side channel, i.e. the time depends only on the buffer length, not on the content. Use the gnutls_memcmp() or nettle_memeql_sec() functions if available, otherwise use the same algorithm as nettle - bitwise ORing XORed data.
This commit is contained in:
25
util.c
25
util.c
@@ -29,6 +29,12 @@
|
||||
|
||||
#include "sysincl.h"
|
||||
|
||||
#if defined(HAVE_NETTLE)
|
||||
#include <nettle/memops.h>
|
||||
#elif defined(HAVE_GNUTLS)
|
||||
#include <gnutls/gnutls.h>
|
||||
#endif
|
||||
|
||||
#include "logging.h"
|
||||
#include "memory.h"
|
||||
#include "util.h"
|
||||
@@ -1648,3 +1654,22 @@ UTI_SplitString(char *string, char **words, int max_saved_words)
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
/* ================================================== */
|
||||
|
||||
int
|
||||
UTI_IsMemoryEqual(const void *s1, const void *s2, unsigned int len)
|
||||
{
|
||||
#if defined(HAVE_NETTLE)
|
||||
return nettle_memeql_sec(s1, s2, len);
|
||||
#elif defined(HAVE_GNUTLS)
|
||||
return gnutls_memcmp(s1, s2, len) == 0;
|
||||
#else
|
||||
unsigned int i, x;
|
||||
|
||||
for (i = 0, x = 0; i < len; i++)
|
||||
x |= ((const unsigned char *)s1)[i] ^ ((const unsigned char *)s2)[i];
|
||||
|
||||
return x == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user