Add constant time compare to AES-CCM

Signed-off-by: Aiden Fox Ivey <aiden@aidenfoxivey.com>
This commit is contained in:
Aiden Fox Ivey 2025-06-20 16:07:23 -04:00 committed by Jonathan Bennett
parent 798b1f4d86
commit 98d010761e

View File

@ -10,6 +10,31 @@
#include "aes-ccm.h" #include "aes-ccm.h"
#if !MESHTASTIC_EXCLUDE_PKI #if !MESHTASTIC_EXCLUDE_PKI
/**
* Constant-time comparison of two byte arrays
*
* @param a First byte array to compare
* @param b Second byte array to compare
* @param len Number of bytes to compare
* @return 0 if arrays are equal, 1 if different or if inputs are invalid
*/
static int constant_time_compare(const void *a_, const void *b_, size_t len)
{
// Cast to volatile to prevent the compiler from optimizing out their comparison.
const volatile uint8_t *volatile a = (const volatile uint8_t *volatile) a_;
const volatile uint8_t *volatile b = (const volatile uint8_t *volatile) b_;
if (len == 0)
return 0;
if (a == NULL || b == NULL)
return 1;
size_t i;
volatile uint8_t d = 0U;
for (i = 0U; i < len; i++) {
d |= (a[i] ^ b[i]);
}
return (1 & ((d - 1) >> 8)) - 1;
}
static void WPA_PUT_BE16(uint8_t *a, uint16_t val) static void WPA_PUT_BE16(uint8_t *a, uint16_t val)
{ {
a[0] = val >> 8; a[0] = val >> 8;
@ -146,7 +171,7 @@ bool aes_ccm_ad(const uint8_t *key, size_t key_len, const uint8_t *nonce, size_t
aes_ccm_encr(L, crypt, crypt_len, plain, a); aes_ccm_encr(L, crypt, crypt_len, plain, a);
aes_ccm_auth_start(M, L, nonce, aad, aad_len, crypt_len, x); aes_ccm_auth_start(M, L, nonce, aad, aad_len, crypt_len, x);
aes_ccm_auth(plain, crypt_len, x); aes_ccm_auth(plain, crypt_len, x);
if (memcmp(x, t, M) != 0) { // FIXME make const comp if (constant_time_compare(x, t, M) != 0) {
return false; return false;
} }
return true; return true;