diff --git a/crypto/mem.c b/crypto/mem.c index 3ac8484176..a89b8719b6 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -239,6 +239,12 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, return NULL; #endif + /* Ensure that alignment is a power of two */ + if (alignment == 0 || (alignment & (alignment - 1)) != 0) { + ossl_report_alloc_err_inv(file, line); + return NULL; + } + /* 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) diff --git a/include/internal/mem_alloc_utils.h b/include/internal/mem_alloc_utils.h index 22c946c6df..e5423fa8fa 100644 --- a/include/internal/mem_alloc_utils.h +++ b/include/internal/mem_alloc_utils.h @@ -61,6 +61,13 @@ ossl_report_alloc_err_of(const char * const file, const int line) ossl_report_alloc_err_ex(file, line, CRYPTO_R_INTEGER_OVERFLOW); } +/* Report invalid memory allocation call arguments. */ +static ossl_inline ossl_unused void +ossl_report_alloc_err_inv(const char * const file, const int line) +{ + ossl_report_alloc_err_ex(file, line, ERR_R_PASSED_INVALID_ARGUMENT); +} + /* * Check the result of num and size multiplication for overflow * and set error if it is the case; return true if there was no overflow,