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 
52 #undef _FORTIFY_SOURCE
53 #pragma GCC optimize ("O0")
54 
55 #include "jitterentropy.h"
56 
57 #ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT
58  /* only check optimization in a compilation for real work */
59  #ifdef __OPTIMIZE__
60   #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."
61  #endif
62 #endif
63 
64 #define MAJVERSION 2 /* API / ABI incompatible changes, functional changes that
65 		      * require consumer to be updated (as long as this number
66 		      * is zero, the API is not considered stable and can
67 		      * change without a bump of the major version) */
68 #define MINVERSION 1 /* API compatible, ABI may change, functional
69 		      * enhancements only, consumer can be left unchanged if
70 		      * enhancements are not considered */
71 #define PATCHLEVEL 0 /* API / ABI compatible, no functional changes, no
72 		      * enhancements, bug fixes only */
73 
74 /**
75  * jent_version() - Return machine-usable version number of jent library
76  *
77  * The function returns a version number that is monotonic increasing
78  * for newer versions. The version numbers are multiples of 100. For example,
79  * version 1.2.3 is converted to 1020300 -- the last two digits are reserved
80  * for future use.
81  *
82  * The result of this function can be used in comparing the version number
83  * in a calling program if version-specific calls need to be make.
84  *
85  * Return: Version number of kcapi library
86  */
87 JENT_PRIVATE_STATIC
jent_version(void)88 unsigned int jent_version(void)
89 {
90 	unsigned int version = 0;
91 
92 	version =  MAJVERSION * 1000000;
93 	version += MINVERSION * 10000;
94 	version += PATCHLEVEL * 100;
95 
96 	return version;
97 }
98 
99 /**
100  * Update of the loop count used for the next round of
101  * an entropy collection.
102  *
103  * Input:
104  * @ec entropy collector struct -- may be NULL
105  * @bits is the number of low bits of the timer to consider
106  * @min is the number of bits we shift the timer value to the right at
107  * 	the end to make sure we have a guaranteed minimum value
108  *
109  * @return Newly calculated loop counter
110  */
jent_loop_shuffle(struct rand_data * ec,unsigned int bits,unsigned int min)111 static uint64_t jent_loop_shuffle(struct rand_data *ec,
112 				  unsigned int bits, unsigned int min)
113 {
114 	uint64_t time = 0;
115 	uint64_t shuffle = 0;
116 	unsigned int i = 0;
117 	unsigned int mask = (1<<bits) - 1;
118 
119 	jent_get_nstime(&time);
120 	/*
121 	 * Mix the current state of the random number into the shuffle
122 	 * calculation to balance that shuffle a bit more.
123 	 */
124 	if (ec)
125 		time ^= ec->data;
126 	/*
127 	 * We fold the time value as much as possible to ensure that as many
128 	 * bits of the time stamp are included as possible.
129 	 */
130 	for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) {
131 		shuffle ^= time & mask;
132 		time = time >> bits;
133 	}
134 
135 	/*
136 	 * We add a lower boundary value to ensure we have a minimum
137 	 * RNG loop count.
138 	 */
139 	return (shuffle + (1<<min));
140 }
141 
142 /***************************************************************************
143  * Noise sources
144  ***************************************************************************/
145 
146 /**
147  * CPU Jitter noise source -- this is the noise source based on the CPU
148  * 			      execution time jitter
149  *
150  * This function injects the individual bits of the time value into the
151  * entropy pool using an LFSR.
152  *
153  * The code is deliberately inefficient with respect to the bit shifting
154  * and shall stay that way. This function is the root cause why the code
155  * shall be compiled without optimization. This function not only acts as
156  * folding operation, but this function's execution is used to measure
157  * the CPU execution time jitter. Any change to the loop in this function
158  * implies that careful retesting must be done.
159  *
160  * Input:
161  * @ec entropy collector struct -- may be NULL
162  * @time time stamp to be injected
163  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
164  *	     loops to perform the folding
165  *
166  * Output:
167  * updated ec->data
168  *
169  * @return Number of loops the folding operation is performed
170  */
jent_lfsr_time(struct rand_data * ec,uint64_t time,uint64_t loop_cnt)171 static uint64_t jent_lfsr_time(struct rand_data *ec, uint64_t time,
172 			       uint64_t loop_cnt)
173 {
174 	unsigned int i;
175 	uint64_t j = 0;
176 	uint64_t new = 0;
177 #define MAX_FOLD_LOOP_BIT 4
178 #define MIN_FOLD_LOOP_BIT 0
179 	uint64_t fold_loop_cnt =
180 		jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT);
181 
182 	/*
183 	 * testing purposes -- allow test app to set the counter, not
184 	 * needed during runtime
185 	 */
186 	if (loop_cnt)
187 		fold_loop_cnt = loop_cnt;
188 	for (j = 0; j < fold_loop_cnt; j++) {
189 		new = ec->data;
190 		for (i = 1; (DATA_SIZE_BITS) >= i; i++) {
191 			uint64_t tmp = time << (DATA_SIZE_BITS - i);
192 
193 			tmp = tmp >> (DATA_SIZE_BITS - 1);
194 
195 			/*
196 			* Fibonacci LSFR with polynomial of
197 			*  x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is
198 			*  primitive according to
199 			*   http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf
200 			* (the shift values are the polynomial values minus one
201 			* due to counting bits from 0 to 63). As the current
202 			* position is always the LSB, the polynomial only needs
203 			* to shift data in from the left without wrap.
204 			*/
205 			new ^= tmp;
206 			new ^= ((new >> 63) & 1);
207 			new ^= ((new >> 60) & 1);
208 			new ^= ((new >> 55) & 1);
209 			new ^= ((new >> 30) & 1);
210 			new ^= ((new >> 27) & 1);
211 			new ^= ((new >> 22) & 1);
212 			new = rol64(new, 1);
213 		}
214 	}
215 	ec->data = new;
216 
217 	return fold_loop_cnt;
218 }
219 
220 /**
221  * Memory Access noise source -- this is a noise source based on variations in
222  * 				 memory access times
223  *
224  * This function performs memory accesses which will add to the timing
225  * variations due to an unknown amount of CPU wait states that need to be
226  * added when accessing memory. The memory size should be larger than the L1
227  * caches as outlined in the documentation and the associated testing.
228  *
229  * The L1 cache has a very high bandwidth, albeit its access rate is  usually
230  * slower than accessing CPU registers. Therefore, L1 accesses only add minimal
231  * variations as the CPU has hardly to wait. Starting with L2, significant
232  * variations are added because L2 typically does not belong to the CPU any more
233  * and therefore a wider range of CPU wait states is necessary for accesses.
234  * L3 and real memory accesses have even a wider range of wait states. However,
235  * to reliably access either L3 or memory, the ec->mem memory must be quite
236  * large which is usually not desirable.
237  *
238  * Input:
239  * @ec Reference to the entropy collector with the memory access data -- if
240  *     the reference to the memory block to be accessed is NULL, this noise
241  *     source is disabled
242  * @loop_cnt if a value not equal to 0 is set, use the given value as number of
243  *	     loops to perform the folding
244  *
245  * @return Number of memory access operations
246  */
jent_memaccess(struct rand_data * ec,uint64_t loop_cnt)247 static unsigned int jent_memaccess(struct rand_data *ec, uint64_t loop_cnt)
248 {
249 	unsigned int wrap = 0;
250 	uint64_t i = 0;
251 #define MAX_ACC_LOOP_BIT 7
252 #define MIN_ACC_LOOP_BIT 0
253 	uint64_t acc_loop_cnt =
254 		jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT);
255 
256 	if (NULL == ec || NULL == ec->mem)
257 		return 0;
258 	wrap = ec->memblocksize * ec->memblocks;
259 
260 	/*
261 	 * testing purposes -- allow test app to set the counter, not
262 	 * needed during runtime
263 	 */
264 	if (loop_cnt)
265 		acc_loop_cnt = loop_cnt;
266 
267 	for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) {
268 		unsigned char *tmpval = ec->mem + ec->memlocation;
269 		/*
270 		 * memory access: just add 1 to one byte,
271 		 * wrap at 255 -- memory access implies read
272 		 * from and write to memory location
273 		 */
274 		*tmpval = (*tmpval + 1) & 0xff;
275 		/*
276 		 * Addition of memblocksize - 1 to pointer
277 		 * with wrap around logic to ensure that every
278 		 * memory location is hit evenly
279 		 */
280 		ec->memlocation = ec->memlocation + ec->memblocksize - 1;
281 		ec->memlocation = ec->memlocation % wrap;
282 	}
283 	return i;
284 }
285 
286 /***************************************************************************
287  * Start of entropy processing logic
288  ***************************************************************************/
289 
290 /**
291  * Stuck test by checking the:
292  * 	1st derivation of the jitter measurement (time delta)
293  * 	2nd derivation of the jitter measurement (delta of time deltas)
294  * 	3rd derivation of the jitter measurement (delta of delta of time deltas)
295  *
296  * All values must always be non-zero.
297  *
298  * Input:
299  * @ec Reference to entropy collector
300  * @current_delta Jitter time delta
301  *
302  * @return
303  * 	0 jitter measurement not stuck (good bit)
304  * 	1 jitter measurement stuck (reject bit)
305  */
jent_stuck(struct rand_data * ec,uint64_t current_delta)306 static int jent_stuck(struct rand_data *ec, uint64_t current_delta)
307 {
308 	int64_t delta2 = ec->last_delta - current_delta;
309 	int64_t delta3 = (uint64_t)delta2 - (uint64_t)ec->last_delta2;
310 
311 	ec->last_delta = current_delta;
312 	ec->last_delta2 = delta2;
313 
314 	if (!current_delta || !delta2 || !delta3)
315 		return 1;
316 
317 	return 0;
318 }
319 
320 /**
321  * This is the heart of the entropy generation: calculate time deltas and
322  * use the CPU jitter in the time deltas. The jitter is injected into the
323  * entropy pool.
324  *
325  * WARNING: ensure that ->prev_time is primed before using the output
326  * 	    of this function! This can be done by calling this function
327  * 	    and not using its result.
328  *
329  * Input:
330  * @entropy_collector Reference to entropy collector
331  *
332  * @return: result of stuck test
333  */
jent_measure_jitter(struct rand_data * ec)334 static int jent_measure_jitter(struct rand_data *ec)
335 {
336 	uint64_t time = 0;
337 	uint64_t current_delta = 0;
338 	int stuck;
339 
340 	/* Invoke one noise source before time measurement to add variations */
341 	jent_memaccess(ec, 0);
342 
343 	/*
344 	 * Get time stamp and calculate time delta to previous
345 	 * invocation to measure the timing variations
346 	 */
347 	jent_get_nstime(&time);
348 	current_delta = time - ec->prev_time;
349 	ec->prev_time = time;
350 
351 	/* Now call the next noise sources which also injects the data */
352 	jent_lfsr_time(ec, current_delta, 0);
353 
354 	/* Check whether we have a stuck measurement. */
355 	stuck = jent_stuck(ec, current_delta);
356 
357 	/*
358 	 * Rotate the data buffer by a prime number (any odd number would
359 	 * do) to ensure that every bit position of the input time stamp
360 	 * has an even chance of being merged with a bit position in the
361 	 * entropy pool. We do not use one here as the adjacent bits in
362 	 * successive time deltas may have some form of dependency. The
363 	 * chosen value of 7 implies that the low 7 bits of the next
364 	 * time delta value is concatenated with the current time delta.
365 	 */
366 	if (!stuck)
367 		ec->data = rol64(ec->data, 7);
368 
369 	return stuck;
370 }
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  */
jent_stir_pool(struct rand_data * entropy_collector)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 		uint64_t uint64;
397 		uint32_t uint32[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 	/* Ensure that the function implements a constant time operation. */
413 	union c throw_away;
414 
415 	/*
416 	 * Store the SHA-1 constants in reverse order to make up the 64 bit
417 	 * value -- this applies to a little endian system, on a big endian
418 	 * system, it reverses as expected. But this really does not matter
419 	 * as we do not rely on the specific numbers. We just pick the SHA-1
420 	 * constants as they have a good mix of bit set and unset.
421 	 */
422 	constant.uint32[1] = 0x67452301;
423 	constant.uint32[0] = 0xefcdab89;
424 	mixer.uint32[1] = 0x98badcfe;
425 	mixer.uint32[0] = 0x10325476;
426 
427 	for (i = 0; i < DATA_SIZE_BITS; i++) {
428 		/*
429 		 * get the i-th bit of the input random number and only XOR
430 		 * the constant into the mixer value when that bit is set
431 		 */
432 		if ((entropy_collector->data >> i) & 1)
433 			mixer.uint64 ^= constant.uint64;
434 		else
435 			throw_away.uint64 ^= constant.uint64;
436 		mixer.uint64 = rol64(mixer.uint64, 1);
437 	}
438 	entropy_collector->data ^= mixer.uint64;
439 }
440 
441 /**
442  * Generator of one 64 bit random number
443  * Function fills rand_data->data
444  *
445  * Input:
446  * @ec Reference to entropy collector
447  */
jent_gen_entropy(struct rand_data * ec)448 static void jent_gen_entropy(struct rand_data *ec)
449 {
450 	unsigned int k = 0;
451 
452 	/* priming of the ->prev_time value */
453 	jent_measure_jitter(ec);
454 
455 	while (1) {
456 		/* If a stuck measurement is received, repeat measurement */
457 		if (jent_measure_jitter(ec))
458 			continue;
459 
460 		/*
461 		 * We multiply the loop value with ->osr to obtain the
462 		 * oversampling rate requested by the caller
463 		 */
464 		if (++k >= (DATA_SIZE_BITS * ec->osr))
465 			break;
466 	}
467 	if (ec->stir)
468 		jent_stir_pool(ec);
469 }
470 
471 /**
472  * The continuous test required by FIPS 140-2 -- the function automatically
473  * primes the test if needed.
474  *
475  * Return:
476  * 0 if FIPS test passed
477  * < 0 if FIPS test failed
478  */
jent_fips_test(struct rand_data * ec)479 static int jent_fips_test(struct rand_data *ec)
480 {
481 	if (ec->fips_enabled == -1)
482 		return 0;
483 
484 	if (ec->fips_enabled == 0) {
485 		if (!jent_fips_enabled()) {
486 			ec->fips_enabled = -1;
487 			return 0;
488 		} else
489 			ec->fips_enabled = 1;
490 	}
491 
492 	/* prime the FIPS test */
493 	if (!ec->old_data) {
494 		ec->old_data = ec->data;
495 		jent_gen_entropy(ec);
496 	}
497 
498 	if (ec->data == ec->old_data)
499 		return -1;
500 
501 	ec->old_data = ec->data;
502 
503 	return 0;
504 }
505 
506 /**
507  * Entry function: Obtain entropy for the caller.
508  *
509  * This function invokes the entropy gathering logic as often to generate
510  * as many bytes as requested by the caller. The entropy gathering logic
511  * creates 64 bit per invocation.
512  *
513  * This function truncates the last 64 bit entropy value output to the exact
514  * size specified by the caller.
515  *
516  * Input:
517  * @ec Reference to entropy collector
518  * @data pointer to buffer for storing random data -- buffer must already
519  *        exist
520  * @len size of the buffer, specifying also the requested number of random
521  *       in bytes
522  *
523  * @return number of bytes returned when request is fulfilled or an error
524  *
525  * The following error codes can occur:
526  *	-1	entropy_collector is NULL
527  *	-2	FIPS test failed
528  */
529 JENT_PRIVATE_STATIC
jent_read_entropy(struct rand_data * ec,char * data,size_t len)530 ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len)
531 {
532 	char *p = data;
533 	size_t orig_len = len;
534 
535 	if (NULL == ec)
536 		return -1;
537 
538 	while (0 < len) {
539 		size_t tocopy;
540 
541 		jent_gen_entropy(ec);
542 		if (jent_fips_test(ec))
543 			return -2;
544 
545 		if ((DATA_SIZE_BITS / 8) < len)
546 			tocopy = (DATA_SIZE_BITS / 8);
547 		else
548 			tocopy = len;
549 		memcpy(p, &ec->data, tocopy);
550 
551 		len -= tocopy;
552 		p += tocopy;
553 	}
554 
555 	/*
556 	 * To be on the safe side, we generate one more round of entropy
557 	 * which we do not give out to the caller. That round shall ensure
558 	 * that in case the calling application crashes, memory dumps, pages
559 	 * out, or due to the CPU Jitter RNG lingering in memory for long
560 	 * time without being moved and an attacker cracks the application,
561 	 * all he reads in the entropy pool is a value that is NEVER EVER
562 	 * being used for anything. Thus, he does NOT see the previous value
563 	 * that was returned to the caller for cryptographic purposes.
564 	 */
565 	/*
566 	 * If we use secured memory, do not use that precaution as the secure
567 	 * memory protects the entropy pool. Moreover, note that using this
568 	 * call reduces the speed of the RNG by up to half
569 	 */
570 #ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY
571 	jent_gen_entropy(ec);
572 #endif
573 	return orig_len;
574 }
575 
576 /***************************************************************************
577  * Initialization logic
578  ***************************************************************************/
579 
580 JENT_PRIVATE_STATIC
jent_entropy_collector_alloc(unsigned int osr,unsigned int flags)581 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
582 					       unsigned int flags)
583 {
584 	struct rand_data *entropy_collector;
585 
586 	entropy_collector = jent_zalloc(sizeof(struct rand_data));
587 	if (NULL == entropy_collector)
588 		return NULL;
589 
590 	if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
591 		/* Allocate memory for adding variations based on memory
592 		 * access
593 		 */
594 		entropy_collector->mem =
595 			(unsigned char *)jent_zalloc(JENT_MEMORY_SIZE);
596 		if (NULL == entropy_collector->mem) {
597 			jent_zfree(entropy_collector, sizeof(struct rand_data));
598 			return NULL;
599 		}
600 		entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE;
601 		entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
602 		entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
603 	}
604 
605 	/* verify and set the oversampling rate */
606 	if (0 == osr)
607 		osr = 1; /* minimum sampling rate is 1 */
608 	entropy_collector->osr = osr;
609 
610 	entropy_collector->stir = 1;
611 	if (flags & JENT_DISABLE_STIR)
612 		entropy_collector->stir = 0;
613 	if (flags & JENT_DISABLE_UNBIAS)
614 		entropy_collector->disable_unbias = 1;
615 
616 	/* fill the data pad with non-zero values */
617 	jent_gen_entropy(entropy_collector);
618 
619 	return entropy_collector;
620 }
621 
622 JENT_PRIVATE_STATIC
jent_entropy_collector_free(struct rand_data * entropy_collector)623 void jent_entropy_collector_free(struct rand_data *entropy_collector)
624 {
625 	if (NULL != entropy_collector) {
626 		if (NULL != entropy_collector->mem) {
627 			jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE);
628 			entropy_collector->mem = NULL;
629 		}
630 		jent_zfree(entropy_collector, sizeof(struct rand_data));
631 	}
632 }
633 
634 JENT_PRIVATE_STATIC
jent_entropy_init(void)635 int jent_entropy_init(void)
636 {
637 	int i;
638 	uint64_t delta_sum = 0;
639 	uint64_t old_delta = 0;
640 	int time_backwards = 0;
641 	int count_mod = 0;
642 	int count_stuck = 0;
643 	struct rand_data ec;
644 
645 	memset(&ec, 0, sizeof(ec));
646 
647 	/* We could perform statistical tests here, but the problem is
648 	 * that we only have a few loop counts to do testing. These
649 	 * loop counts may show some slight skew and we produce
650 	 * false positives.
651 	 *
652 	 * Moreover, only old systems show potentially problematic
653 	 * jitter entropy that could potentially be caught here. But
654 	 * the RNG is intended for hardware that is available or widely
655 	 * used, but not old systems that are long out of favor. Thus,
656 	 * no statistical tests.
657 	 */
658 
659 	/*
660 	 * We could add a check for system capabilities such as clock_getres or
661 	 * check for CONFIG_X86_TSC, but it does not make much sense as the
662 	 * following sanity checks verify that we have a high-resolution
663 	 * timer.
664 	 */
665 	/*
666 	 * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is
667 	 * definitely too little.
668 	 */
669 #define TESTLOOPCOUNT 300
670 #define CLEARCACHE 100
671 	for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) {
672 		uint64_t time = 0;
673 		uint64_t time2 = 0;
674 		uint64_t delta = 0;
675 		unsigned int lowdelta = 0;
676 		int stuck;
677 
678 		/* Invoke core entropy collection logic */
679 		jent_get_nstime(&time);
680 		ec.prev_time = time;
681 		jent_lfsr_time(&ec, time, 0);
682 		jent_get_nstime(&time2);
683 
684 		/* test whether timer works */
685 		if (!time || !time2)
686 			return ENOTIME;
687 		delta = time2 - time;
688 		/*
689 		 * test whether timer is fine grained enough to provide
690 		 * delta even when called shortly after each other -- this
691 		 * implies that we also have a high resolution timer
692 		 */
693 		if (!delta)
694 			return ECOARSETIME;
695 
696 		stuck = jent_stuck(&ec, delta);
697 
698 		/*
699 		 * up to here we did not modify any variable that will be
700 		 * evaluated later, but we already performed some work. Thus we
701 		 * already have had an impact on the caches, branch prediction,
702 		 * etc. with the goal to clear it to get the worst case
703 		 * measurements.
704 		 */
705 		if (CLEARCACHE > i)
706 			continue;
707 
708 		if (stuck)
709 			count_stuck++;
710 
711 		/* test whether we have an increasing timer */
712 		if (!(time2 > time))
713 			time_backwards++;
714 
715 		/* use 32 bit value to ensure compilation on 32 bit arches */
716 		lowdelta = time2 - time;
717 		if (!(lowdelta % 100))
718 			count_mod++;
719 
720 		/*
721 		 * ensure that we have a varying delta timer which is necessary
722 		 * for the calculation of entropy -- perform this check
723 		 * only after the first loop is executed as we need to prime
724 		 * the old_data value
725 		 */
726 		if (delta > old_delta)
727 			delta_sum += (delta - old_delta);
728 		else
729 			delta_sum += (old_delta - delta);
730 		old_delta = delta;
731 	}
732 
733 	/*
734 	 * we allow up to three times the time running backwards.
735 	 * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
736 	 * if such an operation just happens to interfere with our test, it
737 	 * should not fail. The value of 3 should cover the NTP case being
738 	 * performed during our test run.
739 	 */
740 	if (3 < time_backwards)
741 		return ENOMONOTONIC;
742 
743 	/*
744 	 * Variations of deltas of time must on average be larger
745 	 * than 1 to ensure the entropy estimation
746 	 * implied with 1 is preserved
747 	 */
748 	if ((delta_sum) <= 1)
749 		return EMINVARVAR;
750 
751 	/*
752 	 * Ensure that we have variations in the time stamp below 10 for at least
753 	 * 10% of all checks -- on some platforms, the counter increments in
754 	 * multiples of 100, but not always
755 	 */
756 	if ((TESTLOOPCOUNT/10 * 9) < count_mod)
757 		return ECOARSETIME;
758 
759 	/*
760 	 * If we have more than 90% stuck results, then this Jitter RNG is
761 	 * likely to not work well.
762 	 */
763 	if (JENT_STUCK_INIT_THRES(TESTLOOPCOUNT) < count_stuck)
764 		return ESTUCK;
765 
766 	return 0;
767 }
768 
769 /***************************************************************************
770  * Statistical test logic not compiled for regular operation
771  ***************************************************************************/
772 
773 #ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT
774 /*
775  * Statistical test: return the time duration for the folding operation. If min
776  * is set, perform the given number of LFSR ops. Otherwise, allow the
777  * loop count shuffling to define the number of LFSR ops.
778  */
779 JENT_PRIVATE_STATIC
jent_lfsr_var_stat(struct rand_data * ec,unsigned int min)780 uint64_t jent_lfsr_var_stat(struct rand_data *ec, unsigned int min)
781 {
782 	uint64_t time = 0;
783 	uint64_t time2 = 0;
784 
785 	jent_get_nstime(&time);
786 	jent_memaccess(ec, min);
787 	jent_lfsr_time(ec, time, min);
788 	jent_get_nstime(&time2);
789 	return ((time2 - time));
790 }
791 #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */
792