]> git.ipfire.org Git - thirdparty/openssl.git/commitdiff
mem: Don't use posix_memalign() and friends with custom wrapper
authorSebastian Andrzej Siewior <sebastian@breakpoint.cc>
Sun, 13 Oct 2024 16:05:55 +0000 (18:05 +0200)
committerTomas Mraz <tomas@openssl.org>
Wed, 16 Oct 2024 08:13:49 +0000 (10:13 +0200)
If the application provides custom memory allocations functions via
CRYPTO_set_mem_functions() then those should be used instead something
else like posix_memalign(). The applications might verify alloc and free
calls and pointers from posix_memalign() were never returned by the
implementations.

At least stunnel4 complains here.

Use posix_memalign() or if aligned_alloc() only if the application did
not provide a custom malloc() implementation. In case of a custom
implementation use CRYPTO_malloc() and align the memory accordingly.

Fixes #25678

Signed-off-by: Sebastian Andrzej Siewior <sebastian@breakpoint.cc>
Reviewed-by: Saša Nedvědický <sashan@openssl.org>
Reviewed-by: Matt Caswell <matt@openssl.org>
Reviewed-by: Shane Lontis <shane.lontis@oracle.com>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/25682)

crypto/mem.c

index d788afaadbda40c9238990ed39683d10cc31477b..032f2a9cd17bb6c0173cb86baeb1942566ff4f0e 100644 (file)
@@ -238,15 +238,19 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
     return ret;
 #endif
 
-#if defined (_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
-    if (posix_memalign(&ret, alignment, num))
-        return NULL;
-    *freeptr = ret;
-    return ret;
+    /* Allow non-malloc() allocations as long as no malloc_impl is provided. */
+    if (malloc_impl == CRYPTO_malloc) {
+#if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
+        if (posix_memalign(&ret, alignment, num))
+            return NULL;
+        *freeptr = ret;
+        return ret;
 #elif defined(_ISOC11_SOURCE)
-    ret = *freeptr =  aligned_alloc(alignment, num);
-    return ret;
-#else
+        ret = *freeptr = aligned_alloc(alignment, num);
+        return ret;
+#endif
+    }
+
     /* we have to do this the hard way */
 
     /*
@@ -261,7 +265,7 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
      * Step 1: Allocate an amount of memory that is <alignment>
      * bytes bigger than requested
      */
-    *freeptr = malloc(num + alignment);
+    *freeptr = CRYPTO_malloc(num + alignment, file, line);
     if (*freeptr == NULL)
         return NULL;
 
@@ -282,7 +286,6 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
      */
     ret = (void *)((uintptr_t)ret & (uintptr_t)(~(alignment - 1)));
     return ret;
-#endif
 }
 
 void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)