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:
Miroslav Lichvar
2025-04-02 15:32:05 +02:00
parent dd8738119b
commit dab98fa8da
4 changed files with 47 additions and 1 deletions

25
util.c
View File

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