From 34ade0d00c2a2de8b01fca47de5575bdfac044de Mon Sep 17 00:00:00 2001 From: jaseg Date: Mon, 19 Jul 2021 14:57:30 +0200 Subject: [PATCH] Make HMAC comparison constant-time --- demo/fw/src/cage.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/demo/fw/src/cage.c b/demo/fw/src/cage.c index a741298..f8125e0 100644 --- a/demo/fw/src/cage.c +++ b/demo/fw/src/cage.c @@ -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; }