jitterentropy.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. /*
  2. * Non-physical true random number generator based on timing jitter --
  3. * Jitter RNG standalone code.
  4. *
  5. * Copyright Stephan Mueller <[email protected]>, 2015 - 2020
  6. *
  7. * Design
  8. * ======
  9. *
  10. * See https://www.chronox.de/jent.html
  11. *
  12. * License
  13. * =======
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions
  17. * are met:
  18. * 1. Redistributions of source code must retain the above copyright
  19. * notice, and the entire permission notice in its entirety,
  20. * including the disclaimer of warranties.
  21. * 2. Redistributions in binary form must reproduce the above copyright
  22. * notice, this list of conditions and the following disclaimer in the
  23. * documentation and/or other materials provided with the distribution.
  24. * 3. The name of the author may not be used to endorse or promote
  25. * products derived from this software without specific prior
  26. * written permission.
  27. *
  28. * ALTERNATIVELY, this product may be distributed under the terms of
  29. * the GNU General Public License, in which case the provisions of the GPL2 are
  30. * required INSTEAD OF the above restrictions. (This clause is
  31. * necessary due to a potential bad interaction between the GPL and
  32. * the restrictions contained in a BSD-style copyright.)
  33. *
  34. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  35. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  36. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
  37. * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
  38. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  39. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  40. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  41. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  42. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  43. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  44. * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
  45. * DAMAGE.
  46. */
  47. /*
  48. * This Jitterentropy RNG is based on the jitterentropy library
  49. * version 2.2.0 provided at https://www.chronox.de/jent.html
  50. */
  51. #ifdef __OPTIMIZE__
  52. #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy.c."
  53. #endif
  54. typedef unsigned long long __u64;
  55. typedef long long __s64;
  56. typedef unsigned int __u32;
  57. #define NULL ((void *) 0)
  58. /* The entropy pool */
  59. struct rand_data {
  60. /* all data values that are vital to maintain the security
  61. * of the RNG are marked as SENSITIVE. A user must not
  62. * access that information while the RNG executes its loops to
  63. * calculate the next random value. */
  64. __u64 data; /* SENSITIVE Actual random number */
  65. __u64 old_data; /* SENSITIVE Previous random number */
  66. __u64 prev_time; /* SENSITIVE Previous time stamp */
  67. #define DATA_SIZE_BITS ((sizeof(__u64)) * 8)
  68. __u64 last_delta; /* SENSITIVE stuck test */
  69. __s64 last_delta2; /* SENSITIVE stuck test */
  70. unsigned int osr; /* Oversample rate */
  71. #define JENT_MEMORY_BLOCKS 64
  72. #define JENT_MEMORY_BLOCKSIZE 32
  73. #define JENT_MEMORY_ACCESSLOOPS 128
  74. #define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
  75. unsigned char *mem; /* Memory access location with size of
  76. * memblocks * memblocksize */
  77. unsigned int memlocation; /* Pointer to byte in *mem */
  78. unsigned int memblocks; /* Number of memory blocks in *mem */
  79. unsigned int memblocksize; /* Size of one memory block in bytes */
  80. unsigned int memaccessloops; /* Number of memory accesses per random
  81. * bit generation */
  82. /* Repetition Count Test */
  83. unsigned int rct_count; /* Number of stuck values */
  84. /* Intermittent health test failure threshold of 2^-30 */
  85. #define JENT_RCT_CUTOFF 30 /* Taken from SP800-90B sec 4.4.1 */
  86. #define JENT_APT_CUTOFF 325 /* Taken from SP800-90B sec 4.4.2 */
  87. /* Permanent health test failure threshold of 2^-60 */
  88. #define JENT_RCT_CUTOFF_PERMANENT 60
  89. #define JENT_APT_CUTOFF_PERMANENT 355
  90. #define JENT_APT_WINDOW_SIZE 512 /* Data window size */
  91. /* LSB of time stamp to process */
  92. #define JENT_APT_LSB 16
  93. #define JENT_APT_WORD_MASK (JENT_APT_LSB - 1)
  94. unsigned int apt_observations; /* Number of collected observations */
  95. unsigned int apt_count; /* APT counter */
  96. unsigned int apt_base; /* APT base reference */
  97. unsigned int apt_base_set:1; /* APT base reference set? */
  98. };
  99. /* Flags that can be used to initialize the RNG */
  100. #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
  101. * entropy, saves MEMORY_SIZE RAM for
  102. * entropy collector */
  103. /* -- error codes for init function -- */
  104. #define JENT_ENOTIME 1 /* Timer service not available */
  105. #define JENT_ECOARSETIME 2 /* Timer too coarse for RNG */
  106. #define JENT_ENOMONOTONIC 3 /* Timer is not monotonic increasing */
  107. #define JENT_EVARVAR 5 /* Timer does not produce variations of
  108. * variations (2nd derivation of time is
  109. * zero). */
  110. #define JENT_ESTUCK 8 /* Too many stuck results during init. */
  111. #define JENT_EHEALTH 9 /* Health test failed during initialization */
  112. /*
  113. * The output n bits can receive more than n bits of min entropy, of course,
  114. * but the fixed output of the conditioning function can only asymptotically
  115. * approach the output size bits of min entropy, not attain that bound. Random
  116. * maps will tend to have output collisions, which reduces the creditable
  117. * output entropy (that is what SP 800-90B Section 3.1.5.1.2 attempts to bound).
  118. *
  119. * The value "64" is justified in Appendix A.4 of the current 90C draft,
  120. * and aligns with NIST's in "epsilon" definition in this document, which is
  121. * that a string can be considered "full entropy" if you can bound the min
  122. * entropy in each bit of output to at least 1-epsilon, where epsilon is
  123. * required to be <= 2^(-32).
  124. */
  125. #define JENT_ENTROPY_SAFETY_FACTOR 64
  126. #include <linux/fips.h>
  127. #include "jitterentropy.h"
  128. /***************************************************************************
  129. * Adaptive Proportion Test
  130. *
  131. * This test complies with SP800-90B section 4.4.2.
  132. ***************************************************************************/
  133. /*
  134. * Reset the APT counter
  135. *
  136. * @ec [in] Reference to entropy collector
  137. */
  138. static void jent_apt_reset(struct rand_data *ec, unsigned int delta_masked)
  139. {
  140. /* Reset APT counter */
  141. ec->apt_count = 0;
  142. ec->apt_base = delta_masked;
  143. ec->apt_observations = 0;
  144. }
  145. /*
  146. * Insert a new entropy event into APT
  147. *
  148. * @ec [in] Reference to entropy collector
  149. * @delta_masked [in] Masked time delta to process
  150. */
  151. static void jent_apt_insert(struct rand_data *ec, unsigned int delta_masked)
  152. {
  153. /* Initialize the base reference */
  154. if (!ec->apt_base_set) {
  155. ec->apt_base = delta_masked;
  156. ec->apt_base_set = 1;
  157. return;
  158. }
  159. if (delta_masked == ec->apt_base)
  160. ec->apt_count++;
  161. ec->apt_observations++;
  162. if (ec->apt_observations >= JENT_APT_WINDOW_SIZE)
  163. jent_apt_reset(ec, delta_masked);
  164. }
  165. /* APT health test failure detection */
  166. static int jent_apt_permanent_failure(struct rand_data *ec)
  167. {
  168. return (ec->apt_count >= JENT_APT_CUTOFF_PERMANENT) ? 1 : 0;
  169. }
  170. static int jent_apt_failure(struct rand_data *ec)
  171. {
  172. return (ec->apt_count >= JENT_APT_CUTOFF) ? 1 : 0;
  173. }
  174. /***************************************************************************
  175. * Stuck Test and its use as Repetition Count Test
  176. *
  177. * The Jitter RNG uses an enhanced version of the Repetition Count Test
  178. * (RCT) specified in SP800-90B section 4.4.1. Instead of counting identical
  179. * back-to-back values, the input to the RCT is the counting of the stuck
  180. * values during the generation of one Jitter RNG output block.
  181. *
  182. * The RCT is applied with an alpha of 2^{-30} compliant to FIPS 140-2 IG 9.8.
  183. *
  184. * During the counting operation, the Jitter RNG always calculates the RCT
  185. * cut-off value of C. If that value exceeds the allowed cut-off value,
  186. * the Jitter RNG output block will be calculated completely but discarded at
  187. * the end. The caller of the Jitter RNG is informed with an error code.
  188. ***************************************************************************/
  189. /*
  190. * Repetition Count Test as defined in SP800-90B section 4.4.1
  191. *
  192. * @ec [in] Reference to entropy collector
  193. * @stuck [in] Indicator whether the value is stuck
  194. */
  195. static void jent_rct_insert(struct rand_data *ec, int stuck)
  196. {
  197. if (stuck) {
  198. ec->rct_count++;
  199. } else {
  200. /* Reset RCT */
  201. ec->rct_count = 0;
  202. }
  203. }
  204. static inline __u64 jent_delta(__u64 prev, __u64 next)
  205. {
  206. #define JENT_UINT64_MAX (__u64)(~((__u64) 0))
  207. return (prev < next) ? (next - prev) :
  208. (JENT_UINT64_MAX - prev + 1 + next);
  209. }
  210. /*
  211. * Stuck test by checking the:
  212. * 1st derivative of the jitter measurement (time delta)
  213. * 2nd derivative of the jitter measurement (delta of time deltas)
  214. * 3rd derivative of the jitter measurement (delta of delta of time deltas)
  215. *
  216. * All values must always be non-zero.
  217. *
  218. * @ec [in] Reference to entropy collector
  219. * @current_delta [in] Jitter time delta
  220. *
  221. * @return
  222. * 0 jitter measurement not stuck (good bit)
  223. * 1 jitter measurement stuck (reject bit)
  224. */
  225. static int jent_stuck(struct rand_data *ec, __u64 current_delta)
  226. {
  227. __u64 delta2 = jent_delta(ec->last_delta, current_delta);
  228. __u64 delta3 = jent_delta(ec->last_delta2, delta2);
  229. ec->last_delta = current_delta;
  230. ec->last_delta2 = delta2;
  231. /*
  232. * Insert the result of the comparison of two back-to-back time
  233. * deltas.
  234. */
  235. jent_apt_insert(ec, current_delta);
  236. if (!current_delta || !delta2 || !delta3) {
  237. /* RCT with a stuck bit */
  238. jent_rct_insert(ec, 1);
  239. return 1;
  240. }
  241. /* RCT with a non-stuck bit */
  242. jent_rct_insert(ec, 0);
  243. return 0;
  244. }
  245. /* RCT health test failure detection */
  246. static int jent_rct_permanent_failure(struct rand_data *ec)
  247. {
  248. return (ec->rct_count >= JENT_RCT_CUTOFF_PERMANENT) ? 1 : 0;
  249. }
  250. static int jent_rct_failure(struct rand_data *ec)
  251. {
  252. return (ec->rct_count >= JENT_RCT_CUTOFF) ? 1 : 0;
  253. }
  254. /* Report of health test failures */
  255. static int jent_health_failure(struct rand_data *ec)
  256. {
  257. return jent_rct_failure(ec) | jent_apt_failure(ec);
  258. }
  259. static int jent_permanent_health_failure(struct rand_data *ec)
  260. {
  261. return jent_rct_permanent_failure(ec) | jent_apt_permanent_failure(ec);
  262. }
  263. /***************************************************************************
  264. * Noise sources
  265. ***************************************************************************/
  266. /*
  267. * Update of the loop count used for the next round of
  268. * an entropy collection.
  269. *
  270. * Input:
  271. * @ec entropy collector struct -- may be NULL
  272. * @bits is the number of low bits of the timer to consider
  273. * @min is the number of bits we shift the timer value to the right at
  274. * the end to make sure we have a guaranteed minimum value
  275. *
  276. * @return Newly calculated loop counter
  277. */
  278. static __u64 jent_loop_shuffle(struct rand_data *ec,
  279. unsigned int bits, unsigned int min)
  280. {
  281. __u64 time = 0;
  282. __u64 shuffle = 0;
  283. unsigned int i = 0;
  284. unsigned int mask = (1<<bits) - 1;
  285. jent_get_nstime(&time);
  286. /*
  287. * Mix the current state of the random number into the shuffle
  288. * calculation to balance that shuffle a bit more.
  289. */
  290. if (ec)
  291. time ^= ec->data;
  292. /*
  293. * We fold the time value as much as possible to ensure that as many
  294. * bits of the time stamp are included as possible.
  295. */
  296. for (i = 0; ((DATA_SIZE_BITS + bits - 1) / bits) > i; i++) {
  297. shuffle ^= time & mask;
  298. time = time >> bits;
  299. }
  300. /*
  301. * We add a lower boundary value to ensure we have a minimum
  302. * RNG loop count.
  303. */
  304. return (shuffle + (1<<min));
  305. }
  306. /*
  307. * CPU Jitter noise source -- this is the noise source based on the CPU
  308. * execution time jitter
  309. *
  310. * This function injects the individual bits of the time value into the
  311. * entropy pool using an LFSR.
  312. *
  313. * The code is deliberately inefficient with respect to the bit shifting
  314. * and shall stay that way. This function is the root cause why the code
  315. * shall be compiled without optimization. This function not only acts as
  316. * folding operation, but this function's execution is used to measure
  317. * the CPU execution time jitter. Any change to the loop in this function
  318. * implies that careful retesting must be done.
  319. *
  320. * @ec [in] entropy collector struct
  321. * @time [in] time stamp to be injected
  322. * @loop_cnt [in] if a value not equal to 0 is set, use the given value as
  323. * number of loops to perform the folding
  324. * @stuck [in] Is the time stamp identified as stuck?
  325. *
  326. * Output:
  327. * updated ec->data
  328. *
  329. * @return Number of loops the folding operation is performed
  330. */
  331. static void jent_lfsr_time(struct rand_data *ec, __u64 time, __u64 loop_cnt,
  332. int stuck)
  333. {
  334. unsigned int i;
  335. __u64 j = 0;
  336. __u64 new = 0;
  337. #define MAX_FOLD_LOOP_BIT 4
  338. #define MIN_FOLD_LOOP_BIT 0
  339. __u64 fold_loop_cnt =
  340. jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT);
  341. /*
  342. * testing purposes -- allow test app to set the counter, not
  343. * needed during runtime
  344. */
  345. if (loop_cnt)
  346. fold_loop_cnt = loop_cnt;
  347. for (j = 0; j < fold_loop_cnt; j++) {
  348. new = ec->data;
  349. for (i = 1; (DATA_SIZE_BITS) >= i; i++) {
  350. __u64 tmp = time << (DATA_SIZE_BITS - i);
  351. tmp = tmp >> (DATA_SIZE_BITS - 1);
  352. /*
  353. * Fibonacci LSFR with polynomial of
  354. * x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is
  355. * primitive according to
  356. * http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf
  357. * (the shift values are the polynomial values minus one
  358. * due to counting bits from 0 to 63). As the current
  359. * position is always the LSB, the polynomial only needs
  360. * to shift data in from the left without wrap.
  361. */
  362. tmp ^= ((new >> 63) & 1);
  363. tmp ^= ((new >> 60) & 1);
  364. tmp ^= ((new >> 55) & 1);
  365. tmp ^= ((new >> 30) & 1);
  366. tmp ^= ((new >> 27) & 1);
  367. tmp ^= ((new >> 22) & 1);
  368. new <<= 1;
  369. new ^= tmp;
  370. }
  371. }
  372. /*
  373. * If the time stamp is stuck, do not finally insert the value into
  374. * the entropy pool. Although this operation should not do any harm
  375. * even when the time stamp has no entropy, SP800-90B requires that
  376. * any conditioning operation (SP800-90B considers the LFSR to be a
  377. * conditioning operation) to have an identical amount of input
  378. * data according to section 3.1.5.
  379. */
  380. if (!stuck)
  381. ec->data = new;
  382. }
  383. /*
  384. * Memory Access noise source -- this is a noise source based on variations in
  385. * memory access times
  386. *
  387. * This function performs memory accesses which will add to the timing
  388. * variations due to an unknown amount of CPU wait states that need to be
  389. * added when accessing memory. The memory size should be larger than the L1
  390. * caches as outlined in the documentation and the associated testing.
  391. *
  392. * The L1 cache has a very high bandwidth, albeit its access rate is usually
  393. * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
  394. * variations as the CPU has hardly to wait. Starting with L2, significant
  395. * variations are added because L2 typically does not belong to the CPU any more
  396. * and therefore a wider range of CPU wait states is necessary for accesses.
  397. * L3 and real memory accesses have even a wider range of wait states. However,
  398. * to reliably access either L3 or memory, the ec->mem memory must be quite
  399. * large which is usually not desirable.
  400. *
  401. * @ec [in] Reference to the entropy collector with the memory access data -- if
  402. * the reference to the memory block to be accessed is NULL, this noise
  403. * source is disabled
  404. * @loop_cnt [in] if a value not equal to 0 is set, use the given value
  405. * number of loops to perform the LFSR
  406. */
  407. static void jent_memaccess(struct rand_data *ec, __u64 loop_cnt)
  408. {
  409. unsigned int wrap = 0;
  410. __u64 i = 0;
  411. #define MAX_ACC_LOOP_BIT 7
  412. #define MIN_ACC_LOOP_BIT 0
  413. __u64 acc_loop_cnt =
  414. jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
  415. if (NULL == ec || NULL == ec->mem)
  416. return;
  417. wrap = ec->memblocksize * ec->memblocks;
  418. /*
  419. * testing purposes -- allow test app to set the counter, not
  420. * needed during runtime
  421. */
  422. if (loop_cnt)
  423. acc_loop_cnt = loop_cnt;
  424. for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
  425. unsigned char *tmpval = ec->mem + ec->memlocation;
  426. /*
  427. * memory access: just add 1 to one byte,
  428. * wrap at 255 -- memory access implies read
  429. * from and write to memory location
  430. */
  431. *tmpval = (*tmpval + 1) & 0xff;
  432. /*
  433. * Addition of memblocksize - 1 to pointer
  434. * with wrap around logic to ensure that every
  435. * memory location is hit evenly
  436. */
  437. ec->memlocation = ec->memlocation + ec->memblocksize - 1;
  438. ec->memlocation = ec->memlocation % wrap;
  439. }
  440. }
  441. /***************************************************************************
  442. * Start of entropy processing logic
  443. ***************************************************************************/
  444. /*
  445. * This is the heart of the entropy generation: calculate time deltas and
  446. * use the CPU jitter in the time deltas. The jitter is injected into the
  447. * entropy pool.
  448. *
  449. * WARNING: ensure that ->prev_time is primed before using the output
  450. * of this function! This can be done by calling this function
  451. * and not using its result.
  452. *
  453. * @ec [in] Reference to entropy collector
  454. *
  455. * @return result of stuck test
  456. */
  457. static int jent_measure_jitter(struct rand_data *ec)
  458. {
  459. __u64 time = 0;
  460. __u64 current_delta = 0;
  461. int stuck;
  462. /* Invoke one noise source before time measurement to add variations */
  463. jent_memaccess(ec, 0);
  464. /*
  465. * Get time stamp and calculate time delta to previous
  466. * invocation to measure the timing variations
  467. */
  468. jent_get_nstime(&time);
  469. current_delta = jent_delta(ec->prev_time, time);
  470. ec->prev_time = time;
  471. /* Check whether we have a stuck measurement. */
  472. stuck = jent_stuck(ec, current_delta);
  473. /* Now call the next noise sources which also injects the data */
  474. jent_lfsr_time(ec, current_delta, 0, stuck);
  475. return stuck;
  476. }
  477. /*
  478. * Generator of one 64 bit random number
  479. * Function fills rand_data->data
  480. *
  481. * @ec [in] Reference to entropy collector
  482. */
  483. static void jent_gen_entropy(struct rand_data *ec)
  484. {
  485. unsigned int k = 0, safety_factor = 0;
  486. if (fips_enabled)
  487. safety_factor = JENT_ENTROPY_SAFETY_FACTOR;
  488. /* priming of the ->prev_time value */
  489. jent_measure_jitter(ec);
  490. while (!jent_health_failure(ec)) {
  491. /* If a stuck measurement is received, repeat measurement */
  492. if (jent_measure_jitter(ec))
  493. continue;
  494. /*
  495. * We multiply the loop value with ->osr to obtain the
  496. * oversampling rate requested by the caller
  497. */
  498. if (++k >= ((DATA_SIZE_BITS + safety_factor) * ec->osr))
  499. break;
  500. }
  501. }
  502. /*
  503. * Entry function: Obtain entropy for the caller.
  504. *
  505. * This function invokes the entropy gathering logic as often to generate
  506. * as many bytes as requested by the caller. The entropy gathering logic
  507. * creates 64 bit per invocation.
  508. *
  509. * This function truncates the last 64 bit entropy value output to the exact
  510. * size specified by the caller.
  511. *
  512. * @ec [in] Reference to entropy collector
  513. * @data [in] pointer to buffer for storing random data -- buffer must already
  514. * exist
  515. * @len [in] size of the buffer, specifying also the requested number of random
  516. * in bytes
  517. *
  518. * @return 0 when request is fulfilled or an error
  519. *
  520. * The following error codes can occur:
  521. * -1 entropy_collector is NULL
  522. * -2 Intermittent health failure
  523. * -3 Permanent health failure
  524. */
  525. int jent_read_entropy(struct rand_data *ec, unsigned char *data,
  526. unsigned int len)
  527. {
  528. unsigned char *p = data;
  529. if (!ec)
  530. return -1;
  531. while (len > 0) {
  532. unsigned int tocopy;
  533. jent_gen_entropy(ec);
  534. if (jent_permanent_health_failure(ec)) {
  535. /*
  536. * At this point, the Jitter RNG instance is considered
  537. * as a failed instance. There is no rerun of the
  538. * startup test any more, because the caller
  539. * is assumed to not further use this instance.
  540. */
  541. return -3;
  542. } else if (jent_health_failure(ec)) {
  543. /*
  544. * Perform startup health tests and return permanent
  545. * error if it fails.
  546. */
  547. if (jent_entropy_init())
  548. return -3;
  549. return -2;
  550. }
  551. if ((DATA_SIZE_BITS / 8) < len)
  552. tocopy = (DATA_SIZE_BITS / 8);
  553. else
  554. tocopy = len;
  555. jent_memcpy(p, &ec->data, tocopy);
  556. len -= tocopy;
  557. p += tocopy;
  558. }
  559. return 0;
  560. }
  561. /***************************************************************************
  562. * Initialization logic
  563. ***************************************************************************/
  564. struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
  565. unsigned int flags)
  566. {
  567. struct rand_data *entropy_collector;
  568. entropy_collector = jent_zalloc(sizeof(struct rand_data));
  569. if (!entropy_collector)
  570. return NULL;
  571. if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
  572. /* Allocate memory for adding variations based on memory
  573. * access
  574. */
  575. entropy_collector->mem = jent_zalloc(JENT_MEMORY_SIZE);
  576. if (!entropy_collector->mem) {
  577. jent_zfree(entropy_collector);
  578. return NULL;
  579. }
  580. entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
  581. entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
  582. entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
  583. }
  584. /* verify and set the oversampling rate */
  585. if (osr == 0)
  586. osr = 1; /* minimum sampling rate is 1 */
  587. entropy_collector->osr = osr;
  588. /* fill the data pad with non-zero values */
  589. jent_gen_entropy(entropy_collector);
  590. return entropy_collector;
  591. }
  592. void jent_entropy_collector_free(struct rand_data *entropy_collector)
  593. {
  594. jent_zfree(entropy_collector->mem);
  595. entropy_collector->mem = NULL;
  596. jent_zfree(entropy_collector);
  597. }
  598. int jent_entropy_init(void)
  599. {
  600. int i;
  601. __u64 delta_sum = 0;
  602. __u64 old_delta = 0;
  603. unsigned int nonstuck = 0;
  604. int time_backwards = 0;
  605. int count_mod = 0;
  606. int count_stuck = 0;
  607. struct rand_data ec = { 0 };
  608. /* Required for RCT */
  609. ec.osr = 1;
  610. /* We could perform statistical tests here, but the problem is
  611. * that we only have a few loop counts to do testing. These
  612. * loop counts may show some slight skew and we produce
  613. * false positives.
  614. *
  615. * Moreover, only old systems show potentially problematic
  616. * jitter entropy that could potentially be caught here. But
  617. * the RNG is intended for hardware that is available or widely
  618. * used, but not old systems that are long out of favor. Thus,
  619. * no statistical tests.
  620. */
  621. /*
  622. * We could add a check for system capabilities such as clock_getres or
  623. * check for CONFIG_X86_TSC, but it does not make much sense as the
  624. * following sanity checks verify that we have a high-resolution
  625. * timer.
  626. */
  627. /*
  628. * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
  629. * definitely too little.
  630. *
  631. * SP800-90B requires at least 1024 initial test cycles.
  632. */
  633. #define TESTLOOPCOUNT 1024
  634. #define CLEARCACHE 100
  635. for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
  636. __u64 time = 0;
  637. __u64 time2 = 0;
  638. __u64 delta = 0;
  639. unsigned int lowdelta = 0;
  640. int stuck;
  641. /* Invoke core entropy collection logic */
  642. jent_get_nstime(&time);
  643. ec.prev_time = time;
  644. jent_lfsr_time(&ec, time, 0, 0);
  645. jent_get_nstime(&time2);
  646. /* test whether timer works */
  647. if (!time || !time2)
  648. return JENT_ENOTIME;
  649. delta = jent_delta(time, time2);
  650. /*
  651. * test whether timer is fine grained enough to provide
  652. * delta even when called shortly after each other -- this
  653. * implies that we also have a high resolution timer
  654. */
  655. if (!delta)
  656. return JENT_ECOARSETIME;
  657. stuck = jent_stuck(&ec, delta);
  658. /*
  659. * up to here we did not modify any variable that will be
  660. * evaluated later, but we already performed some work. Thus we
  661. * already have had an impact on the caches, branch prediction,
  662. * etc. with the goal to clear it to get the worst case
  663. * measurements.
  664. */
  665. if (i < CLEARCACHE)
  666. continue;
  667. if (stuck)
  668. count_stuck++;
  669. else {
  670. nonstuck++;
  671. /*
  672. * Ensure that the APT succeeded.
  673. *
  674. * With the check below that count_stuck must be less
  675. * than 10% of the overall generated raw entropy values
  676. * it is guaranteed that the APT is invoked at
  677. * floor((TESTLOOPCOUNT * 0.9) / 64) == 14 times.
  678. */
  679. if ((nonstuck % JENT_APT_WINDOW_SIZE) == 0) {
  680. jent_apt_reset(&ec,
  681. delta & JENT_APT_WORD_MASK);
  682. }
  683. }
  684. /* Validate health test result */
  685. if (jent_health_failure(&ec))
  686. return JENT_EHEALTH;
  687. /* test whether we have an increasing timer */
  688. if (!(time2 > time))
  689. time_backwards++;
  690. /* use 32 bit value to ensure compilation on 32 bit arches */
  691. lowdelta = time2 - time;
  692. if (!(lowdelta % 100))
  693. count_mod++;
  694. /*
  695. * ensure that we have a varying delta timer which is necessary
  696. * for the calculation of entropy -- perform this check
  697. * only after the first loop is executed as we need to prime
  698. * the old_data value
  699. */
  700. if (delta > old_delta)
  701. delta_sum += (delta - old_delta);
  702. else
  703. delta_sum += (old_delta - delta);
  704. old_delta = delta;
  705. }
  706. /*
  707. * we allow up to three times the time running backwards.
  708. * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
  709. * if such an operation just happens to interfere with our test, it
  710. * should not fail. The value of 3 should cover the NTP case being
  711. * performed during our test run.
  712. */
  713. if (time_backwards > 3)
  714. return JENT_ENOMONOTONIC;
  715. /*
  716. * Variations of deltas of time must on average be larger
  717. * than 1 to ensure the entropy estimation
  718. * implied with 1 is preserved
  719. */
  720. if ((delta_sum) <= 1)
  721. return JENT_EVARVAR;
  722. /*
  723. * Ensure that we have variations in the time stamp below 10 for at
  724. * least 10% of all checks -- on some platforms, the counter increments
  725. * in multiples of 100, but not always
  726. */
  727. if ((TESTLOOPCOUNT/10 * 9) < count_mod)
  728. return JENT_ECOARSETIME;
  729. /*
  730. * If we have more than 90% stuck results, then this Jitter RNG is
  731. * likely to not work well.
  732. */
  733. if ((TESTLOOPCOUNT/10 * 9) < count_stuck)
  734. return JENT_ESTUCK;
  735. return 0;
  736. }