Debian Codegraph @

random/jitterentropy-base.c

raw
1 /*
2 * Non-physical true random number generator based on timing jitter.
3 *
4 * Copyright Stephan Mueller <[email protected]>, 2014 - 2021
5 *
6 * Design
7 * ======
8 *
9 * See documentation in doc/ folder.
10 *
11 * Interface
12 * =========
13 *
14 * See documentation in jitterentropy(3) man page.
15 *
16 * License: see LICENSE file in root directory
17 *
18 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
19 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
21 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
28 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
29 * DAMAGE.
30 */
31
32 #include "jitterentropy.h"
33
34 #include "jitterentropy-base.h"
35 #include "jitterentropy-gcd.h"
36 #include "jitterentropy-health.h"
37 #include "jitterentropy-noise.h"
38 #include "jitterentropy-timer.h"
39 #include "jitterentropy-sha3.h"
40
41 #define MAJVERSION 3 /* API / ABI incompatible changes, functional changes that
42 * require consumer to be updated (as long as this number
43 * is zero, the API is not considered stable and can
44 * change without a bump of the major version) */
45 #define MINVERSION 3 /* API compatible, ABI may change, functional
46 * enhancements only, consumer can be left unchanged if
47 * enhancements are not considered */
48 #define PATCHLEVEL 0 /* API / ABI compatible, no functional changes, no
49 * enhancements, bug fixes only */
50
51 /***************************************************************************
52 * Jitter RNG Static Definitions
53 *
54 * None of the following should be altered
55 ***************************************************************************/
56
57 #ifdef __OPTIMIZE__
58 #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy.c."
59 #endif
60
61 /*
62 * JENT_POWERUP_TESTLOOPCOUNT needs some loops to identify edge
63 * systems. 100 is definitely too little.
64 *
65 * SP800-90B requires at least 1024 initial test cycles.
66 */
67 #define JENT_POWERUP_TESTLOOPCOUNT 1024
68
69 /**
70 * jent_version() - Return machine-usable version number of jent library
71 *
72 * The function returns a version number that is monotonic increasing
73 * for newer versions. The version numbers are multiples of 100. For example,
74 * version 1.2.3 is converted to 1020300 -- the last two digits are reserved
75 * for future use.
76 *
77 * The result of this function can be used in comparing the version number
78 * in a calling program if version-specific calls need to be make.
79 *
80 * @return Version number of jitterentropy library
81 */
82 JENT_PRIVATE_STATIC
83 unsigned int jent_version(void)
84 {
85 unsigned int version = 0;
86
87 version = MAJVERSION * 1000000;
88 version += MINVERSION * 10000;
89 version += PATCHLEVEL * 100;
90
91 return version;
92 }
93
94 /***************************************************************************
95 * Helper
96 ***************************************************************************/
97
98 /* Calculate log2 of given value assuming that the value is a power of 2 */
99 static inline unsigned int jent_log2_simple(unsigned int val)
100 {
101 unsigned int idx = 0;
102
103 while (val >>= 1)
104 idx++;
105 return idx;
106 }
107
108 /* Increase the memory size by one step */
109 static inline unsigned int jent_update_memsize(unsigned int flags)
110 {
111 unsigned int global_max = JENT_FLAGS_TO_MAX_MEMSIZE(
112 JENT_MAX_MEMSIZE_MAX);
113 unsigned int max;
114
115 max = JENT_FLAGS_TO_MAX_MEMSIZE(flags);
116
117 if (!max) {
118 /*
119 * The safe starting value is the amount of memory we allocated
120 * last round.
121 */
122 max = jent_log2_simple(JENT_MEMORY_SIZE);
123 /* Adjust offset */
124 max = (max > JENT_MAX_MEMSIZE_OFFSET) ?
125 max - JENT_MAX_MEMSIZE_OFFSET : 0;
126 } else {
127 max++;
128 }
129
130 max = (max > global_max) ? global_max : max;
131
132 /* Clear out the max size */
133 flags &= ~JENT_MAX_MEMSIZE_MASK;
134 /* Set the freshly calculated max size */
135 flags |= JENT_MAX_MEMSIZE_TO_FLAGS(max);
136
137 return flags;
138 }
139
140 /***************************************************************************
141 * Random Number Generation
142 ***************************************************************************/
143
144 /**
145 * Entry function: Obtain entropy for the caller.
146 *
147 * This function invokes the entropy gathering logic as often to generate
148 * as many bytes as requested by the caller. The entropy gathering logic
149 * creates 64 bit per invocation.
150 *
151 * This function truncates the last 64 bit entropy value output to the exact
152 * size specified by the caller.
153 *
154 * @ec [in] Reference to entropy collector
155 * @data [out] pointer to buffer for storing random data -- buffer must
156 * already exist
157 * @len [in] size of the buffer, specifying also the requested number of random
158 * in bytes
159 *
160 * @return number of bytes returned when request is fulfilled or an error
161 *
162 * The following error codes can occur:
163 * -1 entropy_collector is NULL
164 * -2 RCT failed
165 * -3 APT test failed
166 * -4 The timer cannot be initialized
167 * -5 LAG failure
168 */
169 JENT_PRIVATE_STATIC
170 ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len)
171 {
172 char *p = data;
173 size_t orig_len = len;
174 int ret = 0;
175
176 if (NULL == ec)
177 return -1;
178
179 if (jent_notime_settick(ec))
180 return -4;
181
182 while (len > 0) {
183 size_t tocopy;
184 unsigned int health_test_result;
185
186 jent_random_data(ec);
187
188 if ((health_test_result = jent_health_failure(ec))) {
189 if (health_test_result & JENT_RCT_FAILURE)
190 ret = -2;
191 else if (health_test_result & JENT_APT_FAILURE)
192 ret = -3;
193 else
194 ret = -5;
195
196 goto err;
197 }
198
199 if ((DATA_SIZE_BITS / 8) < len)
200 tocopy = (DATA_SIZE_BITS / 8);
201 else
202 tocopy = len;
203 memcpy(p, &ec->data, tocopy);
204
205 len -= tocopy;
206 p += tocopy;
207 }
208
209 /*
210 * To be on the safe side, we generate one more round of entropy
211 * which we do not give out to the caller. That round shall ensure
212 * that in case the calling application crashes, memory dumps, pages
213 * out, or due to the CPU Jitter RNG lingering in memory for long
214 * time without being moved and an attacker cracks the application,
215 * all he reads in the entropy pool is a value that is NEVER EVER
216 * being used for anything. Thus, he does NOT see the previous value
217 * that was returned to the caller for cryptographic purposes.
218 */
219 /*
220 * If we use secured memory, do not use that precaution as the secure
221 * memory protects the entropy pool. Moreover, note that using this
222 * call reduces the speed of the RNG by up to half
223 */
224 #ifndef JENT_CPU_JITTERENTROPY_SECURE_MEMORY
225 jent_random_data(ec);
226 #endif
227
228 err:
229 jent_notime_unsettick(ec);
230 return ret ? ret : (ssize_t)orig_len;
231 }
232
233 static struct rand_data *_jent_entropy_collector_alloc(unsigned int osr,
234 unsigned int flags);
235
236 /**
237 * Entry function: Obtain entropy for the caller.
238 *
239 * This is a service function to jent_read_entropy() with the difference
240 * that it automatically re-allocates the entropy collector if a health
241 * test failure is observed. Before reallocation, a new power-on health test
242 * is performed. The allocation of the new entropy collector automatically
243 * increases the OSR by one. This is done based on the idea that a health
244 * test failure indicates that the assumed entropy rate is too high.
245 *
246 * Note the function returns with an health test error if the OSR is
247 * getting too large. If an error is returned by this function, the Jitter RNG
248 * is not safe to be used on the current system.
249 *
250 * @ec [in] Reference to entropy collector - this is a double pointer as
251 * The entropy collector may be freed and reallocated.
252 * @data [out] pointer to buffer for storing random data -- buffer must
253 * already exist
254 * @len [in] size of the buffer, specifying also the requested number of random
255 * in bytes
256 *
257 * @return see jent_read_entropy()
258 */
259 JENT_PRIVATE_STATIC
260 ssize_t jent_read_entropy_safe(struct rand_data **ec, char *data, size_t len)
261 {
262 char *p = data;
263 size_t orig_len = len;
264 ssize_t ret = 0;
265
266 if (!ec)
267 return -1;
268
269 while (len > 0) {
270 unsigned int osr, flags, max_mem_set;
271
272 ret = jent_read_entropy(*ec, p, len);
273
274 switch (ret) {
275 case -1:
276 case -4:
277 return ret;
278 case -2:
279 case -3:
280 case -5:
281 osr = (*ec)->osr + 1;
282 flags = (*ec)->flags;
283 max_mem_set = (*ec)->max_mem_set;
284
285 /* generic arbitrary cutoff */
286 if (osr > 20)
287 return ret;
288
289 /*
290 * If the caller did not set any specific maximum value
291 * let the Jitter RNG increase the maximum memory by
292 * one step.
293 */
294 if (!max_mem_set)
295 flags = jent_update_memsize(flags);
296
297 /*
298 * re-allocate entropy collector with higher OSR and
299 * memory size
300 */
301 jent_entropy_collector_free(*ec);
302
303 /* Perform new health test with updated OSR */
304 if (jent_entropy_init_ex(osr, flags))
305 return -1;
306
307 *ec = _jent_entropy_collector_alloc(osr, flags);
308 if (!*ec)
309 return -1;
310
311 /* Remember whether caller configured memory size */
312 (*ec)->max_mem_set = !!max_mem_set;
313
314 break;
315
316 default:
317 len -= (size_t)ret;
318 p += (size_t)ret;
319 }
320 }
321
322 return (ssize_t)orig_len;
323 }
324
325 /***************************************************************************
326 * Initialization logic
327 ***************************************************************************/
328
329 /*
330 * Obtain memory size to allocate for memory access variations.
331 *
332 * The maximum variations we can get from the memory access is when we allocate
333 * a bit more memory than we have as data cache. But allocating as much
334 * memory as we have as data cache might strain the resources on the system
335 * more than necessary.
336 *
337 * On a lot of systems it is not necessary to need so much memory as the
338 * variations coming from the general Jitter RNG execution commonly provide
339 * large amount of variations.
340 *
341 * Thus, the default is:
342 *
343 * min(JENT_MEMORY_SIZE, data cache size)
344 *
345 * In case the data cache size cannot be obtained, use JENT_MEMORY_SIZE.
346 *
347 * If the caller provides a maximum memory size, use
348 * min(provided max memory, data cache size).
349 */
350 static inline uint32_t jent_memsize(unsigned int flags)
351 {
352 uint32_t memsize, max_memsize;
353
354 max_memsize = JENT_FLAGS_TO_MAX_MEMSIZE(flags);
355
356 if (max_memsize == 0) {
357 max_memsize = JENT_MEMORY_SIZE;
358 } else {
359 max_memsize = UINT32_C(1) << (max_memsize +
360 JENT_MAX_MEMSIZE_OFFSET);
361 }
362
363 /* Allocate memory for adding variations based on memory access */
364 memsize = jent_cache_size_roundup();
365
366 /* Limit the memory as defined by caller */
367 memsize = (memsize > max_memsize) ? max_memsize : memsize;
368
369 /* Set a value if none was found */
370 if (!memsize)
371 memsize = JENT_MEMORY_SIZE;
372
373 return memsize;
374 }
375
376 static int jent_selftest_run = 0;
377
378 static struct rand_data
379 *jent_entropy_collector_alloc_internal(unsigned int osr, unsigned int flags)
380 {
381 struct rand_data *entropy_collector;
382
383 /*
384 * Requesting disabling and forcing of internal timer
385 * makes no sense.
386 */
387 if ((flags & JENT_DISABLE_INTERNAL_TIMER) &&
388 (flags & JENT_FORCE_INTERNAL_TIMER))
389 return NULL;
390
391 /* Force the self test to be run */
392 if (!jent_selftest_run && jent_entropy_init_ex(osr, flags))
393 return NULL;
394
395 /*
396 * If the initial test code concludes to force the internal timer
397 * and the user requests it not to be used, do not allocate
398 * the Jitter RNG instance.
399 */
400 if (jent_notime_forced() && (flags & JENT_DISABLE_INTERNAL_TIMER))
401 return NULL;
402
403 entropy_collector = jent_zalloc(sizeof(struct rand_data));
404 if (NULL == entropy_collector)
405 return NULL;
406
407 if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) {
408 uint32_t memsize = jent_memsize(flags);
409
410 entropy_collector->mem = _gcry_calloc (1, memsize);
411 #ifdef _GCRYPT_IN_LIBGCRYPT
412 gpgrt_annotate_leaked_object (entropy_collector->mem);
413 #endif
414
415 #ifdef JENT_RANDOM_MEMACCESS
416 /*
417 * Transform the size into a mask - it is assumed that size is
418 * a power of 2.
419 */
420 entropy_collector->memmask = memsize - 1;
421 #else /* JENT_RANDOM_MEMACCESS */
422 entropy_collector->memblocksize = memsize / JENT_MEMORY_BLOCKS;
423 entropy_collector->memblocks = JENT_MEMORY_BLOCKS;
424
425 /* sanity check */
426 if (entropy_collector->memblocksize *
427 entropy_collector->memblocks != memsize)
428 goto err;
429
430 #endif /* JENT_RANDOM_MEMACCESS */
431
432 if (entropy_collector->mem == NULL)
433 goto err;
434 entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS;
435 }
436
437 /* verify and set the oversampling rate */
438 if (osr < JENT_MIN_OSR)
439 osr = JENT_MIN_OSR;
440 entropy_collector->osr = osr;
441 entropy_collector->flags = flags;
442
443 if (jent_fips_enabled() || (flags & JENT_FORCE_FIPS))
444 entropy_collector->fips_enabled = 1;
445
446 /* Initialize the APT */
447 jent_apt_init(entropy_collector, osr);
448
449 /* Initialize the Lag Predictor Test */
450 jent_lag_init(entropy_collector, osr);
451
452 /* Was jent_entropy_init run (establishing the common GCD)? */
453 if (jent_gcd_get(&entropy_collector->jent_common_timer_gcd)) {
454 /*
455 * It was not. This should probably be an error, but this
456 * behavior breaks the test code. Set the gcd to a value that
457 * won't hurt anything.
458 */
459 entropy_collector->jent_common_timer_gcd = 1;
460 }
461
462 /*
463 * Use timer-less noise source - note, OSR must be set in
464 * entropy_collector!
465 */
466 if (!(flags & JENT_DISABLE_INTERNAL_TIMER)) {
467 if (jent_notime_enable(entropy_collector, flags))
468 goto err;
469 }
470
471 return entropy_collector;
472
473 err:
474 if (entropy_collector->mem != NULL)
475 jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE);
476 jent_zfree(entropy_collector, sizeof(struct rand_data));
477 return NULL;
478 }
479
480 static struct rand_data *_jent_entropy_collector_alloc(unsigned int osr,
481 unsigned int flags)
482 {
483 struct rand_data *ec = jent_entropy_collector_alloc_internal(osr,
484 flags);
485
486 if (!ec)
487 return ec;
488
489 /* fill the data pad with non-zero values */
490 if (jent_notime_settick(ec)) {
491 jent_entropy_collector_free(ec);
492 return NULL;
493 }
494 jent_random_data(ec);
495 jent_notime_unsettick(ec);
496
497 return ec;
498 }
499
500 JENT_PRIVATE_STATIC
501 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
502 unsigned int flags)
503 {
504 struct rand_data *ec = _jent_entropy_collector_alloc(osr, flags);
505
506 /* Remember that the caller provided a maximum size flag */
507 if (ec)
508 ec->max_mem_set = !!JENT_FLAGS_TO_MAX_MEMSIZE(flags);
509
510 return ec;
511 }
512
513 JENT_PRIVATE_STATIC
514 void jent_entropy_collector_free(struct rand_data *entropy_collector)
515 {
516 if (entropy_collector != NULL) {
517 jent_notime_disable(entropy_collector);
518 if (entropy_collector->mem != NULL) {
519 jent_zfree(entropy_collector->mem,
520 jent_memsize(entropy_collector->flags));
521 entropy_collector->mem = NULL;
522 }
523 jent_zfree(entropy_collector, sizeof(struct rand_data));
524 }
525 }
526
527 int jent_time_entropy_init(unsigned int osr, unsigned int flags)
528 {
529 struct rand_data *ec;
530 uint64_t *delta_history;
531 int i, time_backwards = 0, count_stuck = 0, ret = 0;
532 unsigned int health_test_result;
533
534 delta_history = jent_gcd_init(JENT_POWERUP_TESTLOOPCOUNT);
535 if (!delta_history)
536 return EMEM;
537
538 if (flags & JENT_FORCE_INTERNAL_TIMER)
539 jent_notime_force();
540 else
541 flags |= JENT_DISABLE_INTERNAL_TIMER;
542
543 /*
544 * If the start-up health tests (including the APT and RCT) are not
545 * run, then the entropy source is not 90B compliant. We could test if
546 * fips_enabled should be set using the jent_fips_enabled() function,
547 * but this can be overridden using the JENT_FORCE_FIPS flag, which
548 * isn't passed in yet. It is better to run the tests on the small
549 * amount of data that we have, which should not fail unless things
550 * are really bad.
551 */
552 flags |= JENT_FORCE_FIPS;
553 ec = jent_entropy_collector_alloc_internal(osr, flags);
554 if (!ec) {
555 ret = EMEM;
556 goto out;
557 }
558
559 if (jent_notime_settick(ec)) {
560 ret = EMEM;
561 goto out;
562 }
563
564 /* To initialize the prior time. */
565 jent_measure_jitter(ec, 0, NULL);
566
567 /* We could perform statistical tests here, but the problem is
568 * that we only have a few loop counts to do testing. These
569 * loop counts may show some slight skew leading to false positives.
570 */
571
572 /*
573 * We could add a check for system capabilities such as clock_getres or
574 * check for CONFIG_X86_TSC, but it does not make much sense as the
575 * following sanity checks verify that we have a high-resolution
576 * timer.
577 */
578 #define CLEARCACHE 100
579 for (i = -CLEARCACHE; i < JENT_POWERUP_TESTLOOPCOUNT; i++) {
580 uint64_t start_time = 0, end_time = 0, delta = 0;
581 unsigned int stuck;
582
583 /* Invoke core entropy collection logic */
584 stuck = jent_measure_jitter(ec, 0, &delta);
585 end_time = ec->prev_time;
586 start_time = ec->prev_time - delta;
587
588 /* test whether timer works */
589 if (!start_time || !end_time) {
590 ret = ENOTIME;
591 goto out;
592 }
593
594 /*
595 * test whether timer is fine grained enough to provide
596 * delta even when called shortly after each other -- this
597 * implies that we also have a high resolution timer
598 */
599 if (!delta || (end_time == start_time)) {
600 ret = ECOARSETIME;
601 goto out;
602 }
603
604 /*
605 * up to here we did not modify any variable that will be
606 * evaluated later, but we already performed some work. Thus we
607 * already have had an impact on the caches, branch prediction,
608 * etc. with the goal to clear it to get the worst case
609 * measurements.
610 */
611 if (i < 0)
612 continue;
613
614 if (stuck)
615 count_stuck++;
616
617 /* test whether we have an increasing timer */
618 if (!(end_time > start_time))
619 time_backwards++;
620
621 /* Watch for common adjacent GCD values */
622 jent_gcd_add_value(delta_history, delta, i);
623 }
624
625 /*
626 * we allow up to three times the time running backwards.
627 * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus,
628 * if such an operation just happens to interfere with our test, it
629 * should not fail. The value of 3 should cover the NTP case being
630 * performed during our test run.
631 */
632 if (time_backwards > 3) {
633 ret = ENOMONOTONIC;
634 goto out;
635 }
636
637 /* First, did we encounter a health test failure? */
638 if ((health_test_result = jent_health_failure(ec))) {
639 ret = (health_test_result & JENT_RCT_FAILURE) ? ERCT : EHEALTH;
640 goto out;
641 }
642
643 ret = jent_gcd_analyze(delta_history, JENT_POWERUP_TESTLOOPCOUNT);
644 if (ret)
645 goto out;
646
647 /*
648 * If we have more than 90% stuck results, then this Jitter RNG is
649 * likely to not work well.
650 */
651 if (JENT_STUCK_INIT_THRES(JENT_POWERUP_TESTLOOPCOUNT) < count_stuck)
652 ret = ESTUCK;
653
654 out:
655 jent_gcd_fini(delta_history, JENT_POWERUP_TESTLOOPCOUNT);
656
657 if ((flags & JENT_FORCE_INTERNAL_TIMER) && ec)
658 jent_notime_unsettick(ec);
659
660 jent_entropy_collector_free(ec);
661
662 return ret;
663 }
664
665 static inline int jent_entropy_init_common_pre(void)
666 {
667 int ret;
668
669 jent_notime_block_switch();
670
671 if (sha3_tester())
672 return EHASH;
673
674 ret = jent_gcd_selftest();
675
676 jent_selftest_run = 1;
677
678 return ret;
679 }
680
681 static inline int jent_entropy_init_common_post(int ret)
682 {
683 /* Unmark the execution of the self tests if they failed. */
684 if (ret)
685 jent_selftest_run = 0;
686
687 return ret;
688 }
689
690 JENT_PRIVATE_STATIC
691 int jent_entropy_init(void)
692 {
693 int ret = jent_entropy_init_common_pre();
694
695 if (ret)
696 return ret;
697
698 ret = jent_time_entropy_init(0, JENT_DISABLE_INTERNAL_TIMER);
699
700 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
701 if (ret)
702 ret = jent_time_entropy_init(0, JENT_FORCE_INTERNAL_TIMER);
703 #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
704
705 return jent_entropy_init_common_post(ret);
706 }
707
708 JENT_PRIVATE_STATIC
709 int jent_entropy_init_ex(unsigned int osr, unsigned int flags)
710 {
711 int ret = jent_entropy_init_common_pre();
712
713 if (ret)
714 return ret;
715
716 /* Test without internal timer unless caller does not want it */
717 if (!(flags & JENT_FORCE_INTERNAL_TIMER))
718 ret = jent_time_entropy_init(osr,
719 flags | JENT_DISABLE_INTERNAL_TIMER);
720
721 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
722 /* Test with internal timer unless caller does not want it */
723 if (ret && !(flags & JENT_DISABLE_INTERNAL_TIMER))
724 ret = jent_time_entropy_init(osr,
725 flags | JENT_FORCE_INTERNAL_TIMER);
726 #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
727
728 return jent_entropy_init_common_post(ret);
729 }
730
731 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
732 JENT_PRIVATE_STATIC
733 int jent_entropy_switch_notime_impl(struct jent_notime_thread *new_thread)
734 {
735 return jent_notime_switch(new_thread);
736 }
737 #endif