You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

425 rivejä
13 KiB

  1. /* Jitter RNG: Noise Sources
  2. *
  3. * Copyright (C) 2021 - 2022, Stephan Mueller <smueller@chronox.de>
  4. *
  5. * License: see LICENSE file in root directory
  6. *
  7. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  8. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  9. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
  10. * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
  11. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  12. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  13. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  14. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  15. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  16. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  17. * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
  18. * DAMAGE.
  19. */
  20. #include "jitterentropy-noise.h"
  21. #include "jitterentropy-health.h"
  22. #include "jitterentropy-timer.h"
  23. #include "jitterentropy-sha3.h"
  24. #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
  25. /***************************************************************************
  26. * Noise sources
  27. ***************************************************************************/
  28. /**
  29. * Update of the loop count used for the next round of
  30. * an entropy collection.
  31. *
  32. * @ec [in] entropy collector struct
  33. * @bits [in] is the number of low bits of the timer to consider
  34. * @min [in] is the number of bits we shift the timer value to the right at
  35. * the end to make sure we have a guaranteed minimum value
  36. *
  37. * @return Newly calculated loop counter
  38. */
  39. static uint64_t jent_loop_shuffle(struct rand_data *ec,
  40. unsigned int bits, unsigned int min)
  41. {
  42. #ifdef JENT_CONF_DISABLE_LOOP_SHUFFLE
  43. (void)ec;
  44. (void)bits;
  45. return (UINT64_C(1)<<min);
  46. #else /* JENT_CONF_DISABLE_LOOP_SHUFFLE */
  47. uint64_t time = 0;
  48. uint64_t shuffle = 0;
  49. uint64_t mask = (UINT64_C(1)<<bits) - 1;
  50. unsigned int i = 0;
  51. /*
  52. * Mix the current state of the random number into the shuffle
  53. * calculation to balance that shuffle a bit more.
  54. */
  55. jent_get_nstime_internal(ec, &time);
  56. /*
  57. * We fold the time value as much as possible to ensure that as many
  58. * bits of the time stamp are included as possible.
  59. */
  60. for (i = 0; (((sizeof(time) << 3) + bits - 1) / bits) > i; i++) {
  61. shuffle ^= time & mask;
  62. time = time >> bits;
  63. }
  64. /*
  65. * We add a lower boundary value to ensure we have a minimum
  66. * RNG loop count.
  67. */
  68. return (shuffle + (UINT64_C(1)<<min));
  69. #endif /* JENT_CONF_DISABLE_LOOP_SHUFFLE */
  70. }
  71. /**
  72. * CPU Jitter noise source -- this is the noise source based on the CPU
  73. * execution time jitter
  74. *
  75. * This function injects the individual bits of the time value into the
  76. * entropy pool using a hash.
  77. *
  78. * @ec [in] entropy collector struct
  79. * @time [in] time delta to be injected
  80. * @loop_cnt [in] if a value not equal to 0 is set, use the given value as
  81. * number of loops to perform the hash operation
  82. * @stuck [in] Is the time delta identified as stuck?
  83. *
  84. * Output:
  85. * updated hash context
  86. */
  87. static void jent_hash_time(struct rand_data *ec, uint64_t time,
  88. uint64_t loop_cnt, unsigned int stuck)
  89. {
  90. HASH_CTX_ON_STACK(ctx);
  91. uint8_t intermediary[SHA3_256_SIZE_DIGEST];
  92. uint64_t j = 0;
  93. #define MAX_HASH_LOOP 3
  94. #define MIN_HASH_LOOP 0
  95. /* Ensure that macros cannot overflow jent_loop_shuffle() */
  96. BUILD_BUG_ON((MAX_HASH_LOOP + MIN_HASH_LOOP) > 63);
  97. uint64_t hash_loop_cnt =
  98. jent_loop_shuffle(ec, MAX_HASH_LOOP, MIN_HASH_LOOP);
  99. /* Use the memset to shut up valgrind */
  100. memset(intermediary, 0, sizeof(intermediary));
  101. sha3_256_init(&ctx);
  102. /*
  103. * testing purposes -- allow test app to set the counter, not
  104. * needed during runtime
  105. */
  106. if (loop_cnt)
  107. hash_loop_cnt = loop_cnt;
  108. /*
  109. * This loop fills a buffer which is injected into the entropy pool.
  110. * The main reason for this loop is to execute something over which we
  111. * can perform a timing measurement. The injection of the resulting
  112. * data into the pool is performed to ensure the result is used and
  113. * the compiler cannot optimize the loop away in case the result is not
  114. * used at all. Yet that data is considered "additional information"
  115. * considering the terminology from SP800-90A without any entropy.
  116. *
  117. * Note, it does not matter which or how much data you inject, we are
  118. * interested in one Keccack1600 compression operation performed with
  119. * the sha3_final.
  120. */
  121. for (j = 0; j < hash_loop_cnt; j++) {
  122. sha3_update(&ctx, intermediary, sizeof(intermediary));
  123. sha3_update(&ctx, (uint8_t *)&ec->rct_count,
  124. sizeof(ec->rct_count));
  125. sha3_update(&ctx, (uint8_t *)&ec->apt_cutoff,
  126. sizeof(ec->apt_cutoff));
  127. sha3_update(&ctx, (uint8_t *)&ec->apt_observations,
  128. sizeof(ec->apt_observations));
  129. sha3_update(&ctx, (uint8_t *)&ec->apt_count,
  130. sizeof(ec->apt_count));
  131. sha3_update(&ctx,(uint8_t *) &ec->apt_base,
  132. sizeof(ec->apt_base));
  133. sha3_update(&ctx, (uint8_t *)&j, sizeof(uint64_t));
  134. sha3_final(&ctx, intermediary);
  135. }
  136. /*
  137. * Inject the data from the previous loop into the pool. This data is
  138. * not considered to contain any entropy, but it stirs the pool a bit.
  139. */
  140. sha3_update(ec->hash_state, intermediary, sizeof(intermediary));
  141. /*
  142. * Insert the time stamp into the hash context representing the pool.
  143. *
  144. * If the time stamp is stuck, do not finally insert the value into the
  145. * entropy pool. Although this operation should not do any harm even
  146. * when the time stamp has no entropy, SP800-90B requires that any
  147. * conditioning operation to have an identical amount of input data
  148. * according to section 3.1.5.
  149. */
  150. if (!stuck)
  151. sha3_update(ec->hash_state, (uint8_t *)&time, sizeof(uint64_t));
  152. jent_memset_secure(&ctx, SHA_MAX_CTX_SIZE);
  153. jent_memset_secure(intermediary, sizeof(intermediary));
  154. }
  155. #define MAX_ACC_LOOP_BIT 7
  156. #define MIN_ACC_LOOP_BIT 0
  157. #ifdef JENT_RANDOM_MEMACCESS
  158. static inline uint32_t uint32rotl(const uint32_t x, int k)
  159. {
  160. return (x << k) | (x >> (32 - k));
  161. }
  162. static inline uint32_t xoshiro128starstar(uint32_t *s)
  163. {
  164. const uint32_t result = uint32rotl(s[1] * 5, 7) * 9;
  165. const uint32_t t = s[1] << 9;
  166. s[2] ^= s[0];
  167. s[3] ^= s[1];
  168. s[1] ^= s[2];
  169. s[0] ^= s[3];
  170. s[2] ^= t;
  171. s[3] = uint32rotl(s[3], 11);
  172. return result;
  173. }
  174. static void jent_memaccess(struct rand_data *ec, uint64_t loop_cnt)
  175. {
  176. uint64_t i = 0, time = 0;
  177. union {
  178. uint32_t u[4];
  179. uint8_t b[sizeof(uint32_t) * 4];
  180. } prngState = { .u = {0x8e93eec0, 0xce65608a, 0xa8d46b46, 0xe83cef69} };
  181. uint32_t addressMask;
  182. /* Ensure that macros cannot overflow jent_loop_shuffle() */
  183. BUILD_BUG_ON((MAX_ACC_LOOP_BIT + MIN_ACC_LOOP_BIT) > 63);
  184. uint64_t acc_loop_cnt =
  185. jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
  186. if (NULL == ec || NULL == ec->mem)
  187. return;
  188. addressMask = ec->memmask;
  189. /*
  190. * Mix the current data into prngState
  191. *
  192. * Any time you see a PRNG in a noise source, you should be concerned.
  193. *
  194. * The PRNG doesn’t directly produce the raw noise, it just adjusts the
  195. * location being updated. The timing of the update is part of the raw
  196. * sample. The main thing this process gets you isn’t better
  197. * “per-update” timing, it gets you mostly independent “per-update”
  198. * timing, so we can now benefit from the Central Limit Theorem!
  199. */
  200. for (i = 0; i < sizeof(prngState); i++) {
  201. jent_get_nstime_internal(ec, &time);
  202. prngState.b[i] ^= (uint8_t)(time & 0xff);
  203. }
  204. /*
  205. * testing purposes -- allow test app to set the counter, not
  206. * needed during runtime
  207. */
  208. if (loop_cnt)
  209. acc_loop_cnt = loop_cnt;
  210. for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
  211. /* Take PRNG output to find the memory location to update. */
  212. unsigned char *tmpval = ec->mem +
  213. (xoshiro128starstar(prngState.u) &
  214. addressMask);
  215. /*
  216. * memory access: just add 1 to one byte,
  217. * wrap at 255 -- memory access implies read
  218. * from and write to memory location
  219. */
  220. *tmpval = (unsigned char)((*tmpval + 1) & 0xff);
  221. }
  222. }
  223. #else /* JENT_RANDOM_MEMACCESS */
  224. /**
  225. * Memory Access noise source -- this is a noise source based on variations in
  226. * memory access times
  227. *
  228. * This function performs memory accesses which will add to the timing
  229. * variations due to an unknown amount of CPU wait states that need to be
  230. * added when accessing memory. The memory size should be larger than the L1
  231. * caches as outlined in the documentation and the associated testing.
  232. *
  233. * The L1 cache has a very high bandwidth, albeit its access rate is usually
  234. * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
  235. * variations as the CPU has hardly to wait. Starting with L2, significant
  236. * variations are added because L2 typically does not belong to the CPU any more
  237. * and therefore a wider range of CPU wait states is necessary for accesses.
  238. * L3 and real memory accesses have even a wider range of wait states. However,
  239. * to reliably access either L3 or memory, the ec->mem memory must be quite
  240. * large which is usually not desirable.
  241. *
  242. * @ec [in] Reference to the entropy collector with the memory access data -- if
  243. * the reference to the memory block to be accessed is NULL, this noise
  244. * source is disabled
  245. * @loop_cnt [in] if a value not equal to 0 is set, use the given value as
  246. * number of loops to perform the hash operation
  247. */
  248. static void jent_memaccess(struct rand_data *ec, uint64_t loop_cnt)
  249. {
  250. unsigned int wrap = 0;
  251. uint64_t i = 0;
  252. /* Ensure that macros cannot overflow jent_loop_shuffle() */
  253. BUILD_BUG_ON((MAX_ACC_LOOP_BIT + MIN_ACC_LOOP_BIT) > 63);
  254. uint64_t acc_loop_cnt =
  255. jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
  256. if (NULL == ec || NULL == ec->mem)
  257. return;
  258. wrap = ec->memblocksize * ec->memblocks;
  259. /*
  260. * testing purposes -- allow test app to set the counter, not
  261. * needed during runtime
  262. */
  263. if (loop_cnt)
  264. acc_loop_cnt = loop_cnt;
  265. for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
  266. unsigned char *tmpval = ec->mem + ec->memlocation;
  267. /*
  268. * memory access: just add 1 to one byte,
  269. * wrap at 255 -- memory access implies read
  270. * from and write to memory location
  271. */
  272. *tmpval = (unsigned char)((*tmpval + 1) & 0xff);
  273. /*
  274. * Addition of memblocksize - 1 to pointer
  275. * with wrap around logic to ensure that every
  276. * memory location is hit evenly
  277. */
  278. ec->memlocation = ec->memlocation + ec->memblocksize - 1;
  279. ec->memlocation = ec->memlocation % wrap;
  280. }
  281. }
  282. #endif /* JENT_RANDOM_MEMACCESS */
  283. /***************************************************************************
  284. * Start of entropy processing logic
  285. ***************************************************************************/
  286. /**
  287. * This is the heart of the entropy generation: calculate time deltas and
  288. * use the CPU jitter in the time deltas. The jitter is injected into the
  289. * entropy pool.
  290. *
  291. * WARNING: ensure that ->prev_time is primed before using the output
  292. * of this function! This can be done by calling this function
  293. * and not using its result.
  294. *
  295. * @ec [in] Reference to entropy collector
  296. * @loop_cnt [in] see jent_hash_time
  297. * @ret_current_delta [out] Test interface: return time delta - may be NULL
  298. *
  299. * @return: result of stuck test
  300. */
  301. unsigned int jent_measure_jitter(struct rand_data *ec,
  302. uint64_t loop_cnt,
  303. uint64_t *ret_current_delta)
  304. {
  305. uint64_t time = 0;
  306. uint64_t current_delta = 0;
  307. unsigned int stuck;
  308. /* Invoke one noise source before time measurement to add variations */
  309. jent_memaccess(ec, loop_cnt);
  310. /*
  311. * Get time stamp and calculate time delta to previous
  312. * invocation to measure the timing variations
  313. */
  314. jent_get_nstime_internal(ec, &time);
  315. current_delta = jent_delta(ec->prev_time, time) /
  316. ec->jent_common_timer_gcd;
  317. ec->prev_time = time;
  318. /* Check whether we have a stuck measurement. */
  319. stuck = jent_stuck(ec, current_delta);
  320. /* Now call the next noise sources which also injects the data */
  321. jent_hash_time(ec, current_delta, loop_cnt, stuck);
  322. /* return the raw entropy value */
  323. if (ret_current_delta)
  324. *ret_current_delta = current_delta;
  325. return stuck;
  326. }
  327. /**
  328. * Generator of one 256 bit random number
  329. * Function fills rand_data->hash_state
  330. *
  331. * @ec [in] Reference to entropy collector
  332. */
  333. void jent_random_data(struct rand_data *ec)
  334. {
  335. unsigned int k = 0, safety_factor = 0;
  336. if (ec->fips_enabled)
  337. safety_factor = ENTROPY_SAFETY_FACTOR;
  338. /* priming of the ->prev_time value */
  339. jent_measure_jitter(ec, 0, NULL);
  340. while (!jent_health_failure(ec)) {
  341. /* If a stuck measurement is received, repeat measurement */
  342. if (jent_measure_jitter(ec, 0, NULL))
  343. continue;
  344. /*
  345. * We multiply the loop value with ->osr to obtain the
  346. * oversampling rate requested by the caller
  347. */
  348. if (++k >= ((DATA_SIZE_BITS + safety_factor) * ec->osr))
  349. break;
  350. }
  351. }
  352. void jent_read_random_block(struct rand_data *ec, char *dst, size_t dst_len)
  353. {
  354. uint8_t jent_block[SHA3_256_SIZE_DIGEST];
  355. BUILD_BUG_ON(SHA3_256_SIZE_DIGEST != (DATA_SIZE_BITS / 8));
  356. /* The final operation automatically re-initializes the ->hash_state */
  357. sha3_final(ec->hash_state, jent_block);
  358. if (dst_len)
  359. memcpy(dst, jent_block, dst_len);
  360. /*
  361. * Stir the new state with the data from the old state - the digest
  362. * of the old data is not considered to have entropy.
  363. */
  364. sha3_update(ec->hash_state, jent_block, sizeof(jent_block));
  365. jent_memset_secure(jent_block, sizeof(jent_block));
  366. }