From: Eugene Syromiatnikov Date: Thu, 31 Jul 2025 12:27:22 +0000 (+0200) Subject: crypto/mem.c: check the alignment for being a power of 2 in CRYPTO_aligned_alloc X-Git-Tag: openssl-3.6.0-alpha1~213 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=1104e80c8dff7d04eb482ddc315947268c251384;p=thirdparty%2Fopenssl.git crypto/mem.c: check the alignment for being a power of 2 in CRYPTO_aligned_alloc Otherwise the roundup calculation performed in the open-coded implementation may put the pointer out of bounds. Signed-off-by: Eugene Syromiatnikov Reviewed-by: Saša Nedvědický Reviewed-by: Matt Caswell Reviewed-by: Paul Dale Reviewed-by: Neil Horman (Merged from https://github.com/openssl/openssl/pull/28059) --- diff --git a/crypto/mem.c b/crypto/mem.c index 3ac84841765..a89b8719b6e 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 22c946c6df3..e5423fa8faa 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,