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