2 * Copyright (c) 2017 Oliver Pinter
3 * Copyright (c) 2017 W. Dean Freeman
4 * Copyright (c) 2000-2015 Mark R V Murray
5 * Copyright (c) 2013 Arthur Mesh
6 * Copyright (c) 2004 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer
14 * in this position and unchanged.
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.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/systm.h>
38 #include <sys/eventhandler.h>
40 #include <sys/kernel.h>
41 #include <sys/kthread.h>
42 #include <sys/linker.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/mutex.h>
47 #include <sys/random.h>
49 #include <sys/sysctl.h>
50 #include <sys/unistd.h>
52 #if defined(RANDOM_LOADABLE)
57 #include <machine/atomic.h>
58 #include <machine/cpu.h>
60 #include <crypto/rijndael/rijndael-api-fst.h>
61 #include <crypto/sha2/sha256.h>
63 #include <dev/random/hash.h>
64 #include <dev/random/randomdev.h>
65 #include <dev/random/random_harvestq.h>
67 #if defined(RANDOM_ENABLE_ETHER)
68 #define _RANDOM_HARVEST_ETHER_OFF 0
70 #define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER)
72 #if defined(RANDOM_ENABLE_UMA)
73 #define _RANDOM_HARVEST_UMA_OFF 0
75 #define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA)
78 static void random_kthread(void);
79 static void random_sources_feed(void);
81 static u_int read_rate;
83 /* List for the dynamic sysctls */
84 static struct sysctl_ctx_list random_clist;
87 * How many events to queue up. We create this many items in
88 * an 'empty' queue, then transfer them to the 'harvest' queue with
89 * supplied junk. When used, they are transferred back to the
92 #define RANDOM_RING_MAX 1024
93 #define RANDOM_ACCUM_MAX 8
95 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
96 volatile int random_kthread_control;
99 /* Allow the sysadmin to select the broad category of
100 * entropy types to harvest.
102 __read_frequently u_int hc_source_mask;
105 * Put all the harvest queue context stuff in one place.
106 * this make is a bit easier to lock and protect.
108 static struct harvest_context {
109 /* The harvest mutex protects all of harvest_context and
113 /* Round-robin destination cache. */
114 u_int hc_destination[ENTROPYSOURCE];
115 /* The context of the kernel thread processing harvested entropy */
116 struct proc *hc_kthread_proc;
118 * Lockless ring buffer holding entropy events
119 * If ring.in == ring.out,
120 * the buffer is empty.
121 * If ring.in != ring.out,
122 * the buffer contains harvested entropy.
123 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX),
124 * the buffer is full.
126 * NOTE: ring.in points to the last added element,
127 * and ring.out points to the last consumed element.
129 * The ring.in variable needs locking as there are multiple
130 * sources to the ring. Only the sources may change ring.in,
131 * but the consumer may examine it.
133 * The ring.out variable does not need locking as there is
134 * only one consumer. Only the consumer may change ring.out,
135 * but the sources may examine it.
137 struct entropy_ring {
138 struct harvest_event ring[RANDOM_RING_MAX];
142 struct fast_entropy_accumulator {
144 uint32_t buf[RANDOM_ACCUM_MAX];
145 } hc_entropy_fast_accumulator;
148 static struct kproc_desc random_proc_kp = {
151 &harvest_context.hc_kthread_proc,
154 /* Pass the given event straight through to Fortuna/Whatever. */
156 random_harvestq_fast_process_event(struct harvest_event *event)
158 #if defined(RANDOM_LOADABLE)
159 RANDOM_CONFIG_S_LOCK();
160 if (p_random_alg_context)
162 p_random_alg_context->ra_event_processor(event);
163 #if defined(RANDOM_LOADABLE)
164 RANDOM_CONFIG_S_UNLOCK();
166 explicit_bzero(event, sizeof(*event));
172 u_int maxloop, ring_out, i;
175 * Locking is not needed as this is the only place we modify ring.out, and
176 * we only examine ring.in without changing it. Both of these are volatile,
177 * and this is a unique thread.
179 for (random_kthread_control = 1; random_kthread_control;) {
180 /* Deal with events, if any. Restrict the number we do in one go. */
181 maxloop = RANDOM_RING_MAX;
182 while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) {
183 ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX;
184 random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out);
185 harvest_context.hc_entropy_ring.out = ring_out;
189 random_sources_feed();
190 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
191 for (i = 0; i < RANDOM_ACCUM_MAX; i++) {
192 if (harvest_context.hc_entropy_fast_accumulator.buf[i]) {
193 random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA);
194 harvest_context.hc_entropy_fast_accumulator.buf[i] = 0;
197 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
198 tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1));
200 random_kthread_control = -1;
201 wakeup(&harvest_context.hc_kthread_proc);
205 /* This happens well after SI_SUB_RANDOM */
206 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
210 * Run through all fast sources reading entropy for the given
211 * number of rounds, which should be a multiple of the number
212 * of entropy accumulation pools in use; it is 32 for Fortuna.
215 random_sources_feed(void)
217 uint32_t entropy[HARVESTSIZE];
218 struct random_sources *rrs;
219 u_int i, n, local_read_rate;
222 * Step over all of live entropy sources, and feed their output
223 * to the system-wide RNG.
225 #if defined(RANDOM_LOADABLE)
226 RANDOM_CONFIG_S_LOCK();
227 if (p_random_alg_context) {
228 /* It's an indenting error. Yeah, Yeah. */
230 local_read_rate = atomic_readandclear_32(&read_rate);
231 /* Perform at least one read per round */
232 local_read_rate = MAX(local_read_rate, 1);
233 /* But not exceeding RANDOM_KEYSIZE_WORDS */
234 local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS);
235 LIST_FOREACH(rrs, &source_list, rrs_entries) {
236 for (i = 0; i < p_random_alg_context->ra_poolcount*local_read_rate; i++) {
237 n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
238 KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
240 * Sometimes the HW entropy source doesn't have anything
241 * ready for us. This isn't necessarily untrustworthy.
242 * We don't perform any other verification of an entropy
243 * source (i.e., length is allowed to be anywhere from 1
244 * to sizeof(entropy), quality is unchecked, etc), so
245 * don't balk verbosely at slow random sources either.
246 * There are reports that RDSEED on x86 metal falls
247 * behind the rate at which we query it, for example.
248 * But it's still a better entropy source than RDRAND.
252 random_harvest_direct(entropy, n, rrs->rrs_source->rs_source);
255 explicit_bzero(entropy, sizeof(entropy));
256 #if defined(RANDOM_LOADABLE)
258 RANDOM_CONFIG_S_UNLOCK();
263 read_rate_increment(u_int chunk)
266 atomic_add_32(&read_rate, chunk);
271 random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)
273 static const u_int user_immutable_mask =
274 (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) |
275 _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF;
278 u_int value, orig_value;
280 orig_value = value = hc_source_mask;
281 error = sysctl_handle_int(oidp, &value, 0, req);
282 if (error != 0 || req->newptr == NULL)
285 if (flsl(value) > ENTROPYSOURCE)
289 * Disallow userspace modification of pure entropy sources.
291 hc_source_mask = (value & ~user_immutable_mask) |
292 (orig_value & user_immutable_mask);
298 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
303 error = sysctl_wire_old_buffer(req, 0);
305 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
306 for (i = ENTROPYSOURCE - 1; i >= 0; i--)
307 sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0");
308 error = sbuf_finish(&sbuf);
314 static const char *random_source_descr[ENTROPYSOURCE] = {
315 [RANDOM_CACHED] = "CACHED",
316 [RANDOM_ATTACH] = "ATTACH",
317 [RANDOM_KEYBOARD] = "KEYBOARD",
318 [RANDOM_MOUSE] = "MOUSE",
319 [RANDOM_NET_TUN] = "NET_TUN",
320 [RANDOM_NET_ETHER] = "NET_ETHER",
321 [RANDOM_NET_NG] = "NET_NG",
322 [RANDOM_INTERRUPT] = "INTERRUPT",
323 [RANDOM_SWI] = "SWI",
324 [RANDOM_FS_ATIME] = "FS_ATIME",
325 [RANDOM_UMA] = "UMA", /* ENVIRONMENTAL_END */
326 [RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */
327 [RANDOM_PURE_SAFE] = "PURE_SAFE",
328 [RANDOM_PURE_GLXSB] = "PURE_GLXSB",
329 [RANDOM_PURE_UBSEC] = "PURE_UBSEC",
330 [RANDOM_PURE_HIFN] = "PURE_HIFN",
331 [RANDOM_PURE_RDRAND] = "PURE_RDRAND",
332 [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
333 [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
334 [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
335 [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
336 [RANDOM_PURE_CCP] = "PURE_CCP",
337 [RANDOM_PURE_DARN] = "PURE_DARN",
338 [RANDOM_PURE_TPM] = "PURE_TPM",
339 /* "ENTROPYSOURCE" */
344 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
351 error = sysctl_wire_old_buffer(req, 0);
353 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
354 for (i = ENTROPYSOURCE - 1; i >= 0; i--) {
355 if (i >= RANDOM_PURE_START &&
356 (hc_source_mask & (1 << i)) == 0)
359 sbuf_cat(&sbuf, ",");
360 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : "");
361 sbuf_cat(&sbuf, random_source_descr[i]);
362 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : "");
365 error = sbuf_finish(&sbuf);
373 random_harvestq_init(void *unused __unused)
375 static const u_int almost_everything_mask =
376 (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) &
377 ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF);
379 struct sysctl_oid *random_sys_o;
381 random_sys_o = SYSCTL_ADD_NODE(&random_clist,
382 SYSCTL_STATIC_CHILDREN(_kern_random),
383 OID_AUTO, "harvest", CTLFLAG_RW, 0,
384 "Entropy Device Parameters");
385 hc_source_mask = almost_everything_mask;
386 SYSCTL_ADD_PROC(&random_clist,
387 SYSCTL_CHILDREN(random_sys_o),
388 OID_AUTO, "mask", CTLTYPE_UINT | CTLFLAG_RW,
389 NULL, 0, random_check_uint_harvestmask, "IU",
390 "Entropy harvesting mask");
391 SYSCTL_ADD_PROC(&random_clist,
392 SYSCTL_CHILDREN(random_sys_o),
393 OID_AUTO, "mask_bin", CTLTYPE_STRING | CTLFLAG_RD,
394 NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)");
395 SYSCTL_ADD_PROC(&random_clist,
396 SYSCTL_CHILDREN(random_sys_o),
397 OID_AUTO, "mask_symbolic", CTLTYPE_STRING | CTLFLAG_RD,
398 NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)");
399 RANDOM_HARVEST_INIT_LOCK();
400 harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
402 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_init, NULL);
405 * This is used to prime the RNG by grabbing any early random stuff
406 * known to the kernel, and inserting it directly into the hashing
407 * module, currently Fortuna.
411 random_harvestq_prime(void *unused __unused)
413 struct harvest_event event;
414 size_t count, size, i;
415 uint8_t *keyfile, *data;
418 * Get entropy that may have been preloaded by loader(8)
419 * and use it to pre-charge the entropy harvest queue.
421 keyfile = preload_search_by_type(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
422 #ifndef NO_BACKWARD_COMPATIBILITY
424 keyfile = preload_search_by_type(RANDOM_LEGACY_BOOT_ENTROPY_MODULE);
426 if (keyfile != NULL) {
427 data = preload_fetch_addr(keyfile);
428 size = preload_fetch_size(keyfile);
429 /* Trim the size. If the admin has a file with a funny size, we lose some. Tough. */
430 size -= (size % sizeof(event.he_entropy));
431 if (data != NULL && size != 0) {
432 for (i = 0; i < size; i += sizeof(event.he_entropy)) {
433 count = sizeof(event.he_entropy);
434 event.he_somecounter = (uint32_t)get_cyclecount();
435 event.he_size = count;
436 event.he_source = RANDOM_CACHED;
437 event.he_destination =
438 harvest_context.hc_destination[RANDOM_CACHED]++;
439 memcpy(event.he_entropy, data + i, sizeof(event.he_entropy));
440 random_harvestq_fast_process_event(&event);
442 explicit_bzero(data, size);
444 printf("random: read %zu bytes from preloaded cache\n", size);
447 printf("random: no preloaded entropy cache\n");
450 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_FOURTH, random_harvestq_prime, NULL);
454 random_harvestq_deinit(void *unused __unused)
457 /* Command the hash/reseed thread to end and wait for it to finish */
458 random_kthread_control = 0;
459 while (random_kthread_control >= 0)
460 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
461 sysctl_ctx_free(&random_clist);
463 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_SECOND, random_harvestq_deinit, NULL);
466 * Entropy harvesting queue routine.
468 * This is supposed to be fast; do not do anything slow in here!
469 * It is also illegal (and morally reprehensible) to insert any
470 * high-rate data here. "High-rate" is defined as a data source
471 * that will usually cause lots of failures of the "Lockless read"
472 * check a few lines below. This includes the "always-on" sources
473 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
475 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
476 * counters are built in, but on older hardware it will do a real time clock
477 * read which can be quite expensive.
480 random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin)
482 struct harvest_event *event;
485 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
486 RANDOM_HARVEST_LOCK();
487 ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
488 if (ring_in != harvest_context.hc_entropy_ring.out) {
489 /* The ring is not full */
490 event = harvest_context.hc_entropy_ring.ring + ring_in;
491 event->he_somecounter = (uint32_t)get_cyclecount();
492 event->he_source = origin;
493 event->he_destination = harvest_context.hc_destination[origin]++;
494 if (size <= sizeof(event->he_entropy)) {
495 event->he_size = size;
496 memcpy(event->he_entropy, entropy, size);
499 /* Big event, so squash it */
500 event->he_size = sizeof(event->he_entropy[0]);
501 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
503 harvest_context.hc_entropy_ring.in = ring_in;
505 RANDOM_HARVEST_UNLOCK();
509 * Entropy harvesting fast routine.
511 * This is supposed to be very fast; do not do anything slow in here!
512 * This is the right place for high-rate harvested data.
515 random_harvest_fast_(const void *entropy, u_int size)
519 pos = harvest_context.hc_entropy_fast_accumulator.pos;
520 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
521 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
525 * Entropy harvesting direct routine.
527 * This is not supposed to be fast, but will only be used during
528 * (e.g.) booting when initial entropy is being gathered.
531 random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin)
533 struct harvest_event event;
535 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
536 size = MIN(size, sizeof(event.he_entropy));
537 event.he_somecounter = (uint32_t)get_cyclecount();
538 event.he_size = size;
539 event.he_source = origin;
540 event.he_destination = harvest_context.hc_destination[origin]++;
541 memcpy(event.he_entropy, entropy, size);
542 random_harvestq_fast_process_event(&event);
546 random_harvest_register_source(enum random_entropy_source source)
549 hc_source_mask |= (1 << source);
553 random_harvest_deregister_source(enum random_entropy_source source)
556 hc_source_mask &= ~(1 << source);
559 MODULE_VERSION(random_harvestq, 1);