constant_time.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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. /* Fill the hash buffer in advance with something that is
  419. * not a valid hash (barring an attack on the hash and
  420. * deliberately-crafted input), in case the caller doesn't
  421. * check the return status properly. */
  422. memset( output, '!', hash_size );
  423. /* For each possible length, compute the hash up to that point */
  424. for( offset = min_data_len; offset <= max_data_len; offset++ )
  425. {
  426. MD_CHK( mbedtls_md_clone( &aux, ctx ) );
  427. MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
  428. /* Keep only the correct inner_hash in the output buffer */
  429. mbedtls_ct_memcpy_if_eq( output, aux_out, hash_size,
  430. offset, data_len_secret );
  431. if( offset < max_data_len )
  432. MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
  433. }
  434. /* The context needs to finish() before it starts() again */
  435. MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
  436. /* Now compute HASH(okey + inner_hash) */
  437. MD_CHK( mbedtls_md_starts( ctx ) );
  438. MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
  439. MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
  440. MD_CHK( mbedtls_md_finish( ctx, output ) );
  441. /* Done, get ready for next time */
  442. MD_CHK( mbedtls_md_hmac_reset( ctx ) );
  443. #undef MD_CHK
  444. cleanup:
  445. mbedtls_md_free( &aux );
  446. return( ret );
  447. }
  448. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  449. #if defined(MBEDTLS_BIGNUM_C)
  450. #define MPI_VALIDATE_RET( cond ) \
  451. MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
  452. /*
  453. * Conditionally assign X = Y, without leaking information
  454. * about whether the assignment was made or not.
  455. * (Leaking information about the respective sizes of X and Y is ok however.)
  456. */
  457. #if defined(_MSC_VER) && defined(_M_ARM64) && (_MSC_FULL_VER < 193131103)
  458. /*
  459. * MSVC miscompiles this function if it's inlined prior to Visual Studio 2022 version 17.1. See:
  460. * https://developercommunity.visualstudio.com/t/c-compiler-miscompiles-part-of-mbedtls-library-on/1646989
  461. */
  462. __declspec(noinline)
  463. #endif
  464. int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
  465. const mbedtls_mpi *Y,
  466. unsigned char assign )
  467. {
  468. int ret = 0;
  469. size_t i;
  470. mbedtls_mpi_uint limb_mask;
  471. MPI_VALIDATE_RET( X != NULL );
  472. MPI_VALIDATE_RET( Y != NULL );
  473. /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
  474. limb_mask = mbedtls_ct_mpi_uint_mask( assign );;
  475. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  476. X->s = mbedtls_ct_cond_select_sign( assign, Y->s, X->s );
  477. mbedtls_ct_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
  478. for( i = Y->n; i < X->n; i++ )
  479. X->p[i] &= ~limb_mask;
  480. cleanup:
  481. return( ret );
  482. }
  483. /*
  484. * Conditionally swap X and Y, without leaking information
  485. * about whether the swap was made or not.
  486. * Here it is not ok to simply swap the pointers, which would lead to
  487. * different memory access patterns when X and Y are used afterwards.
  488. */
  489. int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
  490. mbedtls_mpi *Y,
  491. unsigned char swap )
  492. {
  493. int ret, s;
  494. size_t i;
  495. mbedtls_mpi_uint limb_mask;
  496. mbedtls_mpi_uint tmp;
  497. MPI_VALIDATE_RET( X != NULL );
  498. MPI_VALIDATE_RET( Y != NULL );
  499. if( X == Y )
  500. return( 0 );
  501. /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
  502. limb_mask = mbedtls_ct_mpi_uint_mask( swap );
  503. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
  504. MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
  505. s = X->s;
  506. X->s = mbedtls_ct_cond_select_sign( swap, Y->s, X->s );
  507. Y->s = mbedtls_ct_cond_select_sign( swap, s, Y->s );
  508. for( i = 0; i < X->n; i++ )
  509. {
  510. tmp = X->p[i];
  511. X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
  512. Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
  513. }
  514. cleanup:
  515. return( ret );
  516. }
  517. /*
  518. * Compare signed values in constant time
  519. */
  520. int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
  521. const mbedtls_mpi *Y,
  522. unsigned *ret )
  523. {
  524. size_t i;
  525. /* The value of any of these variables is either 0 or 1 at all times. */
  526. unsigned cond, done, X_is_negative, Y_is_negative;
  527. MPI_VALIDATE_RET( X != NULL );
  528. MPI_VALIDATE_RET( Y != NULL );
  529. MPI_VALIDATE_RET( ret != NULL );
  530. if( X->n != Y->n )
  531. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  532. /*
  533. * Set sign_N to 1 if N >= 0, 0 if N < 0.
  534. * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
  535. */
  536. X_is_negative = ( X->s & 2 ) >> 1;
  537. Y_is_negative = ( Y->s & 2 ) >> 1;
  538. /*
  539. * If the signs are different, then the positive operand is the bigger.
  540. * That is if X is negative (X_is_negative == 1), then X < Y is true and it
  541. * is false if X is positive (X_is_negative == 0).
  542. */
  543. cond = ( X_is_negative ^ Y_is_negative );
  544. *ret = cond & X_is_negative;
  545. /*
  546. * This is a constant-time function. We might have the result, but we still
  547. * need to go through the loop. Record if we have the result already.
  548. */
  549. done = cond;
  550. for( i = X->n; i > 0; i-- )
  551. {
  552. /*
  553. * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
  554. * X and Y are negative.
  555. *
  556. * Again even if we can make a decision, we just mark the result and
  557. * the fact that we are done and continue looping.
  558. */
  559. cond = mbedtls_ct_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
  560. *ret |= cond & ( 1 - done ) & X_is_negative;
  561. done |= cond;
  562. /*
  563. * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
  564. * X and Y are positive.
  565. *
  566. * Again even if we can make a decision, we just mark the result and
  567. * the fact that we are done and continue looping.
  568. */
  569. cond = mbedtls_ct_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
  570. *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
  571. done |= cond;
  572. }
  573. return( 0 );
  574. }
  575. #endif /* MBEDTLS_BIGNUM_C */
  576. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  577. int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
  578. unsigned char *input,
  579. size_t ilen,
  580. unsigned char *output,
  581. size_t output_max_len,
  582. size_t *olen )
  583. {
  584. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  585. size_t i, plaintext_max_size;
  586. /* The following variables take sensitive values: their value must
  587. * not leak into the observable behavior of the function other than
  588. * the designated outputs (output, olen, return value). Otherwise
  589. * this would open the execution of the function to
  590. * side-channel-based variants of the Bleichenbacher padding oracle
  591. * attack. Potential side channels include overall timing, memory
  592. * access patterns (especially visible to an adversary who has access
  593. * to a shared memory cache), and branches (especially visible to
  594. * an adversary who has access to a shared code cache or to a shared
  595. * branch predictor). */
  596. size_t pad_count = 0;
  597. unsigned bad = 0;
  598. unsigned char pad_done = 0;
  599. size_t plaintext_size = 0;
  600. unsigned output_too_large;
  601. plaintext_max_size = ( output_max_len > ilen - 11 ) ? ilen - 11
  602. : output_max_len;
  603. /* Check and get padding length in constant time and constant
  604. * memory trace. The first byte must be 0. */
  605. bad |= input[0];
  606. if( mode == MBEDTLS_RSA_PRIVATE )
  607. {
  608. /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  609. * where PS must be at least 8 nonzero bytes. */
  610. bad |= input[1] ^ MBEDTLS_RSA_CRYPT;
  611. /* Read the whole buffer. Set pad_done to nonzero if we find
  612. * the 0x00 byte and remember the padding length in pad_count. */
  613. for( i = 2; i < ilen; i++ )
  614. {
  615. pad_done |= ((input[i] | (unsigned char)-input[i]) >> 7) ^ 1;
  616. pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
  617. }
  618. }
  619. else
  620. {
  621. /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
  622. * where PS must be at least 8 bytes with the value 0xFF. */
  623. bad |= input[1] ^ MBEDTLS_RSA_SIGN;
  624. /* Read the whole buffer. Set pad_done to nonzero if we find
  625. * the 0x00 byte and remember the padding length in pad_count.
  626. * If there's a non-0xff byte in the padding, the padding is bad. */
  627. for( i = 2; i < ilen; i++ )
  628. {
  629. pad_done |= mbedtls_ct_uint_if( input[i], 0, 1 );
  630. pad_count += mbedtls_ct_uint_if( pad_done, 0, 1 );
  631. bad |= mbedtls_ct_uint_if( pad_done, 0, input[i] ^ 0xFF );
  632. }
  633. }
  634. /* If pad_done is still zero, there's no data, only unfinished padding. */
  635. bad |= mbedtls_ct_uint_if( pad_done, 0, 1 );
  636. /* There must be at least 8 bytes of padding. */
  637. bad |= mbedtls_ct_size_gt( 8, pad_count );
  638. /* If the padding is valid, set plaintext_size to the number of
  639. * remaining bytes after stripping the padding. If the padding
  640. * is invalid, avoid leaking this fact through the size of the
  641. * output: use the maximum message size that fits in the output
  642. * buffer. Do it without branches to avoid leaking the padding
  643. * validity through timing. RSA keys are small enough that all the
  644. * size_t values involved fit in unsigned int. */
  645. plaintext_size = mbedtls_ct_uint_if(
  646. bad, (unsigned) plaintext_max_size,
  647. (unsigned) ( ilen - pad_count - 3 ) );
  648. /* Set output_too_large to 0 if the plaintext fits in the output
  649. * buffer and to 1 otherwise. */
  650. output_too_large = mbedtls_ct_size_gt( plaintext_size,
  651. plaintext_max_size );
  652. /* Set ret without branches to avoid timing attacks. Return:
  653. * - INVALID_PADDING if the padding is bad (bad != 0).
  654. * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  655. * plaintext does not fit in the output buffer.
  656. * - 0 if the padding is correct. */
  657. ret = - (int) mbedtls_ct_uint_if(
  658. bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
  659. mbedtls_ct_uint_if( output_too_large,
  660. - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
  661. 0 ) );
  662. /* If the padding is bad or the plaintext is too large, zero the
  663. * data that we're about to copy to the output buffer.
  664. * We need to copy the same amount of data
  665. * from the same buffer whether the padding is good or not to
  666. * avoid leaking the padding validity through overall timing or
  667. * through memory or cache access patterns. */
  668. bad = mbedtls_ct_uint_mask( bad | output_too_large );
  669. for( i = 11; i < ilen; i++ )
  670. input[i] &= ~bad;
  671. /* If the plaintext is too large, truncate it to the buffer size.
  672. * Copy anyway to avoid revealing the length through timing, because
  673. * revealing the length is as bad as revealing the padding validity
  674. * for a Bleichenbacher attack. */
  675. plaintext_size = mbedtls_ct_uint_if( output_too_large,
  676. (unsigned) plaintext_max_size,
  677. (unsigned) plaintext_size );
  678. /* Move the plaintext to the leftmost position where it can start in
  679. * the working buffer, i.e. make it start plaintext_max_size from
  680. * the end of the buffer. Do this with a memory access trace that
  681. * does not depend on the plaintext size. After this move, the
  682. * starting location of the plaintext is no longer sensitive
  683. * information. */
  684. mbedtls_ct_mem_move_to_left( input + ilen - plaintext_max_size,
  685. plaintext_max_size,
  686. plaintext_max_size - plaintext_size );
  687. /* Finally copy the decrypted plaintext plus trailing zeros into the output
  688. * buffer. If output_max_len is 0, then output may be an invalid pointer
  689. * and the result of memcpy() would be undefined; prevent undefined
  690. * behavior making sure to depend only on output_max_len (the size of the
  691. * user-provided output buffer), which is independent from plaintext
  692. * length, validity of padding, success of the decryption, and other
  693. * secrets. */
  694. if( output_max_len != 0 )
  695. memcpy( output, input + ilen - plaintext_max_size, plaintext_max_size );
  696. /* Report the amount of data we copied to the output buffer. In case
  697. * of errors (bad padding or output too large), the value of *olen
  698. * when this function returns is not specified. Making it equivalent
  699. * to the good case limits the risks of leaking the padding validity. */
  700. *olen = plaintext_size;
  701. return( ret );
  702. }
  703. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */