constant_time.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /**
  2. * Constant-time functions
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /*
  20. * The following functions are implemented without using comparison operators, as those
  21. * might be translated to branches by some compilers on some platforms.
  22. */
  23. #include "common.h"
  24. #include "constant_time_internal.h"
  25. #include "mbedtls/constant_time.h"
  26. #include "mbedtls/error.h"
  27. #include "mbedtls/platform_util.h"
  28. #if defined(MBEDTLS_BIGNUM_C)
  29. #include "mbedtls/bignum.h"
  30. #endif
  31. #if defined(MBEDTLS_SSL_TLS_C)
  32. #include "ssl_misc.h"
  33. #endif
  34. #if defined(MBEDTLS_RSA_C)
  35. #include "mbedtls/rsa.h"
  36. #endif
  37. #include <string.h>
  38. int mbedtls_ct_memcmp( const void *a,
  39. const void *b,
  40. size_t n )
  41. {
  42. size_t i;
  43. volatile const unsigned char *A = (volatile const unsigned char *) a;
  44. volatile const unsigned char *B = (volatile const unsigned char *) b;
  45. volatile unsigned char diff = 0;
  46. for( i = 0; i < n; i++ )
  47. {
  48. /* Read volatile data in order before computing diff.
  49. * This avoids IAR compiler warning:
  50. * 'the order of volatile accesses is undefined ..' */
  51. unsigned char x = A[i], y = B[i];
  52. diff |= x ^ y;
  53. }
  54. return( (int)diff );
  55. }
  56. unsigned mbedtls_ct_uint_mask( unsigned value )
  57. {
  58. /* MSVC has a warning about unary minus on unsigned, but this is
  59. * well-defined and precisely what we want to do here */
  60. #if defined(_MSC_VER)
  61. #pragma warning( push )
  62. #pragma warning( disable : 4146 )
  63. #endif
  64. return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
  65. #if defined(_MSC_VER)
  66. #pragma warning( pop )
  67. #endif
  68. }
  69. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
  70. size_t mbedtls_ct_size_mask( size_t value )
  71. {
  72. /* MSVC has a warning about unary minus on unsigned integer types,
  73. * but this is well-defined and precisely what we want to do here. */
  74. #if defined(_MSC_VER)
  75. #pragma warning( push )
  76. #pragma warning( disable : 4146 )
  77. #endif
  78. return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
  79. #if defined(_MSC_VER)
  80. #pragma warning( pop )
  81. #endif
  82. }
  83. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  84. #if defined(MBEDTLS_BIGNUM_C)
  85. mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value )
  86. {
  87. /* MSVC has a warning about unary minus on unsigned, but this is
  88. * well-defined and precisely what we want to do here */
  89. #if defined(_MSC_VER)
  90. #pragma warning( push )
  91. #pragma warning( disable : 4146 )
  92. #endif
  93. return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
  94. #if defined(_MSC_VER)
  95. #pragma warning( pop )
  96. #endif
  97. }
  98. #endif /* MBEDTLS_BIGNUM_C */
  99. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
  100. /** Constant-flow mask generation for "less than" comparison:
  101. * - if \p x < \p y, return all-bits 1, that is (size_t) -1
  102. * - otherwise, return all bits 0, that is 0
  103. *
  104. * This function can be used to write constant-time code by replacing branches
  105. * with bit operations using masks.
  106. *
  107. * \param x The first value to analyze.
  108. * \param y The second value to analyze.
  109. *
  110. * \return All-bits-one if \p x is less than \p y, otherwise zero.
  111. */
  112. static size_t mbedtls_ct_size_mask_lt( size_t x,
  113. size_t y )
  114. {
  115. /* This has the most significant bit set if and only if x < y */
  116. const size_t sub = x - y;
  117. /* sub1 = (x < y) ? 1 : 0 */
  118. const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
  119. /* mask = (x < y) ? 0xff... : 0x00... */
  120. const size_t mask = mbedtls_ct_size_mask( sub1 );
  121. return( mask );
  122. }
  123. size_t mbedtls_ct_size_mask_ge( size_t x,
  124. size_t y )
  125. {
  126. return( ~mbedtls_ct_size_mask_lt( x, y ) );
  127. }
  128. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  129. unsigned mbedtls_ct_size_bool_eq( size_t x,
  130. size_t y )
  131. {
  132. /* diff = 0 if x == y, non-zero otherwise */
  133. const size_t diff = x ^ y;
  134. /* MSVC has a warning about unary minus on unsigned integer types,
  135. * but this is well-defined and precisely what we want to do here. */
  136. #if defined(_MSC_VER)
  137. #pragma warning( push )
  138. #pragma warning( disable : 4146 )
  139. #endif
  140. /* diff_msb's most significant bit is equal to x != y */
  141. const size_t diff_msb = ( diff | (size_t) -diff );
  142. #if defined(_MSC_VER)
  143. #pragma warning( pop )
  144. #endif
  145. /* diff1 = (x != y) ? 1 : 0 */
  146. const unsigned diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
  147. return( 1 ^ diff1 );
  148. }
  149. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  150. /** Constant-flow "greater than" comparison:
  151. * return x > y
  152. *
  153. * This is equivalent to \p x > \p y, but is likely to be compiled
  154. * to code using bitwise operation rather than a branch.
  155. *
  156. * \param x The first value to analyze.
  157. * \param y The second value to analyze.
  158. *
  159. * \return 1 if \p x greater than \p y, otherwise 0.
  160. */
  161. static unsigned mbedtls_ct_size_gt( size_t x,
  162. size_t y )
  163. {
  164. /* Return the sign bit (1 for negative) of (y - x). */
  165. return( ( y - x ) >> ( sizeof( size_t ) * 8 - 1 ) );
  166. }
  167. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
  168. #if defined(MBEDTLS_BIGNUM_C)
  169. unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
  170. const mbedtls_mpi_uint y )
  171. {
  172. mbedtls_mpi_uint ret;
  173. mbedtls_mpi_uint cond;
  174. /*
  175. * Check if the most significant bits (MSB) of the operands are different.
  176. */
  177. cond = ( x ^ y );
  178. /*
  179. * If the MSB are the same then the difference x-y will be negative (and
  180. * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
  181. */
  182. ret = ( x - y ) & ~cond;
  183. /*
  184. * If the MSB are different, then the operand with the MSB of 1 is the
  185. * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
  186. * the MSB of y is 0.)
  187. */
  188. ret |= y & cond;
  189. ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
  190. return (unsigned) ret;
  191. }
  192. #endif /* MBEDTLS_BIGNUM_C */
  193. unsigned mbedtls_ct_uint_if( unsigned condition,
  194. unsigned if1,
  195. unsigned if0 )
  196. {
  197. unsigned mask = mbedtls_ct_uint_mask( condition );
  198. return( ( mask & if1 ) | (~mask & if0 ) );
  199. }
  200. #if defined(MBEDTLS_BIGNUM_C)
  201. /** Select between two sign values without branches.
  202. *
  203. * This is functionally equivalent to `condition ? if1 : if0` but uses only bit
  204. * operations in order to avoid branches.
  205. *
  206. * \note if1 and if0 must be either 1 or -1, otherwise the result
  207. * is undefined.
  208. *
  209. * \param condition Condition to test.
  210. * \param if1 The first sign; must be either +1 or -1.
  211. * \param if0 The second sign; must be either +1 or -1.
  212. *
  213. * \return \c if1 if \p condition is nonzero, otherwise \c if0.
  214. * */
  215. static int mbedtls_ct_cond_select_sign( unsigned char condition,
  216. int if1,
  217. int if0 )
  218. {
  219. /* In order to avoid questions about what we can reasonably assume about
  220. * the representations of signed integers, move everything to unsigned
  221. * by taking advantage of the fact that if1 and if0 are either +1 or -1. */
  222. unsigned uif1 = if1 + 1;
  223. unsigned uif0 = if0 + 1;
  224. /* condition was 0 or 1, mask is 0 or 2 as are uif1 and uif0 */
  225. const unsigned mask = condition << 1;
  226. /* select uif1 or uif0 */
  227. unsigned ur = ( uif0 & ~mask ) | ( uif1 & mask );
  228. /* ur is now 0 or 2, convert back to -1 or +1 */
  229. return( (int) ur - 1 );
  230. }
  231. void mbedtls_ct_mpi_uint_cond_assign( size_t n,
  232. mbedtls_mpi_uint *dest,
  233. const mbedtls_mpi_uint *src,
  234. unsigned char condition )
  235. {
  236. size_t i;
  237. /* MSVC has a warning about unary minus on unsigned integer types,
  238. * but this is well-defined and precisely what we want to do here. */
  239. #if defined(_MSC_VER)
  240. #pragma warning( push )
  241. #pragma warning( disable : 4146 )
  242. #endif
  243. /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
  244. const mbedtls_mpi_uint mask = -condition;
  245. #if defined(_MSC_VER)
  246. #pragma warning( pop )
  247. #endif
  248. for( i = 0; i < n; i++ )
  249. dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
  250. }
  251. #endif /* MBEDTLS_BIGNUM_C */
  252. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  253. /** Shift some data towards the left inside a buffer.
  254. *
  255. * `mbedtls_ct_mem_move_to_left(start, total, offset)` is functionally
  256. * equivalent to
  257. * ```
  258. * memmove(start, start + offset, total - offset);
  259. * memset(start + offset, 0, total - offset);
  260. * ```
  261. * but it strives to use a memory access pattern (and thus total timing)
  262. * that does not depend on \p offset. This timing independence comes at
  263. * the expense of performance.
  264. *
  265. * \param start Pointer to the start of the buffer.
  266. * \param total Total size of the buffer.
  267. * \param offset Offset from which to copy \p total - \p offset bytes.
  268. */
  269. static void mbedtls_ct_mem_move_to_left( void *start,
  270. size_t total,
  271. size_t offset )
  272. {
  273. volatile unsigned char *buf = start;
  274. size_t i, n;
  275. if( total == 0 )
  276. return;
  277. for( i = 0; i < total; i++ )
  278. {
  279. unsigned no_op = mbedtls_ct_size_gt( total - offset, i );
  280. /* The first `total - offset` passes are a no-op. The last
  281. * `offset` passes shift the data one byte to the left and
  282. * zero out the last byte. */
  283. for( n = 0; n < total - 1; n++ )
  284. {
  285. unsigned char current = buf[n];
  286. unsigned char next = buf[n+1];
  287. buf[n] = mbedtls_ct_uint_if( no_op, current, next );
  288. }
  289. buf[total-1] = mbedtls_ct_uint_if( no_op, buf[total-1], 0 );
  290. }
  291. }
  292. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
  293. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
  294. void mbedtls_ct_memcpy_if_eq( unsigned char *dest,
  295. const unsigned char *src,
  296. size_t len,
  297. size_t c1,
  298. size_t c2 )
  299. {
  300. /* mask = c1 == c2 ? 0xff : 0x00 */
  301. const size_t equal = mbedtls_ct_size_bool_eq( c1, c2 );
  302. const unsigned char mask = (unsigned char) mbedtls_ct_size_mask( equal );
  303. /* dest[i] = c1 == c2 ? src[i] : dest[i] */
  304. for( size_t i = 0; i < len; i++ )
  305. dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
  306. }
  307. void mbedtls_ct_memcpy_offset( unsigned char *dest,
  308. const unsigned char *src,
  309. size_t offset,
  310. size_t offset_min,
  311. size_t offset_max,
  312. size_t len )
  313. {
  314. size_t offsetval;
  315. for( offsetval = offset_min; offsetval <= offset_max; offsetval++ )
  316. {
  317. mbedtls_ct_memcpy_if_eq( dest, src + offsetval, len,
  318. offsetval, offset );
  319. }
  320. }
  321. int mbedtls_ct_hmac( mbedtls_md_context_t *ctx,
  322. const unsigned char *add_data,
  323. size_t add_data_len,
  324. const unsigned char *data,
  325. size_t data_len_secret,
  326. size_t min_data_len,
  327. size_t max_data_len,
  328. unsigned char *output )
  329. {
  330. /*
  331. * This function breaks the HMAC abstraction and uses the md_clone()
  332. * extension to the MD API in order to get constant-flow behaviour.
  333. *
  334. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  335. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  336. * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
  337. *
  338. * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
  339. * minlen, then cloning the context, and for each byte up to maxlen
  340. * finishing up the hash computation, keeping only the correct result.
  341. *
  342. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  343. */
  344. const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
  345. /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
  346. * all of which have the same block size except SHA-384. */
  347. const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
  348. const unsigned char * const ikey = ctx->hmac_ctx;
  349. const unsigned char * const okey = ikey + block_size;
  350. const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
  351. unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
  352. mbedtls_md_context_t aux;
  353. size_t offset;
  354. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  355. mbedtls_md_init( &aux );
  356. #define MD_CHK( func_call ) \
  357. do { \
  358. ret = (func_call); \
  359. if( ret != 0 ) \
  360. goto cleanup; \
  361. } while( 0 )
  362. MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
  363. /* After hmac_start() of hmac_reset(), ikey has already been hashed,
  364. * so we can start directly with the message */
  365. MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
  366. MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
  367. /* For each possible length, compute the hash up to that point */
  368. for( offset = min_data_len; offset <= max_data_len; offset++ )
  369. {
  370. MD_CHK( mbedtls_md_clone( &aux, ctx ) );
  371. MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
  372. /* Keep only the correct inner_hash in the output buffer */
  373. mbedtls_ct_memcpy_if_eq( output, aux_out, hash_size,
  374. offset, data_len_secret );
  375. if( offset < max_data_len )
  376. MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
  377. }
  378. /* The context needs to finish() before it starts() again */
  379. MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
  380. /* Now compute HASH(okey + inner_hash) */
  381. MD_CHK( mbedtls_md_starts( ctx ) );
  382. MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
  383. MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
  384. MD_CHK( mbedtls_md_finish( ctx, output ) );
  385. /* Done, get ready for next time */
  386. MD_CHK( mbedtls_md_hmac_reset( ctx ) );
  387. #undef MD_CHK
  388. cleanup:
  389. mbedtls_md_free( &aux );
  390. return( ret );
  391. }
  392. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  393. #if defined(MBEDTLS_BIGNUM_C)
  394. #define MPI_VALIDATE_RET( cond ) \
  395. MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
  396. /*
  397. * Conditionally assign X = Y, without leaking information
  398. * about whether the assignment was made or not.
  399. * (Leaking information about the respective sizes of X and Y is ok however.)
  400. */
  401. int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
  402. const mbedtls_mpi *Y,
  403. unsigned char assign )
  404. {
  405. int ret = 0;
  406. size_t i;
  407. mbedtls_mpi_uint limb_mask;
  408. MPI_VALIDATE_RET( X != NULL );
  409. MPI_VALIDATE_RET( Y != NULL );
  410. /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
  411. limb_mask = mbedtls_ct_mpi_uint_mask( assign );;
  412. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  413. X->s = mbedtls_ct_cond_select_sign( assign, Y->s, X->s );
  414. mbedtls_ct_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
  415. for( i = Y->n; i < X->n; i++ )
  416. X->p[i] &= ~limb_mask;
  417. cleanup:
  418. return( ret );
  419. }
  420. /*
  421. * Conditionally swap X and Y, without leaking information
  422. * about whether the swap was made or not.
  423. * Here it is not ok to simply swap the pointers, which whould lead to
  424. * different memory access patterns when X and Y are used afterwards.
  425. */
  426. int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
  427. mbedtls_mpi *Y,
  428. unsigned char swap )
  429. {
  430. int ret, s;
  431. size_t i;
  432. mbedtls_mpi_uint limb_mask;
  433. mbedtls_mpi_uint tmp;
  434. MPI_VALIDATE_RET( X != NULL );
  435. MPI_VALIDATE_RET( Y != NULL );
  436. if( X == Y )
  437. return( 0 );
  438. /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
  439. limb_mask = mbedtls_ct_mpi_uint_mask( swap );
  440. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  441. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
  442. s = X->s;
  443. X->s = mbedtls_ct_cond_select_sign( swap, Y->s, X->s );
  444. Y->s = mbedtls_ct_cond_select_sign( swap, s, Y->s );
  445. for( i = 0; i < X->n; i++ )
  446. {
  447. tmp = X->p[i];
  448. X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
  449. Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
  450. }
  451. cleanup:
  452. return( ret );
  453. }
  454. /*
  455. * Compare signed values in constant time
  456. */
  457. int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
  458. const mbedtls_mpi *Y,
  459. unsigned *ret )
  460. {
  461. size_t i;
  462. /* The value of any of these variables is either 0 or 1 at all times. */
  463. unsigned cond, done, X_is_negative, Y_is_negative;
  464. MPI_VALIDATE_RET( X != NULL );
  465. MPI_VALIDATE_RET( Y != NULL );
  466. MPI_VALIDATE_RET( ret != NULL );
  467. if( X->n != Y->n )
  468. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  469. /*
  470. * Set sign_N to 1 if N >= 0, 0 if N < 0.
  471. * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
  472. */
  473. X_is_negative = ( X->s & 2 ) >> 1;
  474. Y_is_negative = ( Y->s & 2 ) >> 1;
  475. /*
  476. * If the signs are different, then the positive operand is the bigger.
  477. * That is if X is negative (X_is_negative == 1), then X < Y is true and it
  478. * is false if X is positive (X_is_negative == 0).
  479. */
  480. cond = ( X_is_negative ^ Y_is_negative );
  481. *ret = cond & X_is_negative;
  482. /*
  483. * This is a constant-time function. We might have the result, but we still
  484. * need to go through the loop. Record if we have the result already.
  485. */
  486. done = cond;
  487. for( i = X->n; i > 0; i-- )
  488. {
  489. /*
  490. * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
  491. * X and Y are negative.
  492. *
  493. * Again even if we can make a decision, we just mark the result and
  494. * the fact that we are done and continue looping.
  495. */
  496. cond = mbedtls_ct_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
  497. *ret |= cond & ( 1 - done ) & X_is_negative;
  498. done |= cond;
  499. /*
  500. * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
  501. * X and Y are positive.
  502. *
  503. * Again even if we can make a decision, we just mark the result and
  504. * the fact that we are done and continue looping.
  505. */
  506. cond = mbedtls_ct_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
  507. *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
  508. done |= cond;
  509. }
  510. return( 0 );
  511. }
  512. #endif /* MBEDTLS_BIGNUM_C */
  513. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  514. int mbedtls_ct_rsaes_pkcs1_v15_unpadding( unsigned char *input,
  515. size_t ilen,
  516. unsigned char *output,
  517. size_t output_max_len,
  518. size_t *olen )
  519. {
  520. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  521. size_t i, plaintext_max_size;
  522. /* The following variables take sensitive values: their value must
  523. * not leak into the observable behavior of the function other than
  524. * the designated outputs (output, olen, return value). Otherwise
  525. * this would open the execution of the function to
  526. * side-channel-based variants of the Bleichenbacher padding oracle
  527. * attack. Potential side channels include overall timing, memory
  528. * access patterns (especially visible to an adversary who has access
  529. * to a shared memory cache), and branches (especially visible to
  530. * an adversary who has access to a shared code cache or to a shared
  531. * branch predictor). */
  532. size_t pad_count = 0;
  533. unsigned bad = 0;
  534. unsigned char pad_done = 0;
  535. size_t plaintext_size = 0;
  536. unsigned output_too_large;
  537. plaintext_max_size = ( output_max_len > ilen - 11 ) ? ilen - 11
  538. : output_max_len;
  539. /* Check and get padding length in constant time and constant
  540. * memory trace. The first byte must be 0. */
  541. bad |= input[0];
  542. /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  543. * where PS must be at least 8 nonzero bytes. */
  544. bad |= input[1] ^ MBEDTLS_RSA_CRYPT;
  545. /* Read the whole buffer. Set pad_done to nonzero if we find
  546. * the 0x00 byte and remember the padding length in pad_count. */
  547. for( i = 2; i < ilen; i++ )
  548. {
  549. pad_done |= ((input[i] | (unsigned char)-input[i]) >> 7) ^ 1;
  550. pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  551. }
  552. /* If pad_done is still zero, there's no data, only unfinished padding. */
  553. bad |= mbedtls_ct_uint_if( pad_done, 0, 1 );
  554. /* There must be at least 8 bytes of padding. */
  555. bad |= mbedtls_ct_size_gt( 8, pad_count );
  556. /* If the padding is valid, set plaintext_size to the number of
  557. * remaining bytes after stripping the padding. If the padding
  558. * is invalid, avoid leaking this fact through the size of the
  559. * output: use the maximum message size that fits in the output
  560. * buffer. Do it without branches to avoid leaking the padding
  561. * validity through timing. RSA keys are small enough that all the
  562. * size_t values involved fit in unsigned int. */
  563. plaintext_size = mbedtls_ct_uint_if(
  564. bad, (unsigned) plaintext_max_size,
  565. (unsigned) ( ilen - pad_count - 3 ) );
  566. /* Set output_too_large to 0 if the plaintext fits in the output
  567. * buffer and to 1 otherwise. */
  568. output_too_large = mbedtls_ct_size_gt( plaintext_size,
  569. plaintext_max_size );
  570. /* Set ret without branches to avoid timing attacks. Return:
  571. * - INVALID_PADDING if the padding is bad (bad != 0).
  572. * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  573. * plaintext does not fit in the output buffer.
  574. * - 0 if the padding is correct. */
  575. ret = - (int) mbedtls_ct_uint_if(
  576. bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
  577. mbedtls_ct_uint_if( output_too_large,
  578. - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
  579. 0 ) );
  580. /* If the padding is bad or the plaintext is too large, zero the
  581. * data that we're about to copy to the output buffer.
  582. * We need to copy the same amount of data
  583. * from the same buffer whether the padding is good or not to
  584. * avoid leaking the padding validity through overall timing or
  585. * through memory or cache access patterns. */
  586. bad = mbedtls_ct_uint_mask( bad | output_too_large );
  587. for( i = 11; i < ilen; i++ )
  588. input[i] &= ~bad;
  589. /* If the plaintext is too large, truncate it to the buffer size.
  590. * Copy anyway to avoid revealing the length through timing, because
  591. * revealing the length is as bad as revealing the padding validity
  592. * for a Bleichenbacher attack. */
  593. plaintext_size = mbedtls_ct_uint_if( output_too_large,
  594. (unsigned) plaintext_max_size,
  595. (unsigned) plaintext_size );
  596. /* Move the plaintext to the leftmost position where it can start in
  597. * the working buffer, i.e. make it start plaintext_max_size from
  598. * the end of the buffer. Do this with a memory access trace that
  599. * does not depend on the plaintext size. After this move, the
  600. * starting location of the plaintext is no longer sensitive
  601. * information. */
  602. mbedtls_ct_mem_move_to_left( input + ilen - plaintext_max_size,
  603. plaintext_max_size,
  604. plaintext_max_size - plaintext_size );
  605. /* Finally copy the decrypted plaintext plus trailing zeros into the output
  606. * buffer. If output_max_len is 0, then output may be an invalid pointer
  607. * and the result of memcpy() would be undefined; prevent undefined
  608. * behavior making sure to depend only on output_max_len (the size of the
  609. * user-provided output buffer), which is independent from plaintext
  610. * length, validity of padding, success of the decryption, and other
  611. * secrets. */
  612. if( output_max_len != 0 )
  613. memcpy( output, input + ilen - plaintext_max_size, plaintext_max_size );
  614. /* Report the amount of data we copied to the output buffer. In case
  615. * of errors (bad padding or output too large), the value of *olen
  616. * when this function returns is not specified. Making it equivalent
  617. * to the good case limits the risks of leaking the padding validity. */
  618. *olen = plaintext_size;
  619. return( ret );
  620. }
  621. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */