Skip to content

Commit

Permalink
mem: Don't use posix_memalign() and friends with custom wrapper.
Browse files Browse the repository at this point in the history
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: openssl#25678

Signed-off-by: Sebastian Andrzej Siewior <[email protected]>
  • Loading branch information
sebastianas committed Oct 13, 2024
1 parent 2c536c8 commit 980a8d5
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions crypto/mem.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -238,15 +238,21 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
return ret;
#endif

/*
* Allow non-malloc() allocations as long as no malloc_impl is provided.
*/
if (!malloc_impl) {
#if defined (_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
if (posix_memalign(&ret, alignment, num))
return NULL;
*freeptr = ret;
return ret;
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 */

/*
Expand All @@ -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 <alignment>
* bytes bigger than requested
*/
*freeptr = malloc(num + alignment);
*freeptr = CRYPTO_malloc(num + alignment, file, line);
if (*freeptr == NULL)
return NULL;

Expand All @@ -282,7 +288,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)
Expand Down

0 comments on commit 980a8d5

Please sign in to comment.