shared: add nm_utils_memeqzero_secret()

[thaller@redhat.com: the code is effectively key_is_zero() by
  <Jason@zx2c4.com> (LGPL2.1+). I took it into our source tree
  and adjusted it to our style]

(cherry picked from commit 6234e41153)
This commit is contained in:
Jason A. Donenfeld 2019-02-28 16:23:26 +01:00 committed by Thomas Haller
parent b680d64b47
commit 92b27a4f88
2 changed files with 29 additions and 0 deletions

View file

@ -17,6 +17,7 @@
* Boston, MA 02110-1301 USA.
*
* (C) Copyright 2018 Red Hat, Inc.
* (C) Copyright 2015 - 2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
*/
#include "nm-default.h"
@ -132,3 +133,29 @@ nm_secret_buf_to_gbytes_take (NMSecretBuf *secret, gssize actual_len)
_secret_buf_free,
secret);
}
/*****************************************************************************/
/**
* nm_utils_memeqzero_secret:
* @data: the data pointer to check (may be %NULL if @length is zero).
* @length: the number of bytes to check.
*
* Checks that all bytes are zero. This always takes the same amount
* of time to prevent timing attacks.
*
* Returns: whether all bytes are zero.
*/
gboolean
nm_utils_memeqzero_secret (gconstpointer data, gsize length)
{
const guint8 *const key = data;
volatile guint8 acc = 0;
gsize i;
for (i = 0; i < length; i++) {
acc |= key[i];
asm volatile("" : "=r"(acc) : "0"(acc));
}
return 1 & ((acc - 1) >> 8);
}

View file

@ -173,4 +173,6 @@ GBytes *nm_secret_buf_to_gbytes_take (NMSecretBuf *secret, gssize actual_len);
/*****************************************************************************/
gboolean nm_utils_memeqzero_secret (gconstpointer data, gsize length);
#endif /* __NM_SECRET_UTILS_H__ */