From e2f71b2e80c81f083514c8419d949c2113b072a9 Mon Sep 17 00:00:00 2001 From: Sebastian Andrzej Siewior Date: Sun, 13 Oct 2024 18:05:55 +0200 Subject: [PATCH] mem: Don't use posix_memalign() and friends with custom wrapper. 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 --- crypto/mem.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crypto/mem.c b/crypto/mem.c index d788afaadbda40..7403c178d5f91c 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -229,7 +229,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) { - void *ret; + void *ret = NULL; *freeptr = NULL; @@ -239,6 +239,10 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, #endif #if defined (_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) + /* + * Allow non-malloc() allocations as long as none are provided + */ + if (!malloc_impl) { if (posix_memalign(&ret, alignment, num)) return NULL; *freeptr = ret; @@ -246,7 +250,9 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, #elif defined(_ISOC11_SOURCE) ret = *freeptr = aligned_alloc(alignment, num); return ret; -#else +#endif + } + /* we have to do this the hard way */ /* @@ -261,7 +267,7 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, * Step 1: Allocate an amount of memory that is * bytes bigger than requested */ - *freeptr = malloc(num + alignment); + *freeptr = CRYPTO_malloc(num + alignment, file, line); if (*freeptr == NULL) return NULL;