constant_time.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. #include "bignum_core.h"
  31. #endif
  32. #if defined(MBEDTLS_SSL_TLS_C)
  33. #include "ssl_misc.h"
  34. #endif
  35. #if defined(MBEDTLS_RSA_C)
  36. #include "mbedtls/rsa.h"
  37. #endif
  38. #if defined(MBEDTLS_BASE64_C)
  39. #include "constant_time_invasive.h"
  40. #endif
  41. #include <string.h>
  42. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  43. #define PSA_TO_MBEDTLS_ERR(status) PSA_TO_MBEDTLS_ERR_LIST(status, \
  44. psa_to_ssl_errors, \
  45. psa_generic_status_to_mbedtls)
  46. #endif
  47. /*
  48. * Define MBEDTLS_EFFICIENT_UNALIGNED_VOLATILE_ACCESS where assembly is present to
  49. * perform fast unaligned access to volatile data.
  50. *
  51. * This is needed because mbedtls_get_unaligned_uintXX etc don't support volatile
  52. * memory accesses.
  53. *
  54. * Some of these definitions could be moved into alignment.h but for now they are
  55. * only used here.
  56. */
  57. #if defined(MBEDTLS_EFFICIENT_UNALIGNED_ACCESS) && defined(MBEDTLS_HAVE_ASM)
  58. #if defined(__arm__) || defined(__thumb__) || defined(__thumb2__) || defined(__aarch64__)
  59. #define MBEDTLS_EFFICIENT_UNALIGNED_VOLATILE_ACCESS
  60. #endif
  61. #endif
  62. #if defined(MBEDTLS_EFFICIENT_UNALIGNED_VOLATILE_ACCESS)
  63. static inline uint32_t mbedtls_get_unaligned_volatile_uint32(volatile const unsigned char *p)
  64. {
  65. /* This is UB, even where it's safe:
  66. * return *((volatile uint32_t*)p);
  67. * so instead the same thing is expressed in assembly below.
  68. */
  69. uint32_t r;
  70. #if defined(__arm__) || defined(__thumb__) || defined(__thumb2__)
  71. asm volatile ("ldr %0, [%1]" : "=r" (r) : "r" (p) :);
  72. #elif defined(__aarch64__)
  73. asm volatile ("ldr %w0, [%1]" : "=r" (r) : "r" (p) :);
  74. #endif
  75. return r;
  76. }
  77. #endif /* MBEDTLS_EFFICIENT_UNALIGNED_VOLATILE_ACCESS */
  78. int mbedtls_ct_memcmp(const void *a,
  79. const void *b,
  80. size_t n)
  81. {
  82. size_t i = 0;
  83. /*
  84. * `A` and `B` are cast to volatile to ensure that the compiler
  85. * generates code that always fully reads both buffers.
  86. * Otherwise it could generate a test to exit early if `diff` has all
  87. * bits set early in the loop.
  88. */
  89. volatile const unsigned char *A = (volatile const unsigned char *) a;
  90. volatile const unsigned char *B = (volatile const unsigned char *) b;
  91. uint32_t diff = 0;
  92. #if defined(MBEDTLS_EFFICIENT_UNALIGNED_VOLATILE_ACCESS)
  93. for (; (i + 4) <= n; i += 4) {
  94. uint32_t x = mbedtls_get_unaligned_volatile_uint32(A + i);
  95. uint32_t y = mbedtls_get_unaligned_volatile_uint32(B + i);
  96. diff |= x ^ y;
  97. }
  98. #endif
  99. for (; i < n; i++) {
  100. /* Read volatile data in order before computing diff.
  101. * This avoids IAR compiler warning:
  102. * 'the order of volatile accesses is undefined ..' */
  103. unsigned char x = A[i], y = B[i];
  104. diff |= x ^ y;
  105. }
  106. return (int) diff;
  107. }
  108. unsigned mbedtls_ct_uint_mask(unsigned value)
  109. {
  110. /* MSVC has a warning about unary minus on unsigned, but this is
  111. * well-defined and precisely what we want to do here */
  112. #if defined(_MSC_VER)
  113. #pragma warning( push )
  114. #pragma warning( disable : 4146 )
  115. #endif
  116. return -((value | -value) >> (sizeof(value) * 8 - 1));
  117. #if defined(_MSC_VER)
  118. #pragma warning( pop )
  119. #endif
  120. }
  121. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  122. size_t mbedtls_ct_size_mask(size_t value)
  123. {
  124. /* MSVC has a warning about unary minus on unsigned integer types,
  125. * but this is well-defined and precisely what we want to do here. */
  126. #if defined(_MSC_VER)
  127. #pragma warning( push )
  128. #pragma warning( disable : 4146 )
  129. #endif
  130. return -((value | -value) >> (sizeof(value) * 8 - 1));
  131. #if defined(_MSC_VER)
  132. #pragma warning( pop )
  133. #endif
  134. }
  135. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
  136. #if defined(MBEDTLS_BIGNUM_C)
  137. mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask(mbedtls_mpi_uint value)
  138. {
  139. /* MSVC has a warning about unary minus on unsigned, but this is
  140. * well-defined and precisely what we want to do here */
  141. #if defined(_MSC_VER)
  142. #pragma warning( push )
  143. #pragma warning( disable : 4146 )
  144. #endif
  145. return -((value | -value) >> (sizeof(value) * 8 - 1));
  146. #if defined(_MSC_VER)
  147. #pragma warning( pop )
  148. #endif
  149. }
  150. #endif /* MBEDTLS_BIGNUM_C */
  151. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
  152. /** Constant-flow mask generation for "less than" comparison:
  153. * - if \p x < \p y, return all-bits 1, that is (size_t) -1
  154. * - otherwise, return all bits 0, that is 0
  155. *
  156. * This function can be used to write constant-time code by replacing branches
  157. * with bit operations using masks.
  158. *
  159. * \param x The first value to analyze.
  160. * \param y The second value to analyze.
  161. *
  162. * \return All-bits-one if \p x is less than \p y, otherwise zero.
  163. */
  164. static size_t mbedtls_ct_size_mask_lt(size_t x,
  165. size_t y)
  166. {
  167. /* This has the most significant bit set if and only if x < y */
  168. const size_t sub = x - y;
  169. /* sub1 = (x < y) ? 1 : 0 */
  170. const size_t sub1 = sub >> (sizeof(sub) * 8 - 1);
  171. /* mask = (x < y) ? 0xff... : 0x00... */
  172. const size_t mask = mbedtls_ct_size_mask(sub1);
  173. return mask;
  174. }
  175. size_t mbedtls_ct_size_mask_ge(size_t x,
  176. size_t y)
  177. {
  178. return ~mbedtls_ct_size_mask_lt(x, y);
  179. }
  180. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
  181. #if defined(MBEDTLS_BASE64_C)
  182. /* Return 0xff if low <= c <= high, 0 otherwise.
  183. *
  184. * Constant flow with respect to c.
  185. */
  186. MBEDTLS_STATIC_TESTABLE
  187. unsigned char mbedtls_ct_uchar_mask_of_range(unsigned char low,
  188. unsigned char high,
  189. unsigned char c)
  190. {
  191. /* low_mask is: 0 if low <= c, 0x...ff if low > c */
  192. unsigned low_mask = ((unsigned) c - low) >> 8;
  193. /* high_mask is: 0 if c <= high, 0x...ff if c > high */
  194. unsigned high_mask = ((unsigned) high - c) >> 8;
  195. return ~(low_mask | high_mask) & 0xff;
  196. }
  197. #endif /* MBEDTLS_BASE64_C */
  198. unsigned mbedtls_ct_size_bool_eq(size_t x,
  199. size_t y)
  200. {
  201. /* diff = 0 if x == y, non-zero otherwise */
  202. const size_t diff = x ^ y;
  203. /* MSVC has a warning about unary minus on unsigned integer types,
  204. * but this is well-defined and precisely what we want to do here. */
  205. #if defined(_MSC_VER)
  206. #pragma warning( push )
  207. #pragma warning( disable : 4146 )
  208. #endif
  209. /* diff_msb's most significant bit is equal to x != y */
  210. const size_t diff_msb = (diff | (size_t) -diff);
  211. #if defined(_MSC_VER)
  212. #pragma warning( pop )
  213. #endif
  214. /* diff1 = (x != y) ? 1 : 0 */
  215. const unsigned diff1 = diff_msb >> (sizeof(diff_msb) * 8 - 1);
  216. return 1 ^ diff1;
  217. }
  218. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  219. /** Constant-flow "greater than" comparison:
  220. * return x > y
  221. *
  222. * This is equivalent to \p x > \p y, but is likely to be compiled
  223. * to code using bitwise operation rather than a branch.
  224. *
  225. * \param x The first value to analyze.
  226. * \param y The second value to analyze.
  227. *
  228. * \return 1 if \p x greater than \p y, otherwise 0.
  229. */
  230. static unsigned mbedtls_ct_size_gt(size_t x,
  231. size_t y)
  232. {
  233. /* Return the sign bit (1 for negative) of (y - x). */
  234. return (y - x) >> (sizeof(size_t) * 8 - 1);
  235. }
  236. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
  237. #if defined(MBEDTLS_BIGNUM_C)
  238. unsigned mbedtls_ct_mpi_uint_lt(const mbedtls_mpi_uint x,
  239. const mbedtls_mpi_uint y)
  240. {
  241. mbedtls_mpi_uint ret;
  242. mbedtls_mpi_uint cond;
  243. /*
  244. * Check if the most significant bits (MSB) of the operands are different.
  245. */
  246. cond = (x ^ y);
  247. /*
  248. * If the MSB are the same then the difference x-y will be negative (and
  249. * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
  250. */
  251. ret = (x - y) & ~cond;
  252. /*
  253. * If the MSB are different, then the operand with the MSB of 1 is the
  254. * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
  255. * the MSB of y is 0.)
  256. */
  257. ret |= y & cond;
  258. ret = ret >> (sizeof(mbedtls_mpi_uint) * 8 - 1);
  259. return (unsigned) ret;
  260. }
  261. #endif /* MBEDTLS_BIGNUM_C */
  262. unsigned mbedtls_ct_uint_if(unsigned condition,
  263. unsigned if1,
  264. unsigned if0)
  265. {
  266. unsigned mask = mbedtls_ct_uint_mask(condition);
  267. return (mask & if1) | (~mask & if0);
  268. }
  269. #if defined(MBEDTLS_BIGNUM_C)
  270. /** Select between two sign values without branches.
  271. *
  272. * This is functionally equivalent to `condition ? if1 : if0` but uses only bit
  273. * operations in order to avoid branches.
  274. *
  275. * \note if1 and if0 must be either 1 or -1, otherwise the result
  276. * is undefined.
  277. *
  278. * \param condition Condition to test; must be either 0 or 1.
  279. * \param if1 The first sign; must be either +1 or -1.
  280. * \param if0 The second sign; must be either +1 or -1.
  281. *
  282. * \return \c if1 if \p condition is nonzero, otherwise \c if0.
  283. * */
  284. static int mbedtls_ct_cond_select_sign(unsigned char condition,
  285. int if1,
  286. int if0)
  287. {
  288. /* In order to avoid questions about what we can reasonably assume about
  289. * the representations of signed integers, move everything to unsigned
  290. * by taking advantage of the fact that if1 and if0 are either +1 or -1. */
  291. unsigned uif1 = if1 + 1;
  292. unsigned uif0 = if0 + 1;
  293. /* condition was 0 or 1, mask is 0 or 2 as are uif1 and uif0 */
  294. const unsigned mask = condition << 1;
  295. /* select uif1 or uif0 */
  296. unsigned ur = (uif0 & ~mask) | (uif1 & mask);
  297. /* ur is now 0 or 2, convert back to -1 or +1 */
  298. return (int) ur - 1;
  299. }
  300. void mbedtls_ct_mpi_uint_cond_assign(size_t n,
  301. mbedtls_mpi_uint *dest,
  302. const mbedtls_mpi_uint *src,
  303. unsigned char condition)
  304. {
  305. size_t i;
  306. /* MSVC has a warning about unary minus on unsigned integer types,
  307. * but this is well-defined and precisely what we want to do here. */
  308. #if defined(_MSC_VER)
  309. #pragma warning( push )
  310. #pragma warning( disable : 4146 )
  311. #endif
  312. /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
  313. const mbedtls_mpi_uint mask = -condition;
  314. #if defined(_MSC_VER)
  315. #pragma warning( pop )
  316. #endif
  317. for (i = 0; i < n; i++) {
  318. dest[i] = (src[i] & mask) | (dest[i] & ~mask);
  319. }
  320. }
  321. #endif /* MBEDTLS_BIGNUM_C */
  322. #if defined(MBEDTLS_BASE64_C)
  323. unsigned char mbedtls_ct_base64_enc_char(unsigned char value)
  324. {
  325. unsigned char digit = 0;
  326. /* For each range of values, if value is in that range, mask digit with
  327. * the corresponding value. Since value can only be in a single range,
  328. * only at most one masking will change digit. */
  329. digit |= mbedtls_ct_uchar_mask_of_range(0, 25, value) & ('A' + value);
  330. digit |= mbedtls_ct_uchar_mask_of_range(26, 51, value) & ('a' + value - 26);
  331. digit |= mbedtls_ct_uchar_mask_of_range(52, 61, value) & ('0' + value - 52);
  332. digit |= mbedtls_ct_uchar_mask_of_range(62, 62, value) & '+';
  333. digit |= mbedtls_ct_uchar_mask_of_range(63, 63, value) & '/';
  334. return digit;
  335. }
  336. signed char mbedtls_ct_base64_dec_value(unsigned char c)
  337. {
  338. unsigned char val = 0;
  339. /* For each range of digits, if c is in that range, mask val with
  340. * the corresponding value. Since c can only be in a single range,
  341. * only at most one masking will change val. Set val to one plus
  342. * the desired value so that it stays 0 if c is in none of the ranges. */
  343. val |= mbedtls_ct_uchar_mask_of_range('A', 'Z', c) & (c - 'A' + 0 + 1);
  344. val |= mbedtls_ct_uchar_mask_of_range('a', 'z', c) & (c - 'a' + 26 + 1);
  345. val |= mbedtls_ct_uchar_mask_of_range('0', '9', c) & (c - '0' + 52 + 1);
  346. val |= mbedtls_ct_uchar_mask_of_range('+', '+', c) & (c - '+' + 62 + 1);
  347. val |= mbedtls_ct_uchar_mask_of_range('/', '/', c) & (c - '/' + 63 + 1);
  348. /* At this point, val is 0 if c is an invalid digit and v+1 if c is
  349. * a digit with the value v. */
  350. return val - 1;
  351. }
  352. #endif /* MBEDTLS_BASE64_C */
  353. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  354. /** Shift some data towards the left inside a buffer.
  355. *
  356. * `mbedtls_ct_mem_move_to_left(start, total, offset)` is functionally
  357. * equivalent to
  358. * ```
  359. * memmove(start, start + offset, total - offset);
  360. * memset(start + offset, 0, total - offset);
  361. * ```
  362. * but it strives to use a memory access pattern (and thus total timing)
  363. * that does not depend on \p offset. This timing independence comes at
  364. * the expense of performance.
  365. *
  366. * \param start Pointer to the start of the buffer.
  367. * \param total Total size of the buffer.
  368. * \param offset Offset from which to copy \p total - \p offset bytes.
  369. */
  370. static void mbedtls_ct_mem_move_to_left(void *start,
  371. size_t total,
  372. size_t offset)
  373. {
  374. volatile unsigned char *buf = start;
  375. size_t i, n;
  376. if (total == 0) {
  377. return;
  378. }
  379. for (i = 0; i < total; i++) {
  380. unsigned no_op = mbedtls_ct_size_gt(total - offset, i);
  381. /* The first `total - offset` passes are a no-op. The last
  382. * `offset` passes shift the data one byte to the left and
  383. * zero out the last byte. */
  384. for (n = 0; n < total - 1; n++) {
  385. unsigned char current = buf[n];
  386. unsigned char next = buf[n+1];
  387. buf[n] = mbedtls_ct_uint_if(no_op, current, next);
  388. }
  389. buf[total-1] = mbedtls_ct_uint_if(no_op, buf[total-1], 0);
  390. }
  391. }
  392. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
  393. #if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
  394. void mbedtls_ct_memcpy_if_eq(unsigned char *dest,
  395. const unsigned char *src,
  396. size_t len,
  397. size_t c1,
  398. size_t c2)
  399. {
  400. /* mask = c1 == c2 ? 0xff : 0x00 */
  401. const size_t equal = mbedtls_ct_size_bool_eq(c1, c2);
  402. /* dest[i] = c1 == c2 ? src[i] : dest[i] */
  403. size_t i = 0;
  404. #if defined(MBEDTLS_EFFICIENT_UNALIGNED_ACCESS)
  405. const uint32_t mask32 = (uint32_t) mbedtls_ct_size_mask(equal);
  406. const unsigned char mask = (unsigned char) mask32 & 0xff;
  407. for (; (i + 4) <= len; i += 4) {
  408. uint32_t a = mbedtls_get_unaligned_uint32(src + i) & mask32;
  409. uint32_t b = mbedtls_get_unaligned_uint32(dest + i) & ~mask32;
  410. mbedtls_put_unaligned_uint32(dest + i, a | b);
  411. }
  412. #else
  413. const unsigned char mask = (unsigned char) mbedtls_ct_size_mask(equal);
  414. #endif /* MBEDTLS_EFFICIENT_UNALIGNED_ACCESS */
  415. for (; i < len; i++) {
  416. dest[i] = (src[i] & mask) | (dest[i] & ~mask);
  417. }
  418. }
  419. void mbedtls_ct_memcpy_offset(unsigned char *dest,
  420. const unsigned char *src,
  421. size_t offset,
  422. size_t offset_min,
  423. size_t offset_max,
  424. size_t len)
  425. {
  426. size_t offsetval;
  427. for (offsetval = offset_min; offsetval <= offset_max; offsetval++) {
  428. mbedtls_ct_memcpy_if_eq(dest, src + offsetval, len,
  429. offsetval, offset);
  430. }
  431. }
  432. #if defined(MBEDTLS_USE_PSA_CRYPTO)
  433. #if defined(PSA_WANT_ALG_SHA_384)
  434. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_384)
  435. #elif defined(PSA_WANT_ALG_SHA_256)
  436. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256)
  437. #else /* See check_config.h */
  438. #define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_1)
  439. #endif
  440. int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
  441. psa_algorithm_t mac_alg,
  442. const unsigned char *add_data,
  443. size_t add_data_len,
  444. const unsigned char *data,
  445. size_t data_len_secret,
  446. size_t min_data_len,
  447. size_t max_data_len,
  448. unsigned char *output)
  449. {
  450. /*
  451. * This function breaks the HMAC abstraction and uses psa_hash_clone()
  452. * extension in order to get constant-flow behaviour.
  453. *
  454. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  455. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  456. * patterns (see RFC 2104, sec. 2).
  457. *
  458. * We'll first compute ikey/okey, then inner_hash = HASH(ikey + msg) by
  459. * hashing up to minlen, then cloning the context, and for each byte up
  460. * to maxlen finishing up the hash computation, keeping only the
  461. * correct result.
  462. *
  463. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  464. */
  465. psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH(mac_alg);
  466. const size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
  467. unsigned char key_buf[MAX_HASH_BLOCK_LENGTH];
  468. const size_t hash_size = PSA_HASH_LENGTH(hash_alg);
  469. psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
  470. size_t hash_length;
  471. unsigned char aux_out[PSA_HASH_MAX_SIZE];
  472. psa_hash_operation_t aux_operation = PSA_HASH_OPERATION_INIT;
  473. size_t offset;
  474. psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
  475. size_t mac_key_length;
  476. size_t i;
  477. #define PSA_CHK(func_call) \
  478. do { \
  479. status = (func_call); \
  480. if (status != PSA_SUCCESS) \
  481. goto cleanup; \
  482. } while (0)
  483. /* Export MAC key
  484. * We assume key length is always exactly the output size
  485. * which is never more than the block size, thus we use block_size
  486. * as the key buffer size.
  487. */
  488. PSA_CHK(psa_export_key(key, key_buf, block_size, &mac_key_length));
  489. /* Calculate ikey */
  490. for (i = 0; i < mac_key_length; i++) {
  491. key_buf[i] = (unsigned char) (key_buf[i] ^ 0x36);
  492. }
  493. for (; i < block_size; ++i) {
  494. key_buf[i] = 0x36;
  495. }
  496. PSA_CHK(psa_hash_setup(&operation, hash_alg));
  497. /* Now compute inner_hash = HASH(ikey + msg) */
  498. PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
  499. PSA_CHK(psa_hash_update(&operation, add_data, add_data_len));
  500. PSA_CHK(psa_hash_update(&operation, data, min_data_len));
  501. /* Fill the hash buffer in advance with something that is
  502. * not a valid hash (barring an attack on the hash and
  503. * deliberately-crafted input), in case the caller doesn't
  504. * check the return status properly. */
  505. memset(output, '!', hash_size);
  506. /* For each possible length, compute the hash up to that point */
  507. for (offset = min_data_len; offset <= max_data_len; offset++) {
  508. PSA_CHK(psa_hash_clone(&operation, &aux_operation));
  509. PSA_CHK(psa_hash_finish(&aux_operation, aux_out,
  510. PSA_HASH_MAX_SIZE, &hash_length));
  511. /* Keep only the correct inner_hash in the output buffer */
  512. mbedtls_ct_memcpy_if_eq(output, aux_out, hash_size,
  513. offset, data_len_secret);
  514. if (offset < max_data_len) {
  515. PSA_CHK(psa_hash_update(&operation, data + offset, 1));
  516. }
  517. }
  518. /* Abort current operation to prepare for final operation */
  519. PSA_CHK(psa_hash_abort(&operation));
  520. /* Calculate okey */
  521. for (i = 0; i < mac_key_length; i++) {
  522. key_buf[i] = (unsigned char) ((key_buf[i] ^ 0x36) ^ 0x5C);
  523. }
  524. for (; i < block_size; ++i) {
  525. key_buf[i] = 0x5C;
  526. }
  527. /* Now compute HASH(okey + inner_hash) */
  528. PSA_CHK(psa_hash_setup(&operation, hash_alg));
  529. PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
  530. PSA_CHK(psa_hash_update(&operation, output, hash_size));
  531. PSA_CHK(psa_hash_finish(&operation, output, hash_size, &hash_length));
  532. #undef PSA_CHK
  533. cleanup:
  534. mbedtls_platform_zeroize(key_buf, MAX_HASH_BLOCK_LENGTH);
  535. mbedtls_platform_zeroize(aux_out, PSA_HASH_MAX_SIZE);
  536. psa_hash_abort(&operation);
  537. psa_hash_abort(&aux_operation);
  538. return PSA_TO_MBEDTLS_ERR(status);
  539. }
  540. #undef MAX_HASH_BLOCK_LENGTH
  541. #else
  542. int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
  543. const unsigned char *add_data,
  544. size_t add_data_len,
  545. const unsigned char *data,
  546. size_t data_len_secret,
  547. size_t min_data_len,
  548. size_t max_data_len,
  549. unsigned char *output)
  550. {
  551. /*
  552. * This function breaks the HMAC abstraction and uses the md_clone()
  553. * extension to the MD API in order to get constant-flow behaviour.
  554. *
  555. * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
  556. * concatenation, and okey/ikey are the XOR of the key with some fixed bit
  557. * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
  558. *
  559. * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
  560. * minlen, then cloning the context, and for each byte up to maxlen
  561. * finishing up the hash computation, keeping only the correct result.
  562. *
  563. * Then we only need to compute HASH(okey + inner_hash) and we're done.
  564. */
  565. const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
  566. /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
  567. * all of which have the same block size except SHA-384. */
  568. const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
  569. const unsigned char * const ikey = ctx->hmac_ctx;
  570. const unsigned char * const okey = ikey + block_size;
  571. const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
  572. unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
  573. mbedtls_md_context_t aux;
  574. size_t offset;
  575. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  576. mbedtls_md_init(&aux);
  577. #define MD_CHK(func_call) \
  578. do { \
  579. ret = (func_call); \
  580. if (ret != 0) \
  581. goto cleanup; \
  582. } while (0)
  583. MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
  584. /* After hmac_start() of hmac_reset(), ikey has already been hashed,
  585. * so we can start directly with the message */
  586. MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
  587. MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
  588. /* Fill the hash buffer in advance with something that is
  589. * not a valid hash (barring an attack on the hash and
  590. * deliberately-crafted input), in case the caller doesn't
  591. * check the return status properly. */
  592. memset(output, '!', hash_size);
  593. /* For each possible length, compute the hash up to that point */
  594. for (offset = min_data_len; offset <= max_data_len; offset++) {
  595. MD_CHK(mbedtls_md_clone(&aux, ctx));
  596. MD_CHK(mbedtls_md_finish(&aux, aux_out));
  597. /* Keep only the correct inner_hash in the output buffer */
  598. mbedtls_ct_memcpy_if_eq(output, aux_out, hash_size,
  599. offset, data_len_secret);
  600. if (offset < max_data_len) {
  601. MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
  602. }
  603. }
  604. /* The context needs to finish() before it starts() again */
  605. MD_CHK(mbedtls_md_finish(ctx, aux_out));
  606. /* Now compute HASH(okey + inner_hash) */
  607. MD_CHK(mbedtls_md_starts(ctx));
  608. MD_CHK(mbedtls_md_update(ctx, okey, block_size));
  609. MD_CHK(mbedtls_md_update(ctx, output, hash_size));
  610. MD_CHK(mbedtls_md_finish(ctx, output));
  611. /* Done, get ready for next time */
  612. MD_CHK(mbedtls_md_hmac_reset(ctx));
  613. #undef MD_CHK
  614. cleanup:
  615. mbedtls_md_free(&aux);
  616. return ret;
  617. }
  618. #endif /* MBEDTLS_USE_PSA_CRYPTO */
  619. #endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
  620. #if defined(MBEDTLS_BIGNUM_C)
  621. #define MPI_VALIDATE_RET(cond) \
  622. MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA)
  623. /*
  624. * Conditionally assign X = Y, without leaking information
  625. * about whether the assignment was made or not.
  626. * (Leaking information about the respective sizes of X and Y is ok however.)
  627. */
  628. #if defined(_MSC_VER) && defined(_M_ARM64) && (_MSC_FULL_VER < 193131103)
  629. /*
  630. * MSVC miscompiles this function if it's inlined prior to Visual Studio 2022 version 17.1. See:
  631. * https://developercommunity.visualstudio.com/t/c-compiler-miscompiles-part-of-mbedtls-library-on/1646989
  632. */
  633. __declspec(noinline)
  634. #endif
  635. int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
  636. const mbedtls_mpi *Y,
  637. unsigned char assign)
  638. {
  639. int ret = 0;
  640. MPI_VALIDATE_RET(X != NULL);
  641. MPI_VALIDATE_RET(Y != NULL);
  642. /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
  643. mbedtls_mpi_uint limb_mask = mbedtls_ct_mpi_uint_mask(assign);
  644. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
  645. X->s = mbedtls_ct_cond_select_sign(assign, Y->s, X->s);
  646. mbedtls_mpi_core_cond_assign(X->p, Y->p, Y->n, assign);
  647. for (size_t i = Y->n; i < X->n; i++) {
  648. X->p[i] &= ~limb_mask;
  649. }
  650. cleanup:
  651. return ret;
  652. }
  653. /*
  654. * Conditionally swap X and Y, without leaking information
  655. * about whether the swap was made or not.
  656. * Here it is not ok to simply swap the pointers, which would lead to
  657. * different memory access patterns when X and Y are used afterwards.
  658. */
  659. int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
  660. mbedtls_mpi *Y,
  661. unsigned char swap)
  662. {
  663. int ret = 0;
  664. int s;
  665. MPI_VALIDATE_RET(X != NULL);
  666. MPI_VALIDATE_RET(Y != NULL);
  667. if (X == Y) {
  668. return 0;
  669. }
  670. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
  671. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
  672. s = X->s;
  673. X->s = mbedtls_ct_cond_select_sign(swap, Y->s, X->s);
  674. Y->s = mbedtls_ct_cond_select_sign(swap, s, Y->s);
  675. mbedtls_mpi_core_cond_swap(X->p, Y->p, X->n, swap);
  676. cleanup:
  677. return ret;
  678. }
  679. /*
  680. * Compare unsigned values in constant time
  681. */
  682. unsigned mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,
  683. const mbedtls_mpi_uint *B,
  684. size_t limbs)
  685. {
  686. unsigned ret, cond, done;
  687. /* The value of any of these variables is either 0 or 1 for the rest of
  688. * their scope. */
  689. ret = cond = done = 0;
  690. for (size_t i = limbs; i > 0; i--) {
  691. /*
  692. * If B[i - 1] < A[i - 1] then A < B is false and the result must
  693. * remain 0.
  694. *
  695. * Again even if we can make a decision, we just mark the result and
  696. * the fact that we are done and continue looping.
  697. */
  698. cond = mbedtls_ct_mpi_uint_lt(B[i - 1], A[i - 1]);
  699. done |= cond;
  700. /*
  701. * If A[i - 1] < B[i - 1] then A < B is true.
  702. *
  703. * Again even if we can make a decision, we just mark the result and
  704. * the fact that we are done and continue looping.
  705. */
  706. cond = mbedtls_ct_mpi_uint_lt(A[i - 1], B[i - 1]);
  707. ret |= cond & (1 - done);
  708. done |= cond;
  709. }
  710. /*
  711. * If all the limbs were equal, then the numbers are equal, A < B is false
  712. * and leaving the result 0 is correct.
  713. */
  714. return ret;
  715. }
  716. /*
  717. * Compare signed values in constant time
  718. */
  719. int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X,
  720. const mbedtls_mpi *Y,
  721. unsigned *ret)
  722. {
  723. size_t i;
  724. /* The value of any of these variables is either 0 or 1 at all times. */
  725. unsigned cond, done, X_is_negative, Y_is_negative;
  726. MPI_VALIDATE_RET(X != NULL);
  727. MPI_VALIDATE_RET(Y != NULL);
  728. MPI_VALIDATE_RET(ret != NULL);
  729. if (X->n != Y->n) {
  730. return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  731. }
  732. /*
  733. * Set sign_N to 1 if N >= 0, 0 if N < 0.
  734. * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
  735. */
  736. X_is_negative = (X->s & 2) >> 1;
  737. Y_is_negative = (Y->s & 2) >> 1;
  738. /*
  739. * If the signs are different, then the positive operand is the bigger.
  740. * That is if X is negative (X_is_negative == 1), then X < Y is true and it
  741. * is false if X is positive (X_is_negative == 0).
  742. */
  743. cond = (X_is_negative ^ Y_is_negative);
  744. *ret = cond & X_is_negative;
  745. /*
  746. * This is a constant-time function. We might have the result, but we still
  747. * need to go through the loop. Record if we have the result already.
  748. */
  749. done = cond;
  750. for (i = X->n; i > 0; i--) {
  751. /*
  752. * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
  753. * X and Y are negative.
  754. *
  755. * Again even if we can make a decision, we just mark the result and
  756. * the fact that we are done and continue looping.
  757. */
  758. cond = mbedtls_ct_mpi_uint_lt(Y->p[i - 1], X->p[i - 1]);
  759. *ret |= cond & (1 - done) & X_is_negative;
  760. done |= cond;
  761. /*
  762. * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
  763. * X and Y are positive.
  764. *
  765. * Again even if we can make a decision, we just mark the result and
  766. * the fact that we are done and continue looping.
  767. */
  768. cond = mbedtls_ct_mpi_uint_lt(X->p[i - 1], Y->p[i - 1]);
  769. *ret |= cond & (1 - done) & (1 - X_is_negative);
  770. done |= cond;
  771. }
  772. return 0;
  773. }
  774. #endif /* MBEDTLS_BIGNUM_C */
  775. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  776. int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
  777. size_t ilen,
  778. unsigned char *output,
  779. size_t output_max_len,
  780. size_t *olen)
  781. {
  782. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  783. size_t i, plaintext_max_size;
  784. /* The following variables take sensitive values: their value must
  785. * not leak into the observable behavior of the function other than
  786. * the designated outputs (output, olen, return value). Otherwise
  787. * this would open the execution of the function to
  788. * side-channel-based variants of the Bleichenbacher padding oracle
  789. * attack. Potential side channels include overall timing, memory
  790. * access patterns (especially visible to an adversary who has access
  791. * to a shared memory cache), and branches (especially visible to
  792. * an adversary who has access to a shared code cache or to a shared
  793. * branch predictor). */
  794. size_t pad_count = 0;
  795. unsigned bad = 0;
  796. unsigned char pad_done = 0;
  797. size_t plaintext_size = 0;
  798. unsigned output_too_large;
  799. plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
  800. : output_max_len;
  801. /* Check and get padding length in constant time and constant
  802. * memory trace. The first byte must be 0. */
  803. bad |= input[0];
  804. /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  805. * where PS must be at least 8 nonzero bytes. */
  806. bad |= input[1] ^ MBEDTLS_RSA_CRYPT;
  807. /* Read the whole buffer. Set pad_done to nonzero if we find
  808. * the 0x00 byte and remember the padding length in pad_count. */
  809. for (i = 2; i < ilen; i++) {
  810. pad_done |= ((input[i] | (unsigned char) -input[i]) >> 7) ^ 1;
  811. pad_count += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
  812. }
  813. /* If pad_done is still zero, there's no data, only unfinished padding. */
  814. bad |= mbedtls_ct_uint_if(pad_done, 0, 1);
  815. /* There must be at least 8 bytes of padding. */
  816. bad |= mbedtls_ct_size_gt(8, pad_count);
  817. /* If the padding is valid, set plaintext_size to the number of
  818. * remaining bytes after stripping the padding. If the padding
  819. * is invalid, avoid leaking this fact through the size of the
  820. * output: use the maximum message size that fits in the output
  821. * buffer. Do it without branches to avoid leaking the padding
  822. * validity through timing. RSA keys are small enough that all the
  823. * size_t values involved fit in unsigned int. */
  824. plaintext_size = mbedtls_ct_uint_if(
  825. bad, (unsigned) plaintext_max_size,
  826. (unsigned) (ilen - pad_count - 3));
  827. /* Set output_too_large to 0 if the plaintext fits in the output
  828. * buffer and to 1 otherwise. */
  829. output_too_large = mbedtls_ct_size_gt(plaintext_size,
  830. plaintext_max_size);
  831. /* Set ret without branches to avoid timing attacks. Return:
  832. * - INVALID_PADDING if the padding is bad (bad != 0).
  833. * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  834. * plaintext does not fit in the output buffer.
  835. * - 0 if the padding is correct. */
  836. ret = -(int) mbedtls_ct_uint_if(
  837. bad, -MBEDTLS_ERR_RSA_INVALID_PADDING,
  838. mbedtls_ct_uint_if(output_too_large,
  839. -MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
  840. 0));
  841. /* If the padding is bad or the plaintext is too large, zero the
  842. * data that we're about to copy to the output buffer.
  843. * We need to copy the same amount of data
  844. * from the same buffer whether the padding is good or not to
  845. * avoid leaking the padding validity through overall timing or
  846. * through memory or cache access patterns. */
  847. bad = mbedtls_ct_uint_mask(bad | output_too_large);
  848. for (i = 11; i < ilen; i++) {
  849. input[i] &= ~bad;
  850. }
  851. /* If the plaintext is too large, truncate it to the buffer size.
  852. * Copy anyway to avoid revealing the length through timing, because
  853. * revealing the length is as bad as revealing the padding validity
  854. * for a Bleichenbacher attack. */
  855. plaintext_size = mbedtls_ct_uint_if(output_too_large,
  856. (unsigned) plaintext_max_size,
  857. (unsigned) plaintext_size);
  858. /* Move the plaintext to the leftmost position where it can start in
  859. * the working buffer, i.e. make it start plaintext_max_size from
  860. * the end of the buffer. Do this with a memory access trace that
  861. * does not depend on the plaintext size. After this move, the
  862. * starting location of the plaintext is no longer sensitive
  863. * information. */
  864. mbedtls_ct_mem_move_to_left(input + ilen - plaintext_max_size,
  865. plaintext_max_size,
  866. plaintext_max_size - plaintext_size);
  867. /* Finally copy the decrypted plaintext plus trailing zeros into the output
  868. * buffer. If output_max_len is 0, then output may be an invalid pointer
  869. * and the result of memcpy() would be undefined; prevent undefined
  870. * behavior making sure to depend only on output_max_len (the size of the
  871. * user-provided output buffer), which is independent from plaintext
  872. * length, validity of padding, success of the decryption, and other
  873. * secrets. */
  874. if (output_max_len != 0) {
  875. memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
  876. }
  877. /* Report the amount of data we copied to the output buffer. In case
  878. * of errors (bad padding or output too large), the value of *olen
  879. * when this function returns is not specified. Making it equivalent
  880. * to the good case limits the risks of leaking the padding validity. */
  881. *olen = plaintext_size;
  882. return ret;
  883. }
  884. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */