constant_time.c 28 KB

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