jitterentropy.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. /*
  2. * Non-physical true random number generator based on timing jitter --
  3. * Jitter RNG standalone code.
  4. *
  5. * Copyright Stephan Mueller <smueller@chronox.de>, 2015
  6. *
  7. * Design
  8. * ======
  9. *
  10. * See http://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 1.1.0 provided at http://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 stuck:1; /* Time measurement stuck */
  71. unsigned int osr; /* Oversample rate */
  72. unsigned int stir:1; /* Post-processing stirring */
  73. unsigned int disable_unbias:1; /* Deactivate Von-Neuman unbias */
  74. #define JENT_MEMORY_BLOCKS 64
  75. #define JENT_MEMORY_BLOCKSIZE 32
  76. #define JENT_MEMORY_ACCESSLOOPS 128
  77. #define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
  78. unsigned char *mem; /* Memory access location with size of
  79. * memblocks * memblocksize */
  80. unsigned int memlocation; /* Pointer to byte in *mem */
  81. unsigned int memblocks; /* Number of memory blocks in *mem */
  82. unsigned int memblocksize; /* Size of one memory block in bytes */
  83. unsigned int memaccessloops; /* Number of memory accesses per random
  84. * bit generation */
  85. };
  86. /* Flags that can be used to initialize the RNG */
  87. #define JENT_DISABLE_STIR (1<<0) /* Disable stirring the entropy pool */
  88. #define JENT_DISABLE_UNBIAS (1<<1) /* Disable the Von-Neuman Unbiaser */
  89. #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
  90. * entropy, saves MEMORY_SIZE RAM for
  91. * entropy collector */
  92. /* -- error codes for init function -- */
  93. #define JENT_ENOTIME 1 /* Timer service not available */
  94. #define JENT_ECOARSETIME 2 /* Timer too coarse for RNG */
  95. #define JENT_ENOMONOTONIC 3 /* Timer is not monotonic increasing */
  96. #define JENT_EMINVARIATION 4 /* Timer variations too small for RNG */
  97. #define JENT_EVARVAR 5 /* Timer does not produce variations of
  98. * variations (2nd derivation of time is
  99. * zero). */
  100. #define JENT_EMINVARVAR 6 /* Timer variations of variations is tooi
  101. * small. */
  102. /***************************************************************************
  103. * Helper functions
  104. ***************************************************************************/
  105. void jent_get_nstime(__u64 *out);
  106. __u64 jent_rol64(__u64 word, unsigned int shift);
  107. void *jent_zalloc(unsigned int len);
  108. void jent_zfree(void *ptr);
  109. int jent_fips_enabled(void);
  110. void jent_panic(char *s);
  111. void jent_memcpy(void *dest, const void *src, unsigned int n);
  112. /**
  113. * Update of the loop count used for the next round of
  114. * an entropy collection.
  115. *
  116. * Input:
  117. * @ec entropy collector struct -- may be NULL
  118. * @bits is the number of low bits of the timer to consider
  119. * @min is the number of bits we shift the timer value to the right at
  120. * the end to make sure we have a guaranteed minimum value
  121. *
  122. * @return Newly calculated loop counter
  123. */
  124. static __u64 jent_loop_shuffle(struct rand_data *ec,
  125. unsigned int bits, unsigned int min)
  126. {
  127. __u64 time = 0;
  128. __u64 shuffle = 0;
  129. unsigned int i = 0;
  130. unsigned int mask = (1<<bits) - 1;
  131. jent_get_nstime(&time);
  132. /*
  133. * mix the current state of the random number into the shuffle
  134. * calculation to balance that shuffle a bit more
  135. */
  136. if (ec)
  137. time ^= ec->data;
  138. /*
  139. * we fold the time value as much as possible to ensure that as many
  140. * bits of the time stamp are included as possible
  141. */
  142. for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) {
  143. shuffle ^= time & mask;
  144. time = time >> bits;
  145. }
  146. /*
  147. * We add a lower boundary value to ensure we have a minimum
  148. * RNG loop count.
  149. */
  150. return (shuffle + (1<<min));
  151. }
  152. /***************************************************************************
  153. * Noise sources
  154. ***************************************************************************/
  155. /**
  156. * CPU Jitter noise source -- this is the noise source based on the CPU
  157. * execution time jitter
  158. *
  159. * This function folds the time into one bit units by iterating
  160. * through the DATA_SIZE_BITS bit time value as follows: assume our time value
  161. * is 0xabcd
  162. * 1st loop, 1st shift generates 0xd000
  163. * 1st loop, 2nd shift generates 0x000d
  164. * 2nd loop, 1st shift generates 0xcd00
  165. * 2nd loop, 2nd shift generates 0x000c
  166. * 3rd loop, 1st shift generates 0xbcd0
  167. * 3rd loop, 2nd shift generates 0x000b
  168. * 4th loop, 1st shift generates 0xabcd
  169. * 4th loop, 2nd shift generates 0x000a
  170. * Now, the values at the end of the 2nd shifts are XORed together.
  171. *
  172. * The code is deliberately inefficient and shall stay that way. This function
  173. * is the root cause why the code shall be compiled without optimization. This
  174. * function not only acts as folding operation, but this function's execution
  175. * is used to measure the CPU execution time jitter. Any change to the loop in
  176. * this function implies that careful retesting must be done.
  177. *
  178. * Input:
  179. * @ec entropy collector struct -- may be NULL
  180. * @time time stamp to be folded
  181. * @loop_cnt if a value not equal to 0 is set, use the given value as number of
  182. * loops to perform the folding
  183. *
  184. * Output:
  185. * @folded result of folding operation
  186. *
  187. * @return Number of loops the folding operation is performed
  188. */
  189. static __u64 jent_fold_time(struct rand_data *ec, __u64 time,
  190. __u64 *folded, __u64 loop_cnt)
  191. {
  192. unsigned int i;
  193. __u64 j = 0;
  194. __u64 new = 0;
  195. #define MAX_FOLD_LOOP_BIT 4
  196. #define MIN_FOLD_LOOP_BIT 0
  197. __u64 fold_loop_cnt =
  198. jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT);
  199. /*
  200. * testing purposes -- allow test app to set the counter, not
  201. * needed during runtime
  202. */
  203. if (loop_cnt)
  204. fold_loop_cnt = loop_cnt;
  205. for (j = 0; j < fold_loop_cnt; j++) {
  206. new = 0;
  207. for (i = 1; (DATA_SIZE_BITS) >= i; i++) {
  208. __u64 tmp = time << (DATA_SIZE_BITS - i);
  209. tmp = tmp >> (DATA_SIZE_BITS - 1);
  210. new ^= tmp;
  211. }
  212. }
  213. *folded = new;
  214. return fold_loop_cnt;
  215. }
  216. /**
  217. * Memory Access noise source -- this is a noise source based on variations in
  218. * memory access times
  219. *
  220. * This function performs memory accesses which will add to the timing
  221. * variations due to an unknown amount of CPU wait states that need to be
  222. * added when accessing memory. The memory size should be larger than the L1
  223. * caches as outlined in the documentation and the associated testing.
  224. *
  225. * The L1 cache has a very high bandwidth, albeit its access rate is usually
  226. * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
  227. * variations as the CPU has hardly to wait. Starting with L2, significant
  228. * variations are added because L2 typically does not belong to the CPU any more
  229. * and therefore a wider range of CPU wait states is necessary for accesses.
  230. * L3 and real memory accesses have even a wider range of wait states. However,
  231. * to reliably access either L3 or memory, the ec->mem memory must be quite
  232. * large which is usually not desirable.
  233. *
  234. * Input:
  235. * @ec Reference to the entropy collector with the memory access data -- if
  236. * the reference to the memory block to be accessed is NULL, this noise
  237. * source is disabled
  238. * @loop_cnt if a value not equal to 0 is set, use the given value as number of
  239. * loops to perform the folding
  240. *
  241. * @return Number of memory access operations
  242. */
  243. static unsigned int jent_memaccess(struct rand_data *ec, __u64 loop_cnt)
  244. {
  245. unsigned char *tmpval = NULL;
  246. unsigned int wrap = 0;
  247. __u64 i = 0;
  248. #define MAX_ACC_LOOP_BIT 7
  249. #define MIN_ACC_LOOP_BIT 0
  250. __u64 acc_loop_cnt =
  251. jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
  252. if (NULL == ec || NULL == ec->mem)
  253. return 0;
  254. wrap = ec->memblocksize * ec->memblocks;
  255. /*
  256. * testing purposes -- allow test app to set the counter, not
  257. * needed during runtime
  258. */
  259. if (loop_cnt)
  260. acc_loop_cnt = loop_cnt;
  261. for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
  262. tmpval = ec->mem + ec->memlocation;
  263. /*
  264. * memory access: just add 1 to one byte,
  265. * wrap at 255 -- memory access implies read
  266. * from and write to memory location
  267. */
  268. *tmpval = (*tmpval + 1) & 0xff;
  269. /*
  270. * Addition of memblocksize - 1 to pointer
  271. * with wrap around logic to ensure that every
  272. * memory location is hit evenly
  273. */
  274. ec->memlocation = ec->memlocation + ec->memblocksize - 1;
  275. ec->memlocation = ec->memlocation % wrap;
  276. }
  277. return i;
  278. }
  279. /***************************************************************************
  280. * Start of entropy processing logic
  281. ***************************************************************************/
  282. /**
  283. * Stuck test by checking the:
  284. * 1st derivation of the jitter measurement (time delta)
  285. * 2nd derivation of the jitter measurement (delta of time deltas)
  286. * 3rd derivation of the jitter measurement (delta of delta of time deltas)
  287. *
  288. * All values must always be non-zero.
  289. *
  290. * Input:
  291. * @ec Reference to entropy collector
  292. * @current_delta Jitter time delta
  293. *
  294. * @return
  295. * 0 jitter measurement not stuck (good bit)
  296. * 1 jitter measurement stuck (reject bit)
  297. */
  298. static void jent_stuck(struct rand_data *ec, __u64 current_delta)
  299. {
  300. __s64 delta2 = ec->last_delta - current_delta;
  301. __s64 delta3 = delta2 - ec->last_delta2;
  302. ec->last_delta = current_delta;
  303. ec->last_delta2 = delta2;
  304. if (!current_delta || !delta2 || !delta3)
  305. ec->stuck = 1;
  306. }
  307. /**
  308. * This is the heart of the entropy generation: calculate time deltas and
  309. * use the CPU jitter in the time deltas. The jitter is folded into one
  310. * bit. You can call this function the "random bit generator" as it
  311. * produces one random bit per invocation.
  312. *
  313. * WARNING: ensure that ->prev_time is primed before using the output
  314. * of this function! This can be done by calling this function
  315. * and not using its result.
  316. *
  317. * Input:
  318. * @entropy_collector Reference to entropy collector
  319. *
  320. * @return One random bit
  321. */
  322. static __u64 jent_measure_jitter(struct rand_data *ec)
  323. {
  324. __u64 time = 0;
  325. __u64 data = 0;
  326. __u64 current_delta = 0;
  327. /* Invoke one noise source before time measurement to add variations */
  328. jent_memaccess(ec, 0);
  329. /*
  330. * Get time stamp and calculate time delta to previous
  331. * invocation to measure the timing variations
  332. */
  333. jent_get_nstime(&time);
  334. current_delta = time - ec->prev_time;
  335. ec->prev_time = time;
  336. /* Now call the next noise sources which also folds the data */
  337. jent_fold_time(ec, current_delta, &data, 0);
  338. /*
  339. * Check whether we have a stuck measurement. The enforcement
  340. * is performed after the stuck value has been mixed into the
  341. * entropy pool.
  342. */
  343. jent_stuck(ec, current_delta);
  344. return data;
  345. }
  346. /**
  347. * Von Neuman unbias as explained in RFC 4086 section 4.2. As shown in the
  348. * documentation of that RNG, the bits from jent_measure_jitter are considered
  349. * independent which implies that the Von Neuman unbias operation is applicable.
  350. * A proof of the Von-Neumann unbias operation to remove skews is given in the
  351. * document "A proposal for: Functionality classes for random number
  352. * generators", version 2.0 by Werner Schindler, section 5.4.1.
  353. *
  354. * Input:
  355. * @entropy_collector Reference to entropy collector
  356. *
  357. * @return One random bit
  358. */
  359. static __u64 jent_unbiased_bit(struct rand_data *entropy_collector)
  360. {
  361. do {
  362. __u64 a = jent_measure_jitter(entropy_collector);
  363. __u64 b = jent_measure_jitter(entropy_collector);
  364. if (a == b)
  365. continue;
  366. if (1 == a)
  367. return 1;
  368. else
  369. return 0;
  370. } while (1);
  371. }
  372. /**
  373. * Shuffle the pool a bit by mixing some value with a bijective function (XOR)
  374. * into the pool.
  375. *
  376. * The function generates a mixer value that depends on the bits set and the
  377. * location of the set bits in the random number generated by the entropy
  378. * source. Therefore, based on the generated random number, this mixer value
  379. * can have 2**64 different values. That mixer value is initialized with the
  380. * first two SHA-1 constants. After obtaining the mixer value, it is XORed into
  381. * the random number.
  382. *
  383. * The mixer value is not assumed to contain any entropy. But due to the XOR
  384. * operation, it can also not destroy any entropy present in the entropy pool.
  385. *
  386. * Input:
  387. * @entropy_collector Reference to entropy collector
  388. */
  389. static void jent_stir_pool(struct rand_data *entropy_collector)
  390. {
  391. /*
  392. * to shut up GCC on 32 bit, we have to initialize the 64 variable
  393. * with two 32 bit variables
  394. */
  395. union c {
  396. __u64 u64;
  397. __u32 u32[2];
  398. };
  399. /*
  400. * This constant is derived from the first two 32 bit initialization
  401. * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1
  402. */
  403. union c constant;
  404. /*
  405. * The start value of the mixer variable is derived from the third
  406. * and fourth 32 bit initialization vector of SHA-1 as defined in
  407. * FIPS 180-4 section 5.3.1
  408. */
  409. union c mixer;
  410. unsigned int i = 0;
  411. /*
  412. * Store the SHA-1 constants in reverse order to make up the 64 bit
  413. * value -- this applies to a little endian system, on a big endian
  414. * system, it reverses as expected. But this really does not matter
  415. * as we do not rely on the specific numbers. We just pick the SHA-1
  416. * constants as they have a good mix of bit set and unset.
  417. */
  418. constant.u32[1] = 0x67452301;
  419. constant.u32[0] = 0xefcdab89;
  420. mixer.u32[1] = 0x98badcfe;
  421. mixer.u32[0] = 0x10325476;
  422. for (i = 0; i < DATA_SIZE_BITS; i++) {
  423. /*
  424. * get the i-th bit of the input random number and only XOR
  425. * the constant into the mixer value when that bit is set
  426. */
  427. if ((entropy_collector->data >> i) & 1)
  428. mixer.u64 ^= constant.u64;
  429. mixer.u64 = jent_rol64(mixer.u64, 1);
  430. }
  431. entropy_collector->data ^= mixer.u64;
  432. }
  433. /**
  434. * Generator of one 64 bit random number
  435. * Function fills rand_data->data
  436. *
  437. * Input:
  438. * @ec Reference to entropy collector
  439. */
  440. static void jent_gen_entropy(struct rand_data *ec)
  441. {
  442. unsigned int k = 0;
  443. /* priming of the ->prev_time value */
  444. jent_measure_jitter(ec);
  445. while (1) {
  446. __u64 data = 0;
  447. if (ec->disable_unbias == 1)
  448. data = jent_measure_jitter(ec);
  449. else
  450. data = jent_unbiased_bit(ec);
  451. /* enforcement of the jent_stuck test */
  452. if (ec->stuck) {
  453. /*
  454. * We only mix in the bit considered not appropriate
  455. * without the LSFR. The reason is that if we apply
  456. * the LSFR and we do not rotate, the 2nd bit with LSFR
  457. * will cancel out the first LSFR application on the
  458. * bad bit.
  459. *
  460. * And we do not rotate as we apply the next bit to the
  461. * current bit location again.
  462. */
  463. ec->data ^= data;
  464. ec->stuck = 0;
  465. continue;
  466. }
  467. /*
  468. * Fibonacci LSFR with polynom of
  469. * x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is
  470. * primitive according to
  471. * http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf
  472. * (the shift values are the polynom values minus one
  473. * due to counting bits from 0 to 63). As the current
  474. * position is always the LSB, the polynom only needs
  475. * to shift data in from the left without wrap.
  476. */
  477. ec->data ^= data;
  478. ec->data ^= ((ec->data >> 63) & 1);
  479. ec->data ^= ((ec->data >> 60) & 1);
  480. ec->data ^= ((ec->data >> 55) & 1);
  481. ec->data ^= ((ec->data >> 30) & 1);
  482. ec->data ^= ((ec->data >> 27) & 1);
  483. ec->data ^= ((ec->data >> 22) & 1);
  484. ec->data = jent_rol64(ec->data, 1);
  485. /*
  486. * We multiply the loop value with ->osr to obtain the
  487. * oversampling rate requested by the caller
  488. */
  489. if (++k >= (DATA_SIZE_BITS * ec->osr))
  490. break;
  491. }
  492. if (ec->stir)
  493. jent_stir_pool(ec);
  494. }
  495. /**
  496. * The continuous test required by FIPS 140-2 -- the function automatically
  497. * primes the test if needed.
  498. *
  499. * Return:
  500. * 0 if FIPS test passed
  501. * < 0 if FIPS test failed
  502. */
  503. static void jent_fips_test(struct rand_data *ec)
  504. {
  505. if (!jent_fips_enabled())
  506. return;
  507. /* prime the FIPS test */
  508. if (!ec->old_data) {
  509. ec->old_data = ec->data;
  510. jent_gen_entropy(ec);
  511. }
  512. if (ec->data == ec->old_data)
  513. jent_panic("jitterentropy: Duplicate output detected\n");
  514. ec->old_data = ec->data;
  515. }
  516. /**
  517. * Entry function: Obtain entropy for the caller.
  518. *
  519. * This function invokes the entropy gathering logic as often to generate
  520. * as many bytes as requested by the caller. The entropy gathering logic
  521. * creates 64 bit per invocation.
  522. *
  523. * This function truncates the last 64 bit entropy value output to the exact
  524. * size specified by the caller.
  525. *
  526. * Input:
  527. * @ec Reference to entropy collector
  528. * @data pointer to buffer for storing random data -- buffer must already
  529. * exist
  530. * @len size of the buffer, specifying also the requested number of random
  531. * in bytes
  532. *
  533. * @return 0 when request is fulfilled or an error
  534. *
  535. * The following error codes can occur:
  536. * -1 entropy_collector is NULL
  537. */
  538. int jent_read_entropy(struct rand_data *ec, unsigned char *data,
  539. unsigned int len)
  540. {
  541. unsigned char *p = data;
  542. if (!ec)
  543. return -1;
  544. while (0 < len) {
  545. unsigned int tocopy;
  546. jent_gen_entropy(ec);
  547. jent_fips_test(ec);
  548. if ((DATA_SIZE_BITS / 8) < len)
  549. tocopy = (DATA_SIZE_BITS / 8);
  550. else
  551. tocopy = len;
  552. jent_memcpy(p, &ec->data, tocopy);
  553. len -= tocopy;
  554. p += tocopy;
  555. }
  556. return 0;
  557. }
  558. /***************************************************************************
  559. * Initialization logic
  560. ***************************************************************************/
  561. struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
  562. unsigned int flags)
  563. {
  564. struct rand_data *entropy_collector;
  565. entropy_collector = jent_zalloc(sizeof(struct rand_data));
  566. if (!entropy_collector)
  567. return NULL;
  568. if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
  569. /* Allocate memory for adding variations based on memory
  570. * access
  571. */
  572. entropy_collector->mem = jent_zalloc(JENT_MEMORY_SIZE);
  573. if (!entropy_collector->mem) {
  574. jent_zfree(entropy_collector);
  575. return NULL;
  576. }
  577. entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
  578. entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
  579. entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
  580. }
  581. /* verify and set the oversampling rate */
  582. if (0 == osr)
  583. osr = 1; /* minimum sampling rate is 1 */
  584. entropy_collector->osr = osr;
  585. entropy_collector->stir = 1;
  586. if (flags & JENT_DISABLE_STIR)
  587. entropy_collector->stir = 0;
  588. if (flags & JENT_DISABLE_UNBIAS)
  589. entropy_collector->disable_unbias = 1;
  590. /* fill the data pad with non-zero values */
  591. jent_gen_entropy(entropy_collector);
  592. return entropy_collector;
  593. }
  594. void jent_entropy_collector_free(struct rand_data *entropy_collector)
  595. {
  596. jent_zfree(entropy_collector->mem);
  597. entropy_collector->mem = NULL;
  598. jent_zfree(entropy_collector);
  599. entropy_collector = NULL;
  600. }
  601. int jent_entropy_init(void)
  602. {
  603. int i;
  604. __u64 delta_sum = 0;
  605. __u64 old_delta = 0;
  606. int time_backwards = 0;
  607. int count_var = 0;
  608. int count_mod = 0;
  609. /* We could perform statistical tests here, but the problem is
  610. * that we only have a few loop counts to do testing. These
  611. * loop counts may show some slight skew and we produce
  612. * false positives.
  613. *
  614. * Moreover, only old systems show potentially problematic
  615. * jitter entropy that could potentially be caught here. But
  616. * the RNG is intended for hardware that is available or widely
  617. * used, but not old systems that are long out of favor. Thus,
  618. * no statistical tests.
  619. */
  620. /*
  621. * We could add a check for system capabilities such as clock_getres or
  622. * check for CONFIG_X86_TSC, but it does not make much sense as the
  623. * following sanity checks verify that we have a high-resolution
  624. * timer.
  625. */
  626. /*
  627. * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
  628. * definitely too little.
  629. */
  630. #define TESTLOOPCOUNT 300
  631. #define CLEARCACHE 100
  632. for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
  633. __u64 time = 0;
  634. __u64 time2 = 0;
  635. __u64 folded = 0;
  636. __u64 delta = 0;
  637. unsigned int lowdelta = 0;
  638. jent_get_nstime(&time);
  639. jent_fold_time(NULL, time, &folded, 1<<MIN_FOLD_LOOP_BIT);
  640. jent_get_nstime(&time2);
  641. /* test whether timer works */
  642. if (!time || !time2)
  643. return JENT_ENOTIME;
  644. delta = time2 - time;
  645. /*
  646. * test whether timer is fine grained enough to provide
  647. * delta even when called shortly after each other -- this
  648. * implies that we also have a high resolution timer
  649. */
  650. if (!delta)
  651. return JENT_ECOARSETIME;
  652. /*
  653. * up to here we did not modify any variable that will be
  654. * evaluated later, but we already performed some work. Thus we
  655. * already have had an impact on the caches, branch prediction,
  656. * etc. with the goal to clear it to get the worst case
  657. * measurements.
  658. */
  659. if (CLEARCACHE > i)
  660. continue;
  661. /* test whether we have an increasing timer */
  662. if (!(time2 > time))
  663. time_backwards++;
  664. /*
  665. * Avoid modulo of 64 bit integer to allow code to compile
  666. * on 32 bit architectures.
  667. */
  668. lowdelta = time2 - time;
  669. if (!(lowdelta % 100))
  670. count_mod++;
  671. /*
  672. * ensure that we have a varying delta timer which is necessary
  673. * for the calculation of entropy -- perform this check
  674. * only after the first loop is executed as we need to prime
  675. * the old_data value
  676. */
  677. if (i) {
  678. if (delta != old_delta)
  679. count_var++;
  680. if (delta > old_delta)
  681. delta_sum += (delta - old_delta);
  682. else
  683. delta_sum += (old_delta - delta);
  684. }
  685. old_delta = delta;
  686. }
  687. /*
  688. * we allow up to three times the time running backwards.
  689. * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
  690. * if such an operation just happens to interfere with our test, it
  691. * should not fail. The value of 3 should cover the NTP case being
  692. * performed during our test run.
  693. */
  694. if (3 < time_backwards)
  695. return JENT_ENOMONOTONIC;
  696. /* Error if the time variances are always identical */
  697. if (!delta_sum)
  698. return JENT_EVARVAR;
  699. /*
  700. * Variations of deltas of time must on average be larger
  701. * than 1 to ensure the entropy estimation
  702. * implied with 1 is preserved
  703. */
  704. if (delta_sum <= 1)
  705. return JENT_EMINVARVAR;
  706. /*
  707. * Ensure that we have variations in the time stamp below 10 for at
  708. * least 10% of all checks -- on some platforms, the counter
  709. * increments in multiples of 100, but not always
  710. */
  711. if ((TESTLOOPCOUNT/10 * 9) < count_mod)
  712. return JENT_ECOARSETIME;
  713. return 0;
  714. }