From 08513ce341c65b812f3c5c16ff54f74997329f3e Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 4 Oct 2018 21:24:21 +0200 Subject: [PATCH] Use branch-free size comparison for the padding size In mbedtls_rsa_rsaes_pkcs1_v15_decrypt, use size_greater_than (which is based on bitwise operations) instead of the < operator to compare sizes when the values being compared must not leak. Some compilers compile < to a branch at least under some circumstances (observed with gcc 5.4 for arm-gnueabi -O9 on a toy program). --- library/rsa.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/library/rsa.c b/library/rsa.c index becbd6fa4..7588a7017 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -1118,7 +1118,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, } /* There must be at least 8 bytes of padding. */ - bad |= ( pad_count < 8 ); + bad |= size_greater_than( 8, pad_count ); /* If the padding is valid, set plaintext_size to the number of * remaining bytes after stripping the padding. If the padding @@ -1132,10 +1132,9 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, (unsigned) ( ilen - ( p - buf ) ) ); /* Set output_too_large to 0 if the plaintext fits in the output - * buffer and to 1 otherwise. This is the sign bit (1 for negative) - * of (output_max_len - plaintext_size). */ - output_too_large = ( ( output_max_len - plaintext_size ) >> - ( ( sizeof( output_max_len ) * 8 - 1 ) ) ); + * buffer and to 1 otherwise. */ + output_too_large = size_greater_than( plaintext_size, + plaintext_max_size ); /* Set ret without branches to avoid timing attacks. Return: * - INVALID_PADDING if the padding is bad (bad != 0).