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