From 89f1f9bd73351e5f4fe16bcd8062d71e8f1fe5a7 Mon Sep 17 00:00:00 2001 From: Eugene Syromiatnikov Date: Thu, 31 Jul 2025 14:32:27 +0200 Subject: [PATCH] crypto/mem.c: check for overflow in size calculation in CRYPTO_aligned_alloc MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The open-coded implementation performs addition of size and alignment, that may overflow. 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 | 16 +++++++++------- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/crypto/mem.c b/crypto/mem.c index 6bdaca27f3..05f2922f20 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -231,6 +231,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) { + size_t alloc_bytes; void *ret; *freeptr = NULL; @@ -280,11 +281,14 @@ void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr, * via _aligned_malloc, just avoid its use entirely */ + if (ossl_unlikely(!ossl_size_add(num, alignment, &alloc_bytes, file, line))) + return NULL; + /* * Step 1: Allocate an amount of memory that is * bytes bigger than requested */ - *freeptr = CRYPTO_malloc(num + alignment, file, line); + *freeptr = CRYPTO_malloc(alloc_bytes, file, line); if (*freeptr == NULL) return NULL; diff --git a/include/internal/mem_alloc_utils.h b/include/internal/mem_alloc_utils.h index e5423fa8fa..4d87179f6b 100644 --- a/include/internal/mem_alloc_utils.h +++ b/include/internal/mem_alloc_utils.h @@ -91,21 +91,23 @@ ossl_size_mul(const size_t num, const size_t size, size_t *bytes, /* * Check the result of size1 and size2 addition for overflow - * and set error if it is the case. + * and set error if it is the case; returns true if there was no overflow, + * false if there was. */ static ossl_inline ossl_unused bool -ossl_size_add_of(const size_t size1, const size_t size2, size_t *bytes, - const char * const file, const int line) +ossl_size_add(const size_t size1, const size_t size2, size_t *bytes, + const char * const file, const int line) { - *bytes = size1 + size2; + int err = 0; + *bytes = safe_add_size_t(size1, size2, &err); - if (ossl_unlikely(*bytes < size1)) { + if (ossl_unlikely(err != 0)) { ossl_report_alloc_err_of(file, line); - return true; + return false; } - return false; + return true; } #endif /* OSSL_INTERNAL_CHECK_SIZE_OVERFLOW_H */ -- 2.47.2