Debian Codegraph @

random/jitterentropy.h

raw
1 /*
2 * Non-physical true random number generator based on timing jitter.
3 *
4 * Copyright Stephan Mueller <[email protected]>, 2014 - 2021
5 *
6 * License
7 * =======
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, and the entire permission notice in its entirety,
14 * including the disclaimer of warranties.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The name of the author may not be used to endorse or promote
19 * products derived from this software without specific prior
20 * written permission.
21 *
22 * ALTERNATIVELY, this product may be distributed under the terms of
23 * the GNU General Public License, in which case the provisions of the GPL are
24 * required INSTEAD OF the above restrictions. (This clause is
25 * necessary due to a potential bad interaction between the GPL and
26 * the restrictions contained in a BSD-style copyright.)
27 *
28 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
29 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
31 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
32 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
39 * DAMAGE.
40 */
41
42 #ifndef _JITTERENTROPY_H
43 #define _JITTERENTROPY_H
44
45 /***************************************************************************
46 * Jitter RNG Configuration Section
47 *
48 * You may alter the following options
49 ***************************************************************************/
50
51 /*
52 * Enable timer-less timer support
53 *
54 * In case the hardware is identified to not provide a high-resolution time
55 * stamp, this option enables a built-in high-resolution time stamp mechanism.
56 *
57 * The timer-less noise source is based on threads. This noise source requires
58 * the linking with the POSIX threads library. I.e. the executing environment
59 * must offer POSIX threads. If this option is disabled, no linking
60 * with the POSIX threads library is needed.
61 */
62 #undef JENT_CONF_ENABLE_INTERNAL_TIMER
63
64 /*
65 * Disable the loop shuffle operation
66 *
67 * The shuffle operation enlarges the timing of the conditioning function
68 * by a variable length defined by the LSB of a time stamp. Some mathematicians
69 * are concerned that this pseudo-random selection of the loop iteration count
70 * may create some form of dependency between the different loop counts
71 * and the associated time duration of the conditioning function. It
72 * also complicates entropy assessment because it effectively combines a bunch
73 * of shifted/scaled copies the same distribution and masks failures from the
74 * health testing.
75 *
76 * By enabling this flag, the loop shuffle operation is disabled and
77 * the entropy collection operates in a way that honor the concerns.
78 *
79 * By enabling this flag, the time of collecting entropy may be enlarged.
80 */
81 #define JENT_CONF_DISABLE_LOOP_SHUFFLE
82
83 /*
84 * Shall the LAG predictor health test be enabled?
85 */
86 #define JENT_HEALTH_LAG_PREDICTOR
87
88 /*
89 * Shall the jent_memaccess use a (statistically) random selection for the
90 * memory to update?
91 */
92 #define JENT_RANDOM_MEMACCESS
93
94 /***************************************************************************
95 * Jitter RNG State Definition Section
96 ***************************************************************************/
97
98 #include "jitterentropy-base-user.h"
99
100 #define SHA3_256_SIZE_DIGEST_BITS 256
101 #define SHA3_256_SIZE_DIGEST (SHA3_256_SIZE_DIGEST_BITS >> 3)
102
103 /*
104 * The output 256 bits can receive more than 256 bits of min entropy,
105 * of course, but the 256-bit output of SHA3-256(M) can only asymptotically
106 * approach 256 bits of min entropy, not attain that bound. Random maps will
107 * tend to have output collisions, which reduces the creditable output entropy
108 * (that is what SP 800-90B Section 3.1.5.1.2 attempts to bound).
109 *
110 * The value "64" is justified in Appendix A.4 of the current 90C draft,
111 * and aligns with NIST's in "epsilon" definition in this document, which is
112 * that a string can be considered "full entropy" if you can bound the min
113 * entropy in each bit of output to at least 1-epsilon, where epsilon is
114 * required to be <= 2^(-32).
115 */
116 #define ENTROPY_SAFETY_FACTOR 64
117
118 /**
119 * Function pointer data structure to register an external thread handler
120 * used for the timer-less mode of the Jitter RNG.
121 *
122 * The external caller provides these function pointers to handle the
123 * management of the timer thread that is spawned by the Jitter RNG.
124 *
125 * @var jent_notime_init This function is intended to initialze the threading
126 * support. All data that is required by the threading code must be
127 * held in the data structure @param ctx. The Jitter RNG maintains the
128 * data structure and uses it for every invocation of the following calls.
129 *
130 * @var jent_notime_fini This function shall terminate the threading support.
131 * The function must dispose of all memory and resources used for the
132 * threading operation. It must also dispose of the @param ctx memory.
133 *
134 * @var jent_notime_start This function is called when the Jitter RNG wants
135 * to start a thread. Besides providing a pointer to the @param ctx
136 * allocated during initialization time, the Jitter RNG provides a
137 * pointer to the function the thread shall execute and the argument
138 * the function shall be invoked with. These two parameters have the
139 * same purpose as the trailing two parameters of pthread_create(3).
140 *
141 * @var jent_notime_stop This function is invoked by the Jitter RNG when the
142 * thread should be stopped. Note, the Jitter RNG intends to start/stop
143 * the thread frequently.
144 *
145 * An example implementation is found in the Jitter RNG itself with its
146 * default thread handler of jent_notime_thread_builtin.
147 *
148 * If the caller wants to register its own thread handler, it must be done
149 * with the API call jent_entropy_switch_notime_impl as the first
150 * call to interact with the Jitter RNG, even before jent_entropy_init.
151 * After jent_entropy_init is called, changing of the threading implementation
152 * is not allowed.
153 */
154 struct jent_notime_thread {
155 int (*jent_notime_init)(void **ctx);
156 void (*jent_notime_fini)(void *ctx);
157 int (*jent_notime_start)(void *ctx,
158 void *(*start_routine) (void *), void *arg);
159 void (*jent_notime_stop)(void *ctx);
160 };
161
162 /* The entropy pool */
163 struct rand_data
164 {
165 /* all data values that are vital to maintain the security
166 * of the RNG are marked as SENSITIVE. A user must not
167 * access that information while the RNG executes its loops to
168 * calculate the next random value. */
169 uint8_t data[SHA3_256_SIZE_DIGEST]; /* SENSITIVE Actual random number */
170 uint64_t prev_time; /* SENSITIVE Previous time stamp */
171 #define DATA_SIZE_BITS (SHA3_256_SIZE_DIGEST_BITS)
172
173 #ifndef JENT_HEALTH_LAG_PREDICTOR
174 uint64_t last_delta; /* SENSITIVE stuck test */
175 uint64_t last_delta2; /* SENSITIVE stuck test */
176 #endif /* JENT_HEALTH_LAG_PREDICTOR */
177
178 unsigned int flags; /* Flags used to initialize */
179 unsigned int osr; /* Oversampling rate */
180
181 #ifdef JENT_RANDOM_MEMACCESS
182 /* The step size should be larger than the cacheline size. */
183 # ifndef JENT_MEMORY_BITS
184 # define JENT_MEMORY_BITS 17
185 # endif
186 # ifndef JENT_MEMORY_SIZE
187 # define JENT_MEMORY_SIZE (UINT32_C(1)<<JENT_MEMORY_BITS)
188 # endif
189 #else /* JENT_RANDOM_MEMACCESS */
190 # ifndef JENT_MEMORY_BLOCKS
191 # define JENT_MEMORY_BLOCKS 512
192 # endif
193 # ifndef JENT_MEMORY_BLOCKSIZE
194 # define JENT_MEMORY_BLOCKSIZE 128
195 # endif
196 # ifndef JENT_MEMORY_SIZE
197 # define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE)
198 # endif
199 #endif /* JENT_RANDOM_MEMACCESS */
200
201 #define JENT_MEMORY_ACCESSLOOPS 128
202 unsigned char *mem; /* Memory access location with size of
203 * JENT_MEMORY_SIZE or memsize */
204 #ifdef JENT_RANDOM_MEMACCESS
205 uint32_t memmask; /* Memory mask (size of memory - 1) */
206 #else
207 unsigned int memlocation; /* Pointer to byte in *mem */
208 unsigned int memblocks; /* Number of memory blocks in *mem */
209 unsigned int memblocksize; /* Size of one memory block in bytes */
210 #endif
211 unsigned int memaccessloops; /* Number of memory accesses per random
212 * bit generation */
213
214 /* Repetition Count Test */
215 int rct_count; /* Number of stuck values */
216
217 /* Adaptive Proportion Test for a significance level of 2^-30 */
218 unsigned int apt_cutoff; /* Calculated using a corrected version
219 * of the SP800-90B sec 4.4.2 formula */
220 #define JENT_APT_WINDOW_SIZE 512 /* Data window size */
221 unsigned int apt_observations; /* Number of collected observations in
222 * current window. */
223 unsigned int apt_count; /* The number of times the reference
224 * symbol been encountered in the
225 * window. */
226 uint64_t apt_base; /* APT base reference */
227 unsigned int health_failure; /* Permanent health failure */
228
229 unsigned int apt_base_set:1; /* APT base reference set? */
230 unsigned int fips_enabled:1;
231 unsigned int enable_notime:1; /* Use internal high-res timer */
232 unsigned int max_mem_set:1; /* Maximum memory configured by user */
233
234 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
235 volatile uint8_t notime_interrupt; /* indicator to interrupt ctr */
236 volatile uint64_t notime_timer; /* high-res timer mock-up */
237 uint64_t notime_prev_timer; /* previous timer value */
238 void *notime_thread_ctx; /* register thread data */
239 #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
240
241 uint64_t jent_common_timer_gcd; /* Common divisor for all time deltas */
242
243 #ifdef JENT_HEALTH_LAG_PREDICTOR
244 /* Lag predictor test to look for re-occurring patterns. */
245
246 /* The lag global cutoff selected based on the selection of osr. */
247 unsigned int lag_global_cutoff;
248
249 /* The lag local cutoff selected based on the selection of osr. */
250 unsigned int lag_local_cutoff;
251
252 /*
253 * The number of times the lag predictor was correct. Compared to the
254 * global cutoff.
255 */
256 unsigned int lag_prediction_success_count;
257
258 /*
259 * The size of the current run of successes. Compared to the local
260 * cutoff.
261 */
262 unsigned int lag_prediction_success_run;
263
264 /*
265 * The total number of collected observations since the health test was
266 * last reset.
267 */
268 unsigned int lag_best_predictor;
269
270 /*
271 * The total number of collected observations since the health test was
272 * last reset.
273 */
274 unsigned int lag_observations;
275
276 /*
277 * This is the size of the window used by the predictor. The predictor
278 * is reset between windows.
279 */
280 #define JENT_LAG_WINDOW_SIZE (1U<<17)
281
282 /*
283 * The amount of history to base predictions on. This must be a power
284 * of 2. Must be 4 or greater.
285 */
286 #define JENT_LAG_HISTORY_SIZE 8
287 #define JENT_LAG_MASK (JENT_LAG_HISTORY_SIZE - 1)
288
289 /* The delta history for the lag predictor. */
290 uint64_t lag_delta_history[JENT_LAG_HISTORY_SIZE];
291
292 /* The scoreboard that tracks how successful each predictor lag is. */
293 unsigned int lag_scoreboard[JENT_LAG_HISTORY_SIZE];
294 #endif /* JENT_HEALTH_LAG_PREDICTOR */
295 };
296
297 /* Flags that can be used to initialize the RNG */
298 #define JENT_DISABLE_STIR (1<<0) /* UNUSED */
299 #define JENT_DISABLE_UNBIAS (1<<1) /* UNUSED */
300 #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more
301 entropy, saves MEMORY_SIZE RAM for
302 entropy collector */
303 #define JENT_FORCE_INTERNAL_TIMER (1<<3) /* Force the use of the internal
304 timer */
305 #define JENT_DISABLE_INTERNAL_TIMER (1<<4) /* Disable the potential use of
306 the internal timer. */
307 #define JENT_FORCE_FIPS (1<<5) /* Force FIPS compliant mode
308 including full SP800-90B
309 compliance. */
310
311 /* Flags field limiting the amount of memory to be used for memory access */
312 #define JENT_FLAGS_TO_MEMSIZE_SHIFT 28
313 #define JENT_FLAGS_TO_MAX_MEMSIZE(val) (val >> JENT_FLAGS_TO_MEMSIZE_SHIFT)
314 #define JENT_MAX_MEMSIZE_TO_FLAGS(val) (val << JENT_FLAGS_TO_MEMSIZE_SHIFT)
315 #define JENT_MAX_MEMSIZE_32kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 1))
316 #define JENT_MAX_MEMSIZE_64kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 2))
317 #define JENT_MAX_MEMSIZE_128kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 3))
318 #define JENT_MAX_MEMSIZE_256kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 4))
319 #define JENT_MAX_MEMSIZE_512kB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 5))
320 #define JENT_MAX_MEMSIZE_1MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 6))
321 #define JENT_MAX_MEMSIZE_2MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 7))
322 #define JENT_MAX_MEMSIZE_4MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 8))
323 #define JENT_MAX_MEMSIZE_8MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C( 9))
324 #define JENT_MAX_MEMSIZE_16MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(10))
325 #define JENT_MAX_MEMSIZE_32MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(11))
326 #define JENT_MAX_MEMSIZE_64MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(12))
327 #define JENT_MAX_MEMSIZE_128MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(13))
328 #define JENT_MAX_MEMSIZE_256MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(14))
329 #define JENT_MAX_MEMSIZE_512MB JENT_MAX_MEMSIZE_TO_FLAGS(UINT32_C(15))
330 #define JENT_MAX_MEMSIZE_MAX JENT_MAX_MEMSIZE_512MB
331 #define JENT_MAX_MEMSIZE_MASK JENT_MAX_MEMSIZE_MAX
332 /* We start at 32kB -> offset is log2(32768) */
333 #define JENT_MAX_MEMSIZE_OFFSET 14
334
335 #ifdef JENT_CONF_DISABLE_LOOP_SHUFFLE
336 # define JENT_MIN_OSR 3
337 #else
338 # define JENT_MIN_OSR 1
339 #endif
340
341 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
342
343 /* -- BEGIN Main interface functions -- */
344
345 #ifndef JENT_STUCK_INIT_THRES
346 /*
347 * Per default, not more than 90% of all measurements during initialization
348 * are allowed to be stuck.
349 *
350 * It is allowed to change this value as required for the intended environment.
351 */
352 #define JENT_STUCK_INIT_THRES(x) ((x*9) / 10)
353 #endif
354
355 #ifdef JENT_PRIVATE_COMPILE
356 # define JENT_PRIVATE_STATIC static
357 #else /* JENT_PRIVATE_COMPILE */
358 # define JENT_PRIVATE_STATIC __attribute__((visibility("default")))
359 #endif
360
361 /* Number of low bits of the time value that we want to consider */
362 /* get raw entropy */
363 JENT_PRIVATE_STATIC
364 ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len);
365 JENT_PRIVATE_STATIC
366 ssize_t jent_read_entropy_safe(struct rand_data **ec, char *data, size_t len);
367 /* initialize an instance of the entropy collector */
368 JENT_PRIVATE_STATIC
369 struct rand_data *jent_entropy_collector_alloc(unsigned int osr,
370 unsigned int flags);
371 /* clearing of entropy collector */
372 JENT_PRIVATE_STATIC
373 void jent_entropy_collector_free(struct rand_data *entropy_collector);
374
375 /* initialization of entropy collector */
376 JENT_PRIVATE_STATIC
377 int jent_entropy_init(void);
378 JENT_PRIVATE_STATIC
379 int jent_entropy_init_ex(unsigned int osr, unsigned int flags);
380
381 /* return version number of core library */
382 JENT_PRIVATE_STATIC
383 unsigned int jent_version(void);
384
385 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
386 /* Set a different thread handling logic for the notimer support */
387 JENT_PRIVATE_STATIC
388 int jent_entropy_switch_notime_impl(struct jent_notime_thread *new_thread);
389 #endif
390
391 /* -- END of Main interface functions -- */
392
393 /* -- BEGIN timer-less threading support functions to prevent code dupes -- */
394
395 struct jent_notime_ctx {
396 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
397 pthread_attr_t notime_pthread_attr; /* pthreads library */
398 pthread_t notime_thread_id; /* pthreads thread ID */
399 #endif
400 };
401
402 #ifdef JENT_CONF_ENABLE_INTERNAL_TIMER
403
404 JENT_PRIVATE_STATIC
405 int jent_notime_init(void **ctx);
406
407 JENT_PRIVATE_STATIC
408 void jent_notime_fini(void *ctx);
409
410 #else
411
412 static inline int jent_notime_init(void **ctx) { (void)ctx; return 0; }
413 static inline void jent_notime_fini(void *ctx) { (void)ctx; }
414
415 #endif /* JENT_CONF_ENABLE_INTERNAL_TIMER */
416
417 /* -- END timer-less threading support functions to prevent code dupes -- */
418
419 /* -- BEGIN error codes for init function -- */
420 #define ENOTIME 1 /* Timer service not available */
421 #define ECOARSETIME 2 /* Timer too coarse for RNG */
422 #define ENOMONOTONIC 3 /* Timer is not monotonic increasing */
423 #define EMINVARIATION 4 /* Timer variations too small for RNG */
424 #define EVARVAR 5 /* Timer does not produce variations of variations
425 (2nd derivation of time is zero) */
426 #define EMINVARVAR 6 /* Timer variations of variations is too small */
427 #define EPROGERR 7 /* Programming error */
428 #define ESTUCK 8 /* Too many stuck results during init. */
429 #define EHEALTH 9 /* Health test failed during initialization */
430 #define ERCT 10 /* RCT failed during initialization */
431 #define EHASH 11 /* Hash self test failed */
432 #define EMEM 12 /* Can't allocate memory for initialization */
433 #define EGCD 13 /* GCD self-test failed */
434 /* -- END error codes for init function -- */
435
436 /* -- BEGIN error masks for health tests -- */
437 #define JENT_RCT_FAILURE 1 /* Failure in RCT health test. */
438 #define JENT_APT_FAILURE 2 /* Failure in APT health test. */
439 #define JENT_LAG_FAILURE 4 /* Failure in Lag predictor health test. */
440 /* -- END error masks for health tests -- */
441
442 /* -- BEGIN statistical test functions only complied with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -- */
443
444 #ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT
445 JENT_PRIVATE_STATIC
446 uint64_t jent_lfsr_var_stat(struct rand_data *ec, unsigned int min);
447 #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */
448
449 /* -- END of statistical test function -- */
450
451 #endif /* _JITTERENTROPY_H */