]> git.ipfire.org Git - thirdparty/openssl.git/commitdiff
crypto/mem.c: check for overflow in size calculation in CRYPTO_aligned_alloc
authorEugene Syromiatnikov <esyr@openssl.org>
Thu, 31 Jul 2025 12:32:27 +0000 (14:32 +0200)
committerNeil Horman <nhorman@openssl.org>
Fri, 8 Aug 2025 16:22:10 +0000 (12:22 -0400)
The open-coded implementation performs addition of size and alignment,
that may overflow.

Signed-off-by: Eugene Syromiatnikov <esyr@openssl.org>
Reviewed-by: Saša Nedvědický <sashan@openssl.org>
Reviewed-by: Matt Caswell <matt@openssl.org>
Reviewed-by: Paul Dale <ppzgs1@gmail.com>
Reviewed-by: Neil Horman <nhorman@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/28059)

crypto/mem.c
include/internal/mem_alloc_utils.h

index 6bdaca27f37281b4f968c7c5badda4113d3b195b..05f2922f20661edb4b0d46057dcf3da55efefc49 100644 (file)
@@ -231,6 +231,7 @@ void *CRYPTO_zalloc(size_t num, const char *file, int line)
 void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
                            const char *file, int line)
 {
+    size_t alloc_bytes;
     void *ret;
 
     *freeptr = NULL;
@@ -280,11 +281,14 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
      * via _aligned_malloc, just avoid its use entirely
      */
 
+    if (ossl_unlikely(!ossl_size_add(num, alignment, &alloc_bytes, file, line)))
+        return NULL;
+
     /*
      * Step 1: Allocate an amount of memory that is <alignment>
      * bytes bigger than requested
      */
-    *freeptr = CRYPTO_malloc(num + alignment, file, line);
+    *freeptr = CRYPTO_malloc(alloc_bytes, file, line);
     if (*freeptr == NULL)
         return NULL;
 
index e5423fa8faa37f58e5b0f6a8f366c0befade7066..4d87179f6bd7ea75c0d24aee20b511600999b71b 100644 (file)
@@ -91,21 +91,23 @@ ossl_size_mul(const size_t num, const size_t size, size_t *bytes,
 
 /*
  * Check the result of size1 and size2 addition for overflow
- * and set error if it is the case.
+ * and set error if it is the case;  returns true if there was no overflow,
+ * false if there was.
  */
 static ossl_inline ossl_unused bool
-ossl_size_add_of(const size_t size1, const size_t size2, size_t *bytes,
-                 const char * const file, const int line)
+ossl_size_add(const size_t size1, const size_t size2, size_t *bytes,
+              const char * const file, const int line)
 {
-    *bytes = size1 + size2;
+    int err = 0;
+    *bytes = safe_add_size_t(size1, size2, &err);
 
-    if (ossl_unlikely(*bytes < size1)) {
+    if (ossl_unlikely(err != 0)) {
         ossl_report_alloc_err_of(file, line);
 
-        return true;
+        return false;
     }
 
-    return false;
+    return true;
 }
 
 #endif /* OSSL_INTERNAL_CHECK_SIZE_OVERFLOW_H */