From 7506e064d791e529d2e57bb52c156deb33b897ef Mon Sep 17 00:00:00 2001 From: Fabien Date: Mon, 26 Oct 2020 12:29:00 +0100 Subject: [PATCH] Prevent arithmetic on NULL pointer if the scratch space is too small If the scratch space is too small when calling `secp256k1_ecmult_strauss_batch()`, the `state.pre_a` allocation will fail and the pointer will be `NULL`. This causes `state.pre_a_lam` to be computed from the `NULL` pointer. It is also possible that the first allocation to fail is for `state.ps`, which will cause the failure to occur when in `secp256k1_ecmult_strauss_wnaf()`. The issue has been detected by UBSAN using Clang 10: ``` CC=clang \ CFLAGS="-fsanitize=undefined -fno-omit-frame-pointer" \ LDFLAGS="-fsanitize=undefined -fno-omit-frame-pointer" \ ../configure UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 make check ``` --- src/ecmult_impl.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ecmult_impl.h b/src/ecmult_impl.h index 057a69cf73..62431b6820 100644 --- a/src/ecmult_impl.h +++ b/src/ecmult_impl.h @@ -595,11 +595,11 @@ static int secp256k1_ecmult_strauss_batch(const secp256k1_callback* error_callba scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(error_callback, scratch, n_points * sizeof(secp256k1_scalar)); state.prej = (secp256k1_gej*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_gej)); state.zr = (secp256k1_fe*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe)); - state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(error_callback, scratch, n_points * 2 * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); - state.pre_a_lam = state.pre_a + n_points * ECMULT_TABLE_SIZE(WINDOW_A); + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); + state.pre_a_lam = (secp256k1_ge*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(error_callback, scratch, n_points * sizeof(struct secp256k1_strauss_point_state)); - if (points == NULL || scalars == NULL || state.prej == NULL || state.zr == NULL || state.pre_a == NULL) { + if (points == NULL || scalars == NULL || state.prej == NULL || state.zr == NULL || state.pre_a == NULL || state.pre_a_lam == NULL || state.ps == NULL) { secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint); return 0; }