di_ops.c 8.3 KB

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