Skip to content

Commit 8ecc6ce

Browse files
committed
Add check preventing rounding to alignment from wrapping around in scratch_alloc
1 parent 4edaf06 commit 8ecc6ce

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/scratch_impl.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,14 @@ static size_t secp256k1_scratch_max_allocation(const secp256k1_callback* error_c
7272

7373
static void *secp256k1_scratch_alloc(const secp256k1_callback* error_callback, secp256k1_scratch* scratch, size_t size) {
7474
void *ret;
75-
size = ROUND_TO_ALIGN(size);
75+
size_t rounded_size;
76+
77+
rounded_size = ROUND_TO_ALIGN(size);
78+
/* Check that rounding did not wrap around */
79+
if (rounded_size < size) {
80+
return NULL;
81+
}
82+
size = rounded_size;
7683

7784
if (memcmp(scratch->magic, "scratch", 8) != 0) {
7885
secp256k1_callback_call(error_callback, "invalid scratch space");

src/tests.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,10 @@ void run_scratch_tests(void) {
406406
* ALIGNMENT is greater than 1 because otherwise the objects take no extra
407407
* space. */
408408
CHECK(ALIGNMENT <= 1 || !secp256k1_scratch_max_allocation(&none->error_callback, scratch, (SIZE_MAX / (ALIGNMENT - 1)) + 1));
409+
/* Try allocating SIZE_MAX to test wrap around which only happens if
410+
* ALIGNMENT > 1, otherwise it returns NULL anyway because the scratch
411+
* space is too small. */
412+
CHECK(secp256k1_scratch_alloc(&none->error_callback, scratch, SIZE_MAX) == NULL);
409413
secp256k1_scratch_space_destroy(none, scratch);
410414

411415
/* cleanup */

0 commit comments

Comments
 (0)