From e6cb45e68ef8eefc8d57cbda2927ba18de7d00d8 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 10 Aug 2023 15:59:28 +0200 Subject: [PATCH] mbedtls_mpi_exp_mod: remove spurious copy of the output variable Clear some confusion between `X` as the output variable and "X" as a name given to the accumulator. Previous iterations of the code used the variable `X` as the accumulator, but now that the accumulator is `W[x_index]`, some of the comments didn't make sense. Remove the copy of the initial value of `X` into `W[x_index]`, which was meaningless: the initial value of an output variable should not, and did not, matter. `W[x_index]` is later overridden unconditionally to take the value `RR`. Signed-off-by: Gilles Peskine --- library/bignum.c | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index f2a864150..798d75824 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -1680,8 +1680,9 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A, * and squarings. Firstly, when multiplying by an element of the window * W[i], we do a constant-trace table lookup to obfuscate i. This leaves * squarings as having a different memory access patterns from other - * multiplications. So secondly, we put the accumulator X in the table as - * well, and also do a constant-trace table lookup to multiply by X. + * multiplications. So secondly, we put the accumulator in the table as + * well, and also do a constant-trace table lookup to multiply by the + * accumulator which is W[x_index]. * * This way, all multiplications take the form of a lookup-and-multiply. * The number of lookup-and-multiply operations inside each iteration of @@ -1694,19 +1695,16 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A, * observe both memory accesses and branches. However, branch prediction * exploitation typically requires many traces of execution over the same * data, which is defeated by randomized blinding. - * - * To achieve this, we make a copy of X and we use the table entry in each - * calculation from this point on. */ const size_t x_index = 0; mbedtls_mpi_init(&W[x_index]); - mbedtls_mpi_copy(&W[x_index], X); j = N->n + 1; - /* All W[i] and X must have at least N->n limbs for the mpi_montmul() - * and mpi_montred() calls later. Here we ensure that W[1] and X are - * large enough, and later we'll grow other W[i] to the same length. - * They must not be shrunk midway through this function! + /* All W[i] including the accumulator must have at least N->n limbs for + * the mpi_montmul() and mpi_montred() calls later. Here we ensure that + * W[1] and the accumulator W[x_index] are large enough. later we'll grow + * other W[i] to the same length. They must not be shrunk midway through + * this function! */ MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[x_index], j)); MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[1], j));