constant_time.c 27 KB

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