Skip to content

Commit 4edaf06

Browse files
committed
Add check preventing integer multiplication wrapping around in scratch_max_allocation
1 parent fa33017 commit 4edaf06

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/scratch_impl.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@ static size_t secp256k1_scratch_max_allocation(const secp256k1_callback* error_c
6060
secp256k1_callback_call(error_callback, "invalid scratch space");
6161
return 0;
6262
}
63+
/* Ensure that multiplication will not wrap around */
64+
if (ALIGNMENT > 1 && objects > SIZE_MAX/(ALIGNMENT - 1)) {
65+
return 0;
66+
}
6367
if (scratch->max_size - scratch->alloc_size <= objects * (ALIGNMENT - 1)) {
6468
return 0;
6569
}

src/tests.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,14 @@ void run_scratch_tests(void) {
400400
secp256k1_scratch_space_destroy(none, scratch);
401401
CHECK(ecount == 5);
402402

403+
/* Test that large integers do not wrap around in a bad way */
404+
scratch = secp256k1_scratch_space_create(none, 1000);
405+
/* Try max allocation with a large number of objects. Only makes sense if
406+
* ALIGNMENT is greater than 1 because otherwise the objects take no extra
407+
* space. */
408+
CHECK(ALIGNMENT <= 1 || !secp256k1_scratch_max_allocation(&none->error_callback, scratch, (SIZE_MAX / (ALIGNMENT - 1)) + 1));
409+
secp256k1_scratch_space_destroy(none, scratch);
410+
403411
/* cleanup */
404412
secp256k1_scratch_space_destroy(none, NULL); /* no-op */
405413
secp256k1_context_destroy(none);

0 commit comments

Comments
 (0)