From 2a1a9f36cc638a8974b962d973195b543e00baab Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Wed, 11 Sep 2019 10:57:23 +1000 Subject: [PATCH] Use constant time comparison in MaskMac with scanStart and macStart Right shift of a negative value is undefined. Add an 'int' return version of constant time greater than equal. Change equal and not equal to be constant time in more situations. --- src/internal.c | 4 ++-- wolfcrypt/src/misc.c | 12 +++++++++--- wolfssl/wolfcrypt/misc.h | 1 + 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/internal.c b/src/internal.c index e96755cf9..c3777f335 100644 --- a/src/internal.c +++ b/src/internal.c @@ -13240,8 +13240,8 @@ static byte MaskMac(const byte* data, int sz, int macSz, byte* expMac) unsigned char started, notEnded; unsigned char good = 0; - scanStart &= (~scanStart) >> (sizeof(int) * 8 - 1); - macStart &= (~macStart) >> (sizeof(int) * 8 - 1); + scanStart &= ctMaskIntGTE(scanStart, 0); + macStart &= ctMaskIntGTE(macStart, 0); /* Div on Intel has different speeds depending on value. * Use a bitwise AND or mod a specific value (converted to mul). */ diff --git a/wolfcrypt/src/misc.c b/wolfcrypt/src/misc.c index 739bd4a3f..c4baa0563 100644 --- a/wolfcrypt/src/misc.c +++ b/wolfcrypt/src/misc.c @@ -332,6 +332,12 @@ WC_STATIC WC_INLINE byte ctMaskGTE(int a, int b) return (((word32)a - b ) >> 31) - 1; } +/* Constant time - mask set when a >= b. */ +WC_STATIC WC_INLINE int ctMaskIntGTE(int a, int b) +{ + return (((word32)a - b ) >> 31) - 1; +} + /* Constant time - mask set when a < b. */ WC_STATIC WC_INLINE byte ctMaskLT(int a, int b) { @@ -347,18 +353,18 @@ WC_STATIC WC_INLINE byte ctMaskLTE(int a, int b) /* Constant time - mask set when a == b. */ WC_STATIC WC_INLINE byte ctMaskEq(int a, int b) { - return 0 - (a == b); + return (~ctMaskGT(a, b)) & (~ctMaskLT(a, b)); } WC_STATIC WC_INLINE word16 ctMask16Eq(int a, int b) { - return 0 - (a == b); + return (~ctMaskGT(a, b)) & (~ctMaskLT(a, b)); } /* Constant time - mask set when a != b. */ WC_STATIC WC_INLINE byte ctMaskNotEq(int a, int b) { - return 0 - (a != b); + return ctMaskGT(a, b) | ctMaskLT(a, b); } /* Constant time - select a when mask is set and b otherwise. */ diff --git a/wolfssl/wolfcrypt/misc.h b/wolfssl/wolfcrypt/misc.h index ccf931137..d4dc7a18f 100644 --- a/wolfssl/wolfcrypt/misc.h +++ b/wolfssl/wolfcrypt/misc.h @@ -94,6 +94,7 @@ word32 btoi(byte b); WOLFSSL_LOCAL byte ctMaskGT(int a, int b); WOLFSSL_LOCAL byte ctMaskGTE(int a, int b); +WOLFSSL_LOCAL int ctMaskIntGTE(int a, int b); WOLFSSL_LOCAL byte ctMaskLT(int a, int b); WOLFSSL_LOCAL byte ctMaskLTE(int a, int b); WOLFSSL_LOCAL byte ctMaskEq(int a, int b);