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).
diff --git a/library/rsa.c b/library/rsa.c
index f70c6da..31f53ad 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -1527,7 +1527,7 @@
}
/* 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
@@ -1541,10 +1541,9 @@
(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).