From f19aefb00b5bb1c73829d8cf33d8bebc08582389 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 4 Oct 2018 22:45:13 +0200 Subject: [PATCH] Minor optimization in the PKCS#1v1.5 unpadding step Rather than doing the quadratic-time constant-memory-trace on the whole working buffer, do it on the section of the buffer where the data to copy has to lie, which can be significantly smaller if the output buffer is significantly smaller than the working buffer, e.g. for TLS RSA ciphersuites (48 bytes vs MBEDTLS_MPI_MAX_SIZE). --- library/rsa.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/library/rsa.c b/library/rsa.c index 7588a7017..2ca27d991 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -1162,15 +1162,19 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, (unsigned) plaintext_max_size, (unsigned) plaintext_size ); - /* Move the plaintext to the beginning of the working buffer so that - * its position no longer depends on the padding and we have enough - * room from the beginning of the plaintext to copy a number of bytes - * that does not depend on the padding. */ - mem_move_to_left( buf, ilen, ilen - plaintext_size ); + /* Move the plaintext to the leftmost position where it can start in + * the working buffer, i.e. make it start plaintext_max_size from + * the end of the buffer. Do this with a memory access trace that + * does not depend on the plaintext size. After this move, the + * starting location of the plaintext is no longer sensitive + * information. */ + p = buf + ilen - plaintext_max_size; + mem_move_to_left( p, plaintext_max_size, + plaintext_max_size - plaintext_size ); - /* Finally copy the decrypted plaintext plus trailing data + /* Finally copy the decrypted plaintext plus trailing zeros * into the output buffer. */ - memcpy( output, buf, plaintext_max_size ); + memcpy( output, p, plaintext_max_size ); /* Report the amount of data we copied to the output buffer. In case * of errors (bad padding or output too large), the value of *olen