From cc94573e9b29fbaf229700cfc9258b02e4219c75 Mon Sep 17 00:00:00 2001 From: "Collin B. Stuart" Date: Tue, 13 Feb 2018 16:44:47 -0500 Subject: [PATCH] Constant time compare - fix case when second part of the && conditional is skipped when data is not equal - isEqual variable marked volatile to prevent case when it doesn't equal 0, the loop can break early since it can never be 0 again - tested with Fastest O3 and Whole Module optimization (App Store Release) // FREEBIE --- SignalServiceKit/src/Util/NSData+OWSConstantTimeCompare.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SignalServiceKit/src/Util/NSData+OWSConstantTimeCompare.m b/SignalServiceKit/src/Util/NSData+OWSConstantTimeCompare.m index 1333e3558..fff804496 100644 --- a/SignalServiceKit/src/Util/NSData+OWSConstantTimeCompare.m +++ b/SignalServiceKit/src/Util/NSData+OWSConstantTimeCompare.m @@ -10,7 +10,7 @@ NS_ASSUME_NONNULL_BEGIN - (BOOL)ows_constantTimeIsEqualToData:(NSData *)other { - BOOL isEqual = YES; + volatile UInt8 isEqual = 0; if (self.length != other.length) { return NO; @@ -21,10 +21,10 @@ NS_ASSUME_NONNULL_BEGIN for (int i = 0; i < self.length; i++) { // rather than returning as soon as we find a discrepency, we compare the rest of // the byte stream to maintain a constant time comparison - isEqual = isEqual && (leftBytes[i] == rightBytes[i]); + isEqual |= leftBytes[i] ^ rightBytes[i]; } - return isEqual; + return isEqual == 0; } @end