di_ops.c 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /* Copyright (c) 2011-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file di_ops.c
  5. * \brief Functions for data-independent operations.
  6. **/
  7. #include "orconfig.h"
  8. #include "lib/ctime/di_ops.h"
  9. #include "lib/err/torerr.h"
  10. #include "lib/malloc/malloc.h"
  11. #include <string.h>
  12. /**
  13. * Timing-safe version of memcmp. As memcmp, compare the <b>sz</b> bytes at
  14. * <b>a</b> with the <b>sz</b> bytes at <b>b</b>, and return less than 0 if
  15. * the bytes at <b>a</b> lexically precede those at <b>b</b>, 0 if the byte
  16. * ranges are equal, and greater than zero if the bytes at <b>a</b> lexically
  17. * follow those at <b>b</b>.
  18. *
  19. * This implementation differs from memcmp in that its timing behavior is not
  20. * data-dependent: it should return in the same amount of time regardless of
  21. * the contents of <b>a</b> and <b>b</b>.
  22. */
  23. int
  24. tor_memcmp(const void *a, const void *b, size_t len)
  25. {
  26. #ifdef HAVE_TIMINGSAFE_MEMCMP
  27. return timingsafe_memcmp(a, b, len);
  28. #else
  29. const uint8_t *x = a;
  30. const uint8_t *y = b;
  31. size_t i = len;
  32. int retval = 0;
  33. /* This loop goes from the end of the arrays to the start. At the
  34. * start of every iteration, before we decrement i, we have set
  35. * "retval" equal to the result of memcmp(a+i,b+i,len-i). During the
  36. * loop, we update retval by leaving it unchanged if x[i]==y[i] and
  37. * setting it to x[i]-y[i] if x[i]!= y[i].
  38. *
  39. * The following assumes we are on a system with two's-complement
  40. * arithmetic. We check for this at configure-time with the check
  41. * that sets USING_TWOS_COMPLEMENT. If we aren't two's complement, then
  42. * torint.h will stop compilation with an error.
  43. */
  44. while (i--) {
  45. int v1 = x[i];
  46. int v2 = y[i];
  47. int equal_p = v1 ^ v2;
  48. /* The following sets bits 8 and above of equal_p to 'equal_p ==
  49. * 0', and thus to v1 == v2. (To see this, note that if v1 ==
  50. * v2, then v1^v2 == equal_p == 0, so equal_p-1 == -1, which is the
  51. * same as ~0 on a two's-complement machine. Then note that if
  52. * v1 != v2, then 0 < v1 ^ v2 < 256, so 0 <= equal_p - 1 < 255.)
  53. */
  54. --equal_p;
  55. equal_p >>= 8;
  56. /* Thanks to (sign-preserving) arithmetic shift, equal_p is now
  57. * equal to -(v1 == v2), which is exactly what we need below.
  58. * (Since we're assuming two's-complement arithmetic, -1 is the
  59. * same as ~0 (all bits set).)
  60. *
  61. * (The result of an arithmetic shift on a negative value is
  62. * actually implementation-defined in standard C. So how do we
  63. * get away with assuming it? Easy. We check.) */
  64. #if ((-60 >> 8) != -1)
  65. #error "According to cpp, right-shift doesn't perform sign-extension."
  66. #endif
  67. #ifndef RSHIFT_DOES_SIGN_EXTEND
  68. #error "According to configure, right-shift doesn't perform sign-extension."
  69. #endif
  70. /* If v1 == v2, equal_p is ~0, so this will leave retval
  71. * unchanged; otherwise, equal_p is 0, so this will zero it. */
  72. retval &= equal_p;
  73. /* If v1 == v2, then this adds 0, and leaves retval unchanged.
  74. * Otherwise, we just zeroed retval, so this sets it to v1 - v2. */
  75. retval += (v1 - v2);
  76. /* There. Now retval is equal to its previous value if v1 == v2, and
  77. * equal to v1 - v2 if v1 != v2. */
  78. }
  79. return retval;
  80. #endif /* defined(HAVE_TIMINGSAFE_MEMCMP) */
  81. }
  82. /**
  83. * Timing-safe memory comparison. Return true if the <b>sz</b> bytes at
  84. * <b>a</b> are the same as the <b>sz</b> bytes at <b>b</b>, and 0 otherwise.
  85. *
  86. * This implementation differs from !memcmp(a,b,sz) in that its timing
  87. * behavior is not data-dependent: it should return in the same amount of time
  88. * regardless of the contents of <b>a</b> and <b>b</b>. It differs from
  89. * !tor_memcmp(a,b,sz) by being faster.
  90. */
  91. int
  92. tor_memeq(const void *a, const void *b, size_t sz)
  93. {
  94. /* Treat a and b as byte ranges. */
  95. const uint8_t *ba = a, *bb = b;
  96. uint32_t any_difference = 0;
  97. while (sz--) {
  98. /* Set byte_diff to all of those bits that are different in *ba and *bb,
  99. * and advance both ba and bb. */
  100. const uint8_t byte_diff = *ba++ ^ *bb++;
  101. /* Set bits in any_difference if they are set in byte_diff. */
  102. any_difference |= byte_diff;
  103. }
  104. /* Now any_difference is 0 if there are no bits different between
  105. * a and b, and is nonzero if there are bits different between a
  106. * and b. Now for paranoia's sake, let's convert it to 0 or 1.
  107. *
  108. * (If we say "!any_difference", the compiler might get smart enough
  109. * to optimize-out our data-independence stuff above.)
  110. *
  111. * To unpack:
  112. *
  113. * If any_difference == 0:
  114. * any_difference - 1 == ~0
  115. * (any_difference - 1) >> 8 == 0x00ffffff
  116. * 1 & ((any_difference - 1) >> 8) == 1
  117. *
  118. * If any_difference != 0:
  119. * 0 < any_difference < 256, so
  120. * 0 <= any_difference - 1 < 255
  121. * (any_difference - 1) >> 8 == 0
  122. * 1 & ((any_difference - 1) >> 8) == 0
  123. */
  124. /*coverity[overflow]*/
  125. return 1 & ((any_difference - 1) >> 8);
  126. }
  127. /* Implement di_digest256_map_t as a linked list of entries. */
  128. struct di_digest256_map_t {
  129. struct di_digest256_map_t *next;
  130. uint8_t key[32];
  131. void *val;
  132. };
  133. /** Release all storage held in <b>map</b>, calling free_fn on each value
  134. * as we go. */
  135. void
  136. dimap_free_(di_digest256_map_t *map, dimap_free_fn free_fn)
  137. {
  138. while (map) {
  139. di_digest256_map_t *victim = map;
  140. map = map->next;
  141. if (free_fn)
  142. free_fn(victim->val);
  143. tor_free(victim);
  144. }
  145. }
  146. /** Adjust the map at *<b>map</b>, adding an entry for <b>key</b> ->
  147. * <b>val</b>, where <b>key</b> is a DIGEST256_LEN-byte key.
  148. *
  149. * The caller MUST NOT add a key that already appears in the map.
  150. */
  151. void
  152. dimap_add_entry(di_digest256_map_t **map,
  153. const uint8_t *key, void *val)
  154. {
  155. di_digest256_map_t *new_ent;
  156. {
  157. void *old_val = dimap_search(*map, key, NULL);
  158. raw_assert(! old_val);
  159. raw_assert(val);
  160. }
  161. new_ent = tor_malloc_zero(sizeof(di_digest256_map_t));
  162. new_ent->next = *map;
  163. memcpy(new_ent->key, key, 32);
  164. new_ent->val = val;
  165. *map = new_ent;
  166. }
  167. /** Search the map at <b>map</b> for an entry whose key is <b>key</b> (a
  168. * DIGEST256_LEN-byte key) returning the corresponding value if we found one,
  169. * and returning <b>dflt_val</b> if the key wasn't found.
  170. *
  171. * This operation takes an amount of time dependent only on the length of
  172. * <b>map</b>, not on the position or presence of <b>key</b> within <b>map</b>.
  173. */
  174. void *
  175. dimap_search(const di_digest256_map_t *map, const uint8_t *key,
  176. void *dflt_val)
  177. {
  178. uintptr_t result = (uintptr_t)dflt_val;
  179. while (map) {
  180. uintptr_t r = (uintptr_t) tor_memeq(map->key, key, 32);
  181. r -= 1; /* Now r is (uintptr_t)-1 if memeq returned false, and
  182. * 0 if memeq returned true. */
  183. result &= r;
  184. result |= ((uintptr_t)(map->val)) & ~r;
  185. map = map->next;
  186. }
  187. return (void *)result;
  188. }
  189. /**
  190. * Return true iff the <b>sz</b> bytes at <b>mem</b> are all zero. Runs in
  191. * time independent of the contents of <b>mem</b>.
  192. */
  193. int
  194. safe_mem_is_zero(const void *mem, size_t sz)
  195. {
  196. uint32_t total = 0;
  197. const uint8_t *ptr = mem;
  198. while (sz--) {
  199. total |= *ptr++;
  200. }
  201. /*coverity[overflow]*/
  202. return 1 & ((total - 1) >> 8);
  203. }
  204. /** Time-invariant 64-bit greater-than; works on two integers in the range
  205. * (0,INT64_MAX). */
  206. #if SIZEOF_VOID_P == 8
  207. #define gt_i64_timei(a,b) ((a) > (b))
  208. #else
  209. static inline int
  210. gt_i64_timei(uint64_t a, uint64_t b)
  211. {
  212. int64_t diff = (int64_t) (b - a);
  213. int res = diff >> 63;
  214. return res & 1;
  215. }
  216. #endif /* SIZEOF_VOID_P == 8 */
  217. /**
  218. * Given an array of list of <b>n_entries</b> uint64_t values, whose sum is
  219. * <b>total</b>, find the first i such that the total of all elements 0...i is
  220. * greater than rand_val.
  221. *
  222. * Try to perform this operation in a constant-time way.
  223. */
  224. int
  225. select_array_member_cumulative_timei(const uint64_t *entries, int n_entries,
  226. uint64_t total, uint64_t rand_val)
  227. {
  228. int i, i_chosen=-1, n_chosen=0;
  229. uint64_t total_so_far = 0;
  230. for (i = 0; i < n_entries; ++i) {
  231. total_so_far += entries[i];
  232. if (gt_i64_timei(total_so_far, rand_val)) {
  233. i_chosen = i;
  234. n_chosen++;
  235. /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
  236. * the time we spend in the loop does not leak which element we chose. */
  237. rand_val = INT64_MAX;
  238. }
  239. }
  240. raw_assert(total_so_far == total);
  241. raw_assert(n_chosen == 1);
  242. raw_assert(i_chosen >= 0);
  243. raw_assert(i_chosen < n_entries);
  244. return i_chosen;
  245. }