Bug 1775359 - make NSS_SecureMemcmp 0/1 valued. r=nss-reviewers,mt
authorJohn M. Schanck <jschanck@mozilla.com>
Mon, 11 Jul 2022 10:02:52 +0000
changeset 16268 07727985696a30d3317f626c3d93ccb3302a611b
parent 16267 3d83a07f913ee141e30541444909447db6f0a6fa
child 16269 cafb891ea6cead904ad550e56fd7eafc10190b4b
push id4172
push userdjackson@mozilla.com
push dateMon, 11 Jul 2022 10:05:10 +0000
reviewersnss-reviewers, mt
bugs1775359
Bug 1775359 - make NSS_SecureMemcmp 0/1 valued. r=nss-reviewers,mt Differential Revision: https://phabricator.services.mozilla.com/D149931
lib/util/secport.c
--- a/lib/util/secport.c
+++ b/lib/util/secport.c
@@ -768,32 +768,35 @@ NSS_PutEnv(const char *envVarName, const
  * Perform a constant-time compare of two memory regions. The return value is
  * 0 if the memory regions are equal and non-zero otherwise.
  */
 int
 NSS_SecureMemcmp(const void *ia, const void *ib, size_t n)
 {
     const unsigned char *a = (const unsigned char *)ia;
     const unsigned char *b = (const unsigned char *)ib;
-    size_t i;
-    unsigned char r = 0;
+    int r = 0;
 
-    for (i = 0; i < n; ++i) {
-        r |= *a++ ^ *b++;
+    for (size_t i = 0; i < n; ++i) {
+        r |= a[i] ^ b[i];
     }
 
-    return r;
+    /* 0 <= r < 256, so -r has bit 8 set when r != 0 */
+    return 1 & (-r >> 8);
 }
 
 /*
  * Perform a constant-time check if a memory region is all 0. The return value
  * is 0 if the memory region is all zero.
  */
 unsigned int
 NSS_SecureMemcmpZero(const void *mem, size_t n)
 {
-    PRUint8 zero = 0;
-    size_t i;
-    for (i = 0; i < n; ++i) {
-        zero |= *(PRUint8 *)((uintptr_t)mem + i);
+    const unsigned char *a = (const unsigned char *)mem;
+    int r = 0;
+
+    for (size_t i = 0; i < n; ++i) {
+        r |= a[i];
     }
-    return zero;
+
+    /* 0 <= r < 256, so -r has bit 8 set when r != 0 */
+    return 1 & (-r >> 8);
 }