1 /*
2  * Non-physical true random number generator based on timing jitter.
3  *
4  * Copyright Stephan Mueller <smueller@chronox.de>, 2014 - 2017
5  *
6  * Design
7  * ======
8  *
9  * See documentation in doc/ folder.
10  *
11  * Interface
12  * =========
13  *
14  * See documentation in doc/ folder.
15  *
16  * License
17  * =======
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, and the entire permission notice in its entirety,
24  *    including the disclaimer of warranties.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  * 3. The name of the author may not be used to endorse or promote
29  *    products derived from this software without specific prior
30  *    written permission.
31  *
32  * ALTERNATIVELY, this product may be distributed under the terms of
33  * the GNU General Public License, in which case the provisions of the GPL2 are
34  * required INSTEAD OF the above restrictions.  (This clause is
35  * necessary due to a potential bad interaction between the GPL and
36  * the restrictions contained in a BSD-style copyright.)
37  *
38  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
39  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
40  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
41  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
42  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
43  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
44  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
45  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
46  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
47  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
48  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
49  * DAMAGE.
50  *
51  * Modifications by the Fuchsia Authors, 2017
52  * =======
53  *
54  * - Add #include lines for stdlib.h, string.h, and internal.h.
55  * - Change #include line for Zircon file conventions.
56  * - Remove CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT flag.
57  * - Add jent_entropy_collector_init definition.
58  * - Remove '#pragma GCC optimize ("O0")' (not recognized by clang)
59  * - Replace 'min' parameter by 'lfsr_loops_override' and 'mem_loops_override'
60  *   in jent_lfsr_var_stat, and moved comment for jent_lfsr_var_stat to
61  *   jitterentropy.h.
62  * - Add jent_have_clock check to jent_entropy_init.
63  */
64 
65 #undef _FORTIFY_SOURCE
66 
67 #include <assert.h>
68 #include <lib/jitterentropy/jitterentropy.h>
69 #include "internal.h"
70 #include <stdlib.h>
71 #include <string.h>
72 
73  /* only check optimization in a compilation for real work */
74  #ifdef __OPTIMIZE__
75   #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy-base.c."
76  #endif
77 
78 #define MAJVERSION 2 /* API / ABI incompatible changes, functional changes that
79 		      * require consumer to be updated (as long as this number
80 		      * is zero, the API is not considered stable and can
81 		      * change without a bump of the major version) */
82 #define MINVERSION 1 /* API compatible, ABI may change, functional
83 		      * enhancements only, consumer can be left unchanged if
84 		      * enhancements are not considered */
85 #define PATCHLEVEL 0 /* API / ABI compatible, no functional changes, no
86 		      * enhancements, bug fixes only */
87 
88 /**
89  * jent_version() - Return machine-usable version number of jent library
90  *
91  * The function returns a version number that is monotonic increasing
92  * for newer versions. The version numbers are multiples of 100. For example,
93  * version 1.2.3 is converted to 1020300 -- the last two digits are reserved
94  * for future use.
95  *
96  * The result of this function can be used in comparing the version number
97  * in a calling program if version-specific calls need to be make.
98  *
99  * Return: Version number of kcapi library
100  */
101 JENT_PRIVATE_STATIC
jent_version(void)102 unsigned int jent_version(void)
103 {
104 	unsigned int version = 0;
105 
106 	version =  MAJVERSION * 1000000;
107 	version += MINVERSION * 10000;
108 	version += PATCHLEVEL * 100;
109 
110 	return version;
111 }
112 
113 /**
114  * Update of the loop count used for the next round of
115  * an entropy collection.
116  *
117  * Input:
118  * @ec entropy collector struct -- may be NULL
119  * @bits is the number of low bits of the timer to consider
120  * @min is the number of bits we shift the timer value to the right at
121  * 	the end to make sure we have a guaranteed minimum value
122  *
123  * @return Newly calculated loop counter
124  */
jent_loop_shuffle(struct rand_data * ec,unsigned int bits,unsigned int min)125 static uint64_t jent_loop_shuffle(struct rand_data *ec,
126 				  unsigned int bits, unsigned int min)
127 {
128 	uint64_t time = 0;
129 	uint64_t shuffle = 0;
130 	unsigned int i = 0;
131 	unsigned int mask = (1<<bits) - 1;
132 
133 	jent_get_nstime(&time);
134 	/*
135 	 * Mix the current state of the random number into the shuffle
136 	 * calculation to balance that shuffle a bit more.
137 	 */
138 	if (ec)
139 		time ^= ec->data;
140 	/*
141 	 * We fold the time value as much as possible to ensure that as many
142 	 * bits of the time stamp are included as possible.
143 	 */
144 	for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) {
145 		shuffle ^= time & mask;
146 		time = time >> bits;
147 	}
148 
149 	/*
150 	 * We add a lower boundary value to ensure we have a minimum
151 	 * RNG loop count.
152 	 */
153 	return (shuffle + (1<<min));
154 }
155 
156 /***************************************************************************
157  * Noise sources
158  ***************************************************************************/
159 
160 /**
161  * CPU Jitter noise source -- this is the noise source based on the CPU
162  * 			      execution time jitter
163  *
164  * This function injects the individual bits of the time value into the
165  * entropy pool using an LFSR.
166  *
167  * The code is deliberately inefficient with respect to the bit shifting
168  * and shall stay that way. This function is the root cause why the code
169  * shall be compiled without optimization. This function not only acts as
170  * folding operation, but this function's execution is used to measure
171  * the CPU execution time jitter. Any change to the loop in this function
172  * implies that careful retesting must be done.
173  *
174  * Input:
175  * @ec entropy collector struct -- may be NULL
176  * @time time stamp to be injected
177  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
178  *	     loops to perform the folding
179  *
180  * Output:
181  * updated ec->data
182  *
183  * @return Number of loops the folding operation is performed
184  */
jent_lfsr_time(struct rand_data * ec,uint64_t time,uint64_t loop_cnt)185 static uint64_t jent_lfsr_time(struct rand_data *ec, uint64_t time,
186 			       uint64_t loop_cnt)
187 {
188 	unsigned int i;
189 	uint64_t j = 0;
190 	uint64_t new = 0;
191 #define MAX_FOLD_LOOP_BIT 4
192 #define MIN_FOLD_LOOP_BIT 0
193 	uint64_t fold_loop_cnt =
194 		jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT);
195 
196 	/*
197 	 * testing purposes -- allow test app to set the counter, not
198 	 * needed during runtime
199 	 */
200 	if (loop_cnt)
201 		fold_loop_cnt = loop_cnt;
202 	for (j = 0; j < fold_loop_cnt; j++) {
203 		new = ec->data;
204 		for (i = 1; (DATA_SIZE_BITS) >= i; i++) {
205 			uint64_t tmp = time << (DATA_SIZE_BITS - i);
206 
207 			tmp = tmp >> (DATA_SIZE_BITS - 1);
208 
209 			/*
210 			* Fibonacci LSFR with polynomial of
211 			*  x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is
212 			*  primitive according to
213 			*   http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf
214 			* (the shift values are the polynomial values minus one
215 			* due to counting bits from 0 to 63). As the current
216 			* position is always the LSB, the polynomial only needs
217 			* to shift data in from the left without wrap.
218 			*/
219 			new ^= tmp;
220 			new ^= ((new >> 63) & 1);
221 			new ^= ((new >> 60) & 1);
222 			new ^= ((new >> 55) & 1);
223 			new ^= ((new >> 30) & 1);
224 			new ^= ((new >> 27) & 1);
225 			new ^= ((new >> 22) & 1);
226 			new = rol64(new, 1);
227 		}
228 	}
229 	ec->data = new;
230 
231 	return fold_loop_cnt;
232 }
233 
234 /**
235  * Memory Access noise source -- this is a noise source based on variations in
236  * 				 memory access times
237  *
238  * This function performs memory accesses which will add to the timing
239  * variations due to an unknown amount of CPU wait states that need to be
240  * added when accessing memory. The memory size should be larger than the L1
241  * caches as outlined in the documentation and the associated testing.
242  *
243  * The L1 cache has a very high bandwidth, albeit its access rate is  usually
244  * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
245  * variations as the CPU has hardly to wait. Starting with L2, significant
246  * variations are added because L2 typically does not belong to the CPU any more
247  * and therefore a wider range of CPU wait states is necessary for accesses.
248  * L3 and real memory accesses have even a wider range of wait states. However,
249  * to reliably access either L3 or memory, the ec->mem memory must be quite
250  * large which is usually not desirable.
251  *
252  * Input:
253  * @ec Reference to the entropy collector with the memory access data -- if
254  *     the reference to the memory block to be accessed is NULL, this noise
255  *     source is disabled
256  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
257  *	     loops to perform the folding
258  *
259  * @return Number of memory access operations
260  */
jent_memaccess(struct rand_data * ec,uint64_t loop_cnt)261 static unsigned int jent_memaccess(struct rand_data *ec, uint64_t loop_cnt)
262 {
263 	unsigned int wrap = 0;
264 	uint64_t i = 0;
265 #define MAX_ACC_LOOP_BIT 7
266 #define MIN_ACC_LOOP_BIT 0
267 	uint64_t acc_loop_cnt =
268 		jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
269 
270 	if (NULL == ec || NULL == ec->mem)
271 		return 0;
272 	wrap = ec->memblocksize * ec->memblocks;
273 
274 	/*
275 	 * testing purposes -- allow test app to set the counter, not
276 	 * needed during runtime
277 	 */
278 	if (loop_cnt)
279 		acc_loop_cnt = loop_cnt;
280 
281 	for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
282 		unsigned char *tmpval = ec->mem + ec->memlocation;
283 		/*
284 		 * memory access: just add 1 to one byte,
285 		 * wrap at 255 -- memory access implies read
286 		 * from and write to memory location
287 		 */
288 		*tmpval = (*tmpval + 1) & 0xff;
289 		/*
290 		 * Addition of memblocksize - 1 to pointer
291 		 * with wrap around logic to ensure that every
292 		 * memory location is hit evenly
293 		 */
294 		ec->memlocation = ec->memlocation + ec->memblocksize - 1;
295 		ec->memlocation = ec->memlocation % wrap;
296 	}
297 	return i;
298 }
299 
300 /***************************************************************************
301  * Start of entropy processing logic
302  ***************************************************************************/
303 
304 /**
305  * Stuck test by checking the:
306  * 	1st derivation of the jitter measurement (time delta)
307  * 	2nd derivation of the jitter measurement (delta of time deltas)
308  * 	3rd derivation of the jitter measurement (delta of delta of time deltas)
309  *
310  * All values must always be non-zero.
311  *
312  * Input:
313  * @ec Reference to entropy collector
314  * @current_delta Jitter time delta
315  *
316  * @return
317  * 	0 jitter measurement not stuck (good bit)
318  * 	1 jitter measurement stuck (reject bit)
319  */
jent_stuck(struct rand_data * ec,uint64_t current_delta)320 static int jent_stuck(struct rand_data *ec, uint64_t current_delta)
321 {
322 	int64_t delta2 = ec->last_delta - current_delta;
323 	int64_t delta3 = delta2 - ec->last_delta2;
324 
325 	ec->last_delta = current_delta;
326 	ec->last_delta2 = delta2;
327 
328 	if (!current_delta || !delta2 || !delta3)
329 		return 1;
330 
331 	return 0;
332 }
333 
334 /**
335  * This is the heart of the entropy generation: calculate time deltas and
336  * use the CPU jitter in the time deltas. The jitter is injected into the
337  * entropy pool.
338  *
339  * WARNING: ensure that ->prev_time is primed before using the output
340  * 	    of this function! This can be done by calling this function
341  * 	    and not using its result.
342  *
343  * Input:
344  * @entropy_collector Reference to entropy collector
345  *
346  * @return: result of stuck test
347  */
jent_measure_jitter(struct rand_data * ec)348 static int jent_measure_jitter(struct rand_data *ec)
349 {
350 	uint64_t time = 0;
351 	uint64_t current_delta = 0;
352 	int stuck;
353 
354 	/* Invoke one noise source before time measurement to add variations */
355 	jent_memaccess(ec, 0);
356 
357 	/*
358 	 * Get time stamp and calculate time delta to previous
359 	 * invocation to measure the timing variations
360 	 */
361 	jent_get_nstime(&time);
362 	current_delta = time - ec->prev_time;
363 	ec->prev_time = time;
364 
365 	/* Now call the next noise sources which also injects the data */
366 	jent_lfsr_time(ec, current_delta, 0);
367 
368 	/* Check whether we have a stuck measurement. */
369 	stuck = jent_stuck(ec, current_delta);
370 
371 	/*
372 	 * Rotate the data buffer by a prime number (any odd number would
373 	 * do) to ensure that every bit position of the input time stamp
374 	 * has an even chance of being merged with a bit position in the
375 	 * entropy pool. We do not use one here as the adjacent bits in
376 	 * successive time deltas may have some form of dependency. The
377 	 * chosen value of 7 implies that the low 7 bits of the next
378 	 * time delta value is concatenated with the current time delta.
379 	 */
380 	if (!stuck)
381 		ec->data = rol64(ec->data, 7);
382 
383 	return stuck;
384 }
385 
386 /**
387  * Shuffle the pool a bit by mixing some value with a bijective function (XOR)
388  * into the pool.
389  *
390  * The function generates a mixer value that depends on the bits set and the
391  * location of the set bits in the random number generated by the entropy
392  * source. Therefore, based on the generated random number, this mixer value
393  * can have 2**64 different values. That mixer value is initialized with the
394  * first two SHA-1 constants. After obtaining the mixer value, it is XORed into
395  * the random number.
396  *
397  * The mixer value is not assumed to contain any entropy. But due to the XOR
398  * operation, it can also not destroy any entropy present in the entropy pool.
399  *
400  * Input:
401  * @entropy_collector Reference to entropy collector
402  */
jent_stir_pool(struct rand_data * entropy_collector)403 static void jent_stir_pool(struct rand_data *entropy_collector)
404 {
405 	/*
406 	 * to shut up GCC on 32 bit, we have to initialize the 64 variable
407 	 * with two 32 bit variables
408 	 */
409 	union c {
410 		uint64_t uint64;
411 		uint32_t uint32[2];
412 	};
413 	/*
414 	 * This constant is derived from the first two 32 bit initialization
415 	 * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1
416 	 */
417 	union c constant;
418 	/*
419 	 * The start value of the mixer variable is derived from the third
420 	 * and fourth 32 bit initialization vector of SHA-1 as defined in
421 	 * FIPS 180-4 section 5.3.1
422 	 */
423 	union c mixer;
424 	unsigned int i = 0;
425 
426 	/* Ensure that the function implements a constant time operation. */
427 	union c throw_away;
428 
429 	/*
430 	 * Store the SHA-1 constants in reverse order to make up the 64 bit
431 	 * value -- this applies to a little endian system, on a big endian
432 	 * system, it reverses as expected. But this really does not matter
433 	 * as we do not rely on the specific numbers. We just pick the SHA-1
434 	 * constants as they have a good mix of bit set and unset.
435 	 */
436 	constant.uint32[1] = 0x67452301;
437 	constant.uint32[0] = 0xefcdab89;
438 	mixer.uint32[1] = 0x98badcfe;
439 	mixer.uint32[0] = 0x10325476;
440 
441 	for (i = 0; i < DATA_SIZE_BITS; i++) {
442 		/*
443 		 * get the i-th bit of the input random number and only XOR
444 		 * the constant into the mixer value when that bit is set
445 		 */
446 		if ((entropy_collector->data >> i) & 1)
447 			mixer.uint64 ^= constant.uint64;
448 		else
449 			throw_away.uint64 ^= constant.uint64;
450 		mixer.uint64 = rol64(mixer.uint64, 1);
451 	}
452 	entropy_collector->data ^= mixer.uint64;
453 }
454 
455 /**
456  * Generator of one 64 bit random number
457  * Function fills rand_data->data
458  *
459  * Input:
460  * @ec Reference to entropy collector
461  */
jent_gen_entropy(struct rand_data * ec)462 static void jent_gen_entropy(struct rand_data *ec)
463 {
464 	unsigned int k = 0;
465 
466 	/* priming of the ->prev_time value */
467 	jent_measure_jitter(ec);
468 
469 	while (1) {
470 		/* If a stuck measurement is received, repeat measurement */
471 		if (jent_measure_jitter(ec))
472 			continue;
473 
474 		/*
475 		 * We multiply the loop value with ->osr to obtain the
476 		 * oversampling rate requested by the caller
477 		 */
478 		if (++k >= (DATA_SIZE_BITS * ec->osr))
479 			break;
480 	}
481 	if (ec->stir)
482 		jent_stir_pool(ec);
483 }
484 
485 /**
486  * The continuous test required by FIPS 140-2 -- the function automatically
487  * primes the test if needed.
488  *
489  * Return:
490  * 0 if FIPS test passed
491  * < 0 if FIPS test failed
492  */
jent_fips_test(struct rand_data * ec)493 static int jent_fips_test(struct rand_data *ec)
494 {
495 	if (ec->fips_enabled == -1)
496 		return 0;
497 
498 	if (ec->fips_enabled == 0) {
499 		if (!jent_fips_enabled()) {
500 			ec->fips_enabled = -1;
501 			return 0;
502 		} else
503 			ec->fips_enabled = 1;
504 	}
505 
506 	/* prime the FIPS test */
507 	if (!ec->old_data) {
508 		ec->old_data = ec->data;
509 		jent_gen_entropy(ec);
510 	}
511 
512 	if (ec->data == ec->old_data)
513 		return -1;
514 
515 	ec->old_data = ec->data;
516 
517 	return 0;
518 }
519 
520 /**
521  * Entry function: Obtain entropy for the caller.
522  *
523  * This function invokes the entropy gathering logic as often to generate
524  * as many bytes as requested by the caller. The entropy gathering logic
525  * creates 64 bit per invocation.
526  *
527  * This function truncates the last 64 bit entropy value output to the exact
528  * size specified by the caller.
529  *
530  * Input:
531  * @ec Reference to entropy collector
532  * @data pointer to buffer for storing random data -- buffer must already
533  *        exist
534  * @len size of the buffer, specifying also the requested number of random
535  *       in bytes
536  *
537  * @return number of bytes returned when request is fulfilled or an error
538  *
539  * The following error codes can occur:
540  *	-1	entropy_collector is NULL
541  *	-2	FIPS test failed
542  */
543 JENT_PRIVATE_STATIC
jent_read_entropy(struct rand_data * ec,char * data,size_t len)544 ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len)
545 {
546 	char *p = data;
547 	size_t orig_len = len;
548 
549 	if (NULL == ec)
550 		return -1;
551 
552 	while (0 < len) {
553 		size_t tocopy;
554 
555 		jent_gen_entropy(ec);
556 		if (jent_fips_test(ec))
557 			return -2;
558 
559 		if ((DATA_SIZE_BITS / 8) < len)
560 			tocopy = (DATA_SIZE_BITS / 8);
561 		else
562 			tocopy = len;
563 		memcpy(p, &ec->data, tocopy);
564 
565 		len -= tocopy;
566 		p += tocopy;
567 	}
568 
569 	/*
570 	 * To be on the safe side, we generate one more round of entropy
571 	 * which we do not give out to the caller. That round shall ensure
572 	 * that in case the calling application crashes, memory dumps, pages
573 	 * out, or due to the CPU Jitter RNG lingering in memory for long
574 	 * time without being moved and an attacker cracks the application,
575 	 * all he reads in the entropy pool is a value that is NEVER EVER
576 	 * being used for anything. Thus, he does NOT see the previous value
577 	 * that was returned to the caller for cryptographic purposes.
578 	 */
579 	/*
580 	 * If we use secured memory, do not use that precaution as the secure
581 	 * memory protects the entropy pool. Moreover, note that using this
582 	 * call reduces the speed of the RNG by up to half
583 	 */
584 #ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
585 	jent_gen_entropy(ec);
586 #endif
587 	return orig_len;
588 }
589 
590 /***************************************************************************
591  * Initialization logic
592  ***************************************************************************/
593 
594 JENT_PRIVATE_STATIC
jent_entropy_collector_alloc(unsigned int osr,unsigned int flags)595 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
596 					       unsigned int flags)
597 {
598 	struct rand_data *entropy_collector;
599 
600 	entropy_collector = jent_zalloc(sizeof(struct rand_data));
601 	if (NULL == entropy_collector)
602 		return NULL;
603 
604 	if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
605 		/* Allocate memory for adding variations based on memory
606 		 * access
607 		 */
608 		entropy_collector->mem =
609 			(unsigned char *)jent_zalloc(JENT_MEMORY_SIZE);
610 		if (NULL == entropy_collector->mem) {
611 			jent_zfree(entropy_collector, sizeof(struct rand_data));
612 			return NULL;
613 		}
614 		entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
615 		entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
616 		entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
617 	}
618 
619 	/* verify and set the oversampling rate */
620 	if (0 == osr)
621 		osr = 1; /* minimum sampling rate is 1 */
622 	entropy_collector->osr = osr;
623 
624 	entropy_collector->stir = 1;
625 	if (flags & JENT_DISABLE_STIR)
626 		entropy_collector->stir = 0;
627 	if (flags & JENT_DISABLE_UNBIAS)
628 		entropy_collector->disable_unbias = 1;
629 
630 	/* fill the data pad with non-zero values */
631 	jent_gen_entropy(entropy_collector);
632 
633 	return entropy_collector;
634 }
635 
636 JENT_PRIVATE_STATIC
jent_entropy_collector_free(struct rand_data * entropy_collector)637 void jent_entropy_collector_free(struct rand_data *entropy_collector)
638 {
639 	if (NULL != entropy_collector) {
640 		if (NULL != entropy_collector->mem) {
641 			jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE);
642 			entropy_collector->mem = NULL;
643 		}
644 		jent_zfree(entropy_collector, sizeof(struct rand_data));
645 	}
646 }
647 
648 JENT_PRIVATE_STATIC
jent_entropy_init(void)649 int jent_entropy_init(void)
650 {
651 	int i;
652 	uint64_t delta_sum = 0;
653 	uint64_t old_delta = 0;
654 	int time_backwards = 0;
655 	int count_mod = 0;
656 	int count_stuck = 0;
657 	struct rand_data ec;
658 
659 	if (!jent_have_clock()) {
660 		return ENOTIME;
661 	}
662 
663 	/* We could perform statistical tests here, but the problem is
664 	 * that we only have a few loop counts to do testing. These
665 	 * loop counts may show some slight skew and we produce
666 	 * false positives.
667 	 *
668 	 * Moreover, only old systems show potentially problematic
669 	 * jitter entropy that could potentially be caught here. But
670 	 * the RNG is intended for hardware that is available or widely
671 	 * used, but not old systems that are long out of favor. Thus,
672 	 * no statistical tests.
673 	 */
674 
675 	/*
676 	 * We could add a check for system capabilities such as clock_getres or
677 	 * check for CONFIG_X86_TSC, but it does not make much sense as the
678 	 * following sanity checks verify that we have a high-resolution
679 	 * timer.
680 	 */
681 	/*
682 	 * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
683 	 * definitely too little.
684 	 */
685 #define TESTLOOPCOUNT 300
686 #define CLEARCACHE 100
687 	for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
688 		uint64_t time = 0;
689 		uint64_t time2 = 0;
690 		uint64_t delta = 0;
691 		unsigned int lowdelta = 0;
692 		int stuck;
693 
694 		/* Invoke core entropy collection logic */
695 		jent_get_nstime(&time);
696 		ec.prev_time = time;
697 		jent_lfsr_time(&ec, time, 0);
698 		jent_get_nstime(&time2);
699 
700 		/* test whether timer works */
701 		if (!time || !time2)
702 			return ENOTIME;
703 		delta = time2 - time;
704 		/*
705 		 * test whether timer is fine grained enough to provide
706 		 * delta even when called shortly after each other -- this
707 		 * implies that we also have a high resolution timer
708 		 */
709 		if (!delta)
710 			return ECOARSETIME;
711 
712 		stuck = jent_stuck(&ec, delta);
713 
714 		/*
715 		 * up to here we did not modify any variable that will be
716 		 * evaluated later, but we already performed some work. Thus we
717 		 * already have had an impact on the caches, branch prediction,
718 		 * etc. with the goal to clear it to get the worst case
719 		 * measurements.
720 		 */
721 		if (CLEARCACHE > i)
722 			continue;
723 
724 		if (stuck)
725 			count_stuck++;
726 
727 		/* test whether we have an increasing timer */
728 		if (!(time2 > time))
729 			time_backwards++;
730 
731 		/* use 32 bit value to ensure compilation on 32 bit arches */
732 		lowdelta = time2 - time;
733 		if (!(lowdelta % 100))
734 			count_mod++;
735 
736 		/*
737 		 * ensure that we have a varying delta timer which is necessary
738 		 * for the calculation of entropy -- perform this check
739 		 * only after the first loop is executed as we need to prime
740 		 * the old_data value
741 		 */
742 		if (delta > old_delta)
743 			delta_sum += (delta - old_delta);
744 		else
745 			delta_sum += (old_delta - delta);
746 		old_delta = delta;
747 	}
748 
749 	/*
750 	 * we allow up to three times the time running backwards.
751 	 * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
752 	 * if such an operation just happens to interfere with our test, it
753 	 * should not fail. The value of 3 should cover the NTP case being
754 	 * performed during our test run.
755 	 */
756 	if (3 < time_backwards)
757 		return ENOMONOTONIC;
758 
759 	/*
760 	 * Variations of deltas of time must on average be larger
761 	 * than 1 to ensure the entropy estimation
762 	 * implied with 1 is preserved
763 	 */
764 	if ((delta_sum) <= 1)
765 		return EMINVARVAR;
766 
767 	/*
768 	 * Ensure that we have variations in the time stamp below 10 for at least
769 	 * 10% of all checks -- on some platforms, the counter increments in
770 	 * multiples of 100, but not always
771 	 */
772 	if ((TESTLOOPCOUNT/10 * 9) < count_mod)
773 		return ECOARSETIME;
774 
775 	/*
776 	 * If we have more than 90% stuck results, then this Jitter RNG is
777 	 * likely to not work well.
778 	 */
779 	if (JENT_STUCK_INIT_THRES(TESTLOOPCOUNT) < count_stuck)
780 		return ESTUCK;
781 
782 	return 0;
783 }
784 
785 /***************************************************************************
786  * Statistical test logic not compiled for regular operation
787  ***************************************************************************/
788 
789 JENT_PRIVATE_STATIC
jent_lfsr_var_stat(struct rand_data * ec,unsigned int lfsr_loops_override,unsigned int mem_loops_override)790 uint64_t jent_lfsr_var_stat(struct rand_data *ec,
791                             unsigned int lfsr_loops_override,
792                             unsigned int mem_loops_override)
793 {
794 	uint64_t time = 0;
795 	uint64_t time2 = 0;
796 
797 	jent_get_nstime(&time);
798 	jent_memaccess(ec, mem_loops_override);
799 	jent_lfsr_time(ec, time, lfsr_loops_override);
800 	jent_get_nstime(&time2);
801 	return ((time2 - time));
802 }
803 
804 /***************************************************************************
805  * Zircon interface
806  ***************************************************************************/
807 
jent_entropy_collector_init(struct rand_data * ec,uint8_t * mem,size_t mem_size,unsigned int mem_block_size,unsigned int mem_block_count,unsigned int mem_loops,bool stir)808 void jent_entropy_collector_init(
809         struct rand_data* ec, uint8_t* mem, size_t mem_size,
810         unsigned int mem_block_size, unsigned int mem_block_count,
811         unsigned int mem_loops, bool stir) {
812     DEBUG_ASSERT(((size_t)mem_block_size) * mem_block_count <= mem_size);
813     memset(ec, 0, sizeof(*ec));
814     /* Oversample rate. The jitterentropy man page (not included with Zircon)
815      * suggests a value of 1. Higher values cause jitterentropy to discount its
816      * entropy estimates by a factor of osr, so that more random bytes are
817      * collected than would be with osr == 1. */
818     ec->osr = 1;
819     /* For now, we don't enable the FIPS 140-2 test mode built into
820      * jitterentropy. Zircon should handle entropy source health tests itself,
821      * to ensure uniform testing of all entropy sources. */
822     ec->fips_enabled = 0;
823     ec->stir = stir;
824     /* von Neumann unbiasing is never performed, and the disable_unbias flag is
825      * never even checked. To avoid confusion, always set the flag to true. */
826     ec->disable_unbias = true;
827     ec->mem = mem;
828     ec->memlocation = 0;
829     ec->memblocks = mem_block_count;
830     ec->memblocksize = mem_block_size;
831     ec->memaccessloops = mem_loops;
832 }
833