Make HMAC comparison constant-time

This commit is contained in:
jaseg 2021-07-19 14:57:30 +02:00
parent aec38e6255
commit 34ade0d00c

View file

@ -35,6 +35,24 @@
#define MBEDTLS_CHECK(fun_call) MBEDTLS_CHECK_VAL(fun_call, CA_ERR_MBEDTLS_ERROR)
/* Constant-time memcmp because inexplicably mbedtls doesn't have one.
* See https://github.com/ARMmbed/mbedtls/issues/3040
*/
static inline int constant_time_memcmp( const void *a, const void *b, size_t n )
{
size_t i;
volatile const unsigned char *A = (volatile const unsigned char *) a;
volatile const unsigned char *B = (volatile const unsigned char *) b;
volatile unsigned char diff = 0;
for( i = 0; i < n; i++ ) {
diff |= A[i] ^ B[i];
}
return diff ;
}
static enum ca_error parse_stanza(struct ca_keystore *ks, const char *stanza_head, size_t len, unsigned char file_key[16]);
static enum ca_error parse_stanza_x25519(struct ca_keystore *ks, size_t nargs, const char **args, size_t body_len, const unsigned char *body, unsigned char file_key[16]);
static enum ca_error check_file_key(const unsigned char *buf, size_t buflen, const unsigned char file_key[16]);
@ -420,7 +438,7 @@ enum ca_error check_file_key(const unsigned char *buf, size_t buflen, const unsi
return CA_ERR_INVALID_HEADER;
}
if (memcmp(mac, hmac_calculated, 32)) {
if (constant_time_memcmp(mac, hmac_calculated, 32)) {
return CA_ERR_MAC_MISMATCH;
}