constant_time.c 27 KB

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