From 4edaf06fb02a9ac9cd115e0c967bb0ef35cae01d Mon Sep 17 00:00:00 2001 From: Jonas Nick Date: Fri, 12 Jul 2019 09:56:56 +0000 Subject: [PATCH] Add check preventing integer multiplication wrapping around in scratch_max_allocation --- src/scratch_impl.h | 4 ++++ src/tests.c | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/src/scratch_impl.h b/src/scratch_impl.h index 4cee7000..937e29a0 100644 --- a/src/scratch_impl.h +++ b/src/scratch_impl.h @@ -60,6 +60,10 @@ static size_t secp256k1_scratch_max_allocation(const secp256k1_callback* error_c secp256k1_callback_call(error_callback, "invalid scratch space"); return 0; } + /* Ensure that multiplication will not wrap around */ + if (ALIGNMENT > 1 && objects > SIZE_MAX/(ALIGNMENT - 1)) { + return 0; + } if (scratch->max_size - scratch->alloc_size <= objects * (ALIGNMENT - 1)) { return 0; } diff --git a/src/tests.c b/src/tests.c index 132df9ba..990f7d65 100644 --- a/src/tests.c +++ b/src/tests.c @@ -400,6 +400,14 @@ void run_scratch_tests(void) { secp256k1_scratch_space_destroy(none, scratch); CHECK(ecount == 5); + /* Test that large integers do not wrap around in a bad way */ + scratch = secp256k1_scratch_space_create(none, 1000); + /* Try max allocation with a large number of objects. Only makes sense if + * ALIGNMENT is greater than 1 because otherwise the objects take no extra + * space. */ + CHECK(ALIGNMENT <= 1 || !secp256k1_scratch_max_allocation(&none->error_callback, scratch, (SIZE_MAX / (ALIGNMENT - 1)) + 1)); + secp256k1_scratch_space_destroy(none, scratch); + /* cleanup */ secp256k1_scratch_space_destroy(none, NULL); /* no-op */ secp256k1_context_destroy(none);