]> git.ipfire.org Git - thirdparty/openvpn.git/commitdiff
Use crypto library functions for const time memcmp when possible
authorArne Schwabe <arne@rfc2549.org>
Thu, 16 Apr 2020 11:39:28 +0000 (13:39 +0200)
committerGert Doering <gert@greenie.muc.de>
Thu, 7 May 2020 12:55:57 +0000 (14:55 +0200)
Signed-off-by: Arne Schwabe <arne@rfc2549.org>
Acked-by: Gert Doering <gert@greenie.muc.de>
Message-Id: <20200416113930.15192-1-arne@rfc2549.org>
URL: https://www.mail-archive.com/openvpn-devel@lists.sourceforge.net/msg19749.html
Signed-off-by: Gert Doering <gert@greenie.muc.de>
src/openvpn/crypto.h
src/openvpn/crypto_mbedtls.c
src/openvpn/crypto_openssl.c

index 18a86ceb0b9dea8f2f181c7550f394d144b96aa2..dadf0a90979a65a66d60f47bc4b214cf3ea6fb6c 100644 (file)
@@ -528,21 +528,7 @@ void crypto_read_openvpn_key(const struct key_type *key_type,
  * As memcmp(), but constant-time.
  * Returns 0 when data is equal, non-zero otherwise.
  */
-static inline int
-memcmp_constant_time(const void *a, const void *b, size_t size)
-{
-    const uint8_t *a1 = a;
-    const uint8_t *b1 = b;
-    int ret = 0;
-    size_t i;
-
-    for (i = 0; i < size; i++)
-    {
-        ret |= *a1++ ^ *b1++;
-    }
-
-    return ret;
-}
+int memcmp_constant_time(const void *a, const void *b, size_t size);
 
 static inline bool
 key_ctx_bi_defined(const struct key_ctx_bi *key)
index 3e77fa9ee66a446c83585a3faa9a4d794139b13c..35072b736c073ae5517fb540d032bc4e1f80a4f2 100644 (file)
@@ -972,4 +972,23 @@ hmac_ctx_final(mbedtls_md_context_t *ctx, uint8_t *dst)
     ASSERT(0 == mbedtls_md_hmac_finish(ctx, dst));
 }
 
+int
+memcmp_constant_time(const void *a, const void *b, size_t size)
+{
+    /* mbed TLS has a no const time memcmp function that it exposes
+     * via its APIs like OpenSSL does with CRYPTO_memcmp
+     * Adapt the function that mbedtls itself uses in
+     * mbedtls_safer_memcmp as it considers that to be safe */
+    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 (size_t i = 0; i < size; i++)
+    {
+        unsigned char x = A[i], y = B[i];
+        diff |= x ^ y;
+    }
+
+    return diff;
+}
 #endif /* ENABLE_CRYPTO_MBEDTLS */
index a81dcfd8252b9819ee49ca8cbd79a8c210f3235e..9e7ea0fff3ac3820fc1ff327414ce2243888ed65 100644 (file)
@@ -1066,4 +1066,9 @@ hmac_ctx_final(HMAC_CTX *ctx, uint8_t *dst)
     HMAC_Final(ctx, dst, &in_hmac_len);
 }
 
+int
+memcmp_constant_time(const void *a, const void *b, size_t size)
+{
+    return CRYPTO_memcmp(a, b, size);
+}
 #endif /* ENABLE_CRYPTO_OPENSSL */