From 1104e80c8dff7d04eb482ddc315947268c251384 Mon Sep 17 00:00:00 2001 From: Eugene Syromiatnikov Date: Thu, 31 Jul 2025 14:27:22 +0200 Subject: [PATCH] crypto/mem.c: check the alignment for being a power of 2 in CRYPTO_aligned_alloc MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 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) --- crypto/mem.c | 6 ++++++ include/internal/mem_alloc_utils.h | 7 +++++++ 2 files changed, 13 insertions(+) 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, -- 2.47.3