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 <esyr@openssl.org>

Reviewed-by: Saša Nedvědický <sashan@openssl.org>
Reviewed-by: Matt Caswell <matt@openssl.org>
Reviewed-by: Paul Dale <ppzgs1@gmail.com>
Reviewed-by: Neil Horman <nhorman@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/28059)
This commit is contained in:
Eugene Syromiatnikov 2025-07-31 14:27:22 +02:00 committed by Neil Horman
parent 648803a17e
commit 1104e80c8d
2 changed files with 13 additions and 0 deletions

View File

@ -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)

View File

@ -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,