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>
39 #include <sys/epoch.h>
40 #include <sys/eventhandler.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/linker.h>
46 #include <sys/malloc.h>
47 #include <sys/module.h>
48 #include <sys/mutex.h>
49 #include <sys/random.h>
51 #include <sys/sysctl.h>
52 #include <sys/unistd.h>
54 #include <machine/atomic.h>
55 #include <machine/cpu.h>
57 #include <crypto/rijndael/rijndael-api-fst.h>
58 #include <crypto/sha2/sha256.h>
60 #include <dev/random/hash.h>
61 #include <dev/random/randomdev.h>
62 #include <dev/random/random_harvestq.h>
64 #if defined(RANDOM_ENABLE_ETHER)
65 #define _RANDOM_HARVEST_ETHER_OFF 0
67 #define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER)
69 #if defined(RANDOM_ENABLE_UMA)
70 #define _RANDOM_HARVEST_UMA_OFF 0
72 #define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA)
75 static void random_kthread(void);
76 static void random_sources_feed(void);
78 static u_int read_rate;
81 * Random must initialize much earlier than epoch, but we can initialize the
82 * epoch code before SMP starts. Prior to SMP, we can safely bypass
83 * concurrency primitives.
85 static __read_mostly bool epoch_inited;
86 static __read_mostly epoch_t rs_epoch;
89 * How many events to queue up. We create this many items in
90 * an 'empty' queue, then transfer them to the 'harvest' queue with
91 * supplied junk. When used, they are transferred back to the
94 #define RANDOM_RING_MAX 1024
95 #define RANDOM_ACCUM_MAX 8
97 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
98 volatile int random_kthread_control;
101 /* Allow the sysadmin to select the broad category of
102 * entropy types to harvest.
104 __read_frequently u_int hc_source_mask;
106 struct random_sources {
107 CK_LIST_ENTRY(random_sources) rrs_entries;
108 struct random_source *rrs_source;
111 static CK_LIST_HEAD(sources_head, random_sources) source_list =
112 CK_LIST_HEAD_INITIALIZER(source_list);
114 SYSCTL_NODE(_kern_random, OID_AUTO, harvest, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
115 "Entropy Device Parameters");
118 * Put all the harvest queue context stuff in one place.
119 * this make is a bit easier to lock and protect.
121 static struct harvest_context {
122 /* The harvest mutex protects all of harvest_context and
126 /* Round-robin destination cache. */
127 u_int hc_destination[ENTROPYSOURCE];
128 /* The context of the kernel thread processing harvested entropy */
129 struct proc *hc_kthread_proc;
131 * Lockless ring buffer holding entropy events
132 * If ring.in == ring.out,
133 * the buffer is empty.
134 * If ring.in != ring.out,
135 * the buffer contains harvested entropy.
136 * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX),
137 * the buffer is full.
139 * NOTE: ring.in points to the last added element,
140 * and ring.out points to the last consumed element.
142 * The ring.in variable needs locking as there are multiple
143 * sources to the ring. Only the sources may change ring.in,
144 * but the consumer may examine it.
146 * The ring.out variable does not need locking as there is
147 * only one consumer. Only the consumer may change ring.out,
148 * but the sources may examine it.
150 struct entropy_ring {
151 struct harvest_event ring[RANDOM_RING_MAX];
155 struct fast_entropy_accumulator {
157 uint32_t buf[RANDOM_ACCUM_MAX];
158 } hc_entropy_fast_accumulator;
161 static struct kproc_desc random_proc_kp = {
164 &harvest_context.hc_kthread_proc,
167 /* Pass the given event straight through to Fortuna/Whatever. */
169 random_harvestq_fast_process_event(struct harvest_event *event)
171 p_random_alg_context->ra_event_processor(event);
172 explicit_bzero(event, sizeof(*event));
178 u_int maxloop, ring_out, i;
181 * Locking is not needed as this is the only place we modify ring.out, and
182 * we only examine ring.in without changing it. Both of these are volatile,
183 * and this is a unique thread.
185 for (random_kthread_control = 1; random_kthread_control;) {
186 /* Deal with events, if any. Restrict the number we do in one go. */
187 maxloop = RANDOM_RING_MAX;
188 while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) {
189 ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX;
190 random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out);
191 harvest_context.hc_entropy_ring.out = ring_out;
195 random_sources_feed();
196 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
197 for (i = 0; i < RANDOM_ACCUM_MAX; i++) {
198 if (harvest_context.hc_entropy_fast_accumulator.buf[i]) {
199 random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA);
200 harvest_context.hc_entropy_fast_accumulator.buf[i] = 0;
203 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
204 tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1));
206 random_kthread_control = -1;
207 wakeup(&harvest_context.hc_kthread_proc);
211 /* This happens well after SI_SUB_RANDOM */
212 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
216 rs_epoch_init(void *dummy __unused)
218 rs_epoch = epoch_alloc("Random Sources", EPOCH_PREEMPT);
221 SYSINIT(rs_epoch_init, SI_SUB_EPOCH, SI_ORDER_ANY, rs_epoch_init, NULL);
224 * Run through all fast sources reading entropy for the given
225 * number of rounds, which should be a multiple of the number
226 * of entropy accumulation pools in use; it is 32 for Fortuna.
229 random_sources_feed(void)
231 uint32_t entropy[HARVESTSIZE];
232 struct epoch_tracker et;
233 struct random_sources *rrs;
234 u_int i, n, local_read_rate;
237 rse_warm = epoch_inited;
240 * Step over all of live entropy sources, and feed their output
241 * to the system-wide RNG.
243 local_read_rate = atomic_readandclear_32(&read_rate);
244 /* Perform at least one read per round */
245 local_read_rate = MAX(local_read_rate, 1);
246 /* But not exceeding RANDOM_KEYSIZE_WORDS */
247 local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS);
249 epoch_enter_preempt(rs_epoch, &et);
250 CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
251 for (i = 0; i < p_random_alg_context->ra_poolcount*local_read_rate; i++) {
252 n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
253 KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
255 * Sometimes the HW entropy source doesn't have anything
256 * ready for us. This isn't necessarily untrustworthy.
257 * We don't perform any other verification of an entropy
258 * source (i.e., length is allowed to be anywhere from 1
259 * to sizeof(entropy), quality is unchecked, etc), so
260 * don't balk verbosely at slow random sources either.
261 * There are reports that RDSEED on x86 metal falls
262 * behind the rate at which we query it, for example.
263 * But it's still a better entropy source than RDRAND.
267 random_harvest_direct(entropy, n, rrs->rrs_source->rs_source);
271 epoch_exit_preempt(rs_epoch, &et);
272 explicit_bzero(entropy, sizeof(entropy));
276 read_rate_increment(u_int chunk)
279 atomic_add_32(&read_rate, chunk);
284 random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)
286 static const u_int user_immutable_mask =
287 (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) |
288 _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF;
291 u_int value, orig_value;
293 orig_value = value = hc_source_mask;
294 error = sysctl_handle_int(oidp, &value, 0, req);
295 if (error != 0 || req->newptr == NULL)
298 if (flsl(value) > ENTROPYSOURCE)
302 * Disallow userspace modification of pure entropy sources.
304 hc_source_mask = (value & ~user_immutable_mask) |
305 (orig_value & user_immutable_mask);
308 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask,
309 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
310 random_check_uint_harvestmask, "IU",
311 "Entropy harvesting mask");
315 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
320 error = sysctl_wire_old_buffer(req, 0);
322 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
323 for (i = ENTROPYSOURCE - 1; i >= 0; i--)
324 sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0");
325 error = sbuf_finish(&sbuf);
330 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin,
331 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
332 random_print_harvestmask, "A",
333 "Entropy harvesting mask (printable)");
335 static const char *random_source_descr[ENTROPYSOURCE] = {
336 [RANDOM_CACHED] = "CACHED",
337 [RANDOM_ATTACH] = "ATTACH",
338 [RANDOM_KEYBOARD] = "KEYBOARD",
339 [RANDOM_MOUSE] = "MOUSE",
340 [RANDOM_NET_TUN] = "NET_TUN",
341 [RANDOM_NET_ETHER] = "NET_ETHER",
342 [RANDOM_NET_NG] = "NET_NG",
343 [RANDOM_INTERRUPT] = "INTERRUPT",
344 [RANDOM_SWI] = "SWI",
345 [RANDOM_FS_ATIME] = "FS_ATIME",
346 [RANDOM_UMA] = "UMA", /* ENVIRONMENTAL_END */
347 [RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */
348 [RANDOM_PURE_SAFE] = "PURE_SAFE",
349 [RANDOM_PURE_GLXSB] = "PURE_GLXSB",
350 [RANDOM_PURE_UBSEC] = "PURE_UBSEC",
351 [RANDOM_PURE_HIFN] = "PURE_HIFN",
352 [RANDOM_PURE_RDRAND] = "PURE_RDRAND",
353 [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
354 [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
355 [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
356 [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
357 [RANDOM_PURE_CCP] = "PURE_CCP",
358 [RANDOM_PURE_DARN] = "PURE_DARN",
359 [RANDOM_PURE_TPM] = "PURE_TPM",
360 [RANDOM_PURE_VMGENID] = "VMGENID",
361 /* "ENTROPYSOURCE" */
366 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
373 error = sysctl_wire_old_buffer(req, 0);
375 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
376 for (i = ENTROPYSOURCE - 1; i >= 0; i--) {
377 if (i >= RANDOM_PURE_START &&
378 (hc_source_mask & (1 << i)) == 0)
381 sbuf_cat(&sbuf, ",");
382 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : "");
383 sbuf_cat(&sbuf, random_source_descr[i]);
384 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : "");
387 error = sbuf_finish(&sbuf);
392 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic,
393 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
394 random_print_harvestmask_symbolic, "A",
395 "Entropy harvesting mask (symbolic)");
399 random_harvestq_init(void *unused __unused)
401 static const u_int almost_everything_mask =
402 (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) &
403 ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF);
405 hc_source_mask = almost_everything_mask;
406 RANDOM_HARVEST_INIT_LOCK();
407 harvest_context.hc_entropy_ring.in = harvest_context.hc_entropy_ring.out = 0;
409 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_init, NULL);
412 * Subroutine to slice up a contiguous chunk of 'entropy' and feed it into the
413 * underlying algorithm. Returns number of bytes actually fed into underlying
417 random_early_prime(char *entropy, size_t len)
419 struct harvest_event event;
422 len = rounddown(len, sizeof(event.he_entropy));
426 for (i = 0; i < len; i += sizeof(event.he_entropy)) {
427 event.he_somecounter = (uint32_t)get_cyclecount();
428 event.he_size = sizeof(event.he_entropy);
429 event.he_source = RANDOM_CACHED;
430 event.he_destination =
431 harvest_context.hc_destination[RANDOM_CACHED]++;
432 memcpy(event.he_entropy, entropy + i, sizeof(event.he_entropy));
433 random_harvestq_fast_process_event(&event);
435 explicit_bzero(entropy, len);
440 * Subroutine to search for known loader-loaded files in memory and feed them
441 * into the underlying algorithm early in boot. Returns the number of bytes
442 * loaded (zero if none were loaded).
445 random_prime_loader_file(const char *type)
447 uint8_t *keyfile, *data;
450 keyfile = preload_search_by_type(type);
454 data = preload_fetch_addr(keyfile);
455 size = preload_fetch_size(keyfile);
459 return (random_early_prime(data, size));
463 * This is used to prime the RNG by grabbing any early random stuff
464 * known to the kernel, and inserting it directly into the hashing
465 * module, currently Fortuna.
469 random_harvestq_prime(void *unused __unused)
474 * Get entropy that may have been preloaded by loader(8)
475 * and use it to pre-charge the entropy harvest queue.
477 size = random_prime_loader_file(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
480 printf("random: read %zu bytes from preloaded cache\n",
483 printf("random: no preloaded entropy cache\n");
486 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL);
490 random_harvestq_deinit(void *unused __unused)
493 /* Command the hash/reseed thread to end and wait for it to finish */
494 random_kthread_control = 0;
495 while (random_kthread_control >= 0)
496 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
498 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_deinit, NULL);
501 * Entropy harvesting queue routine.
503 * This is supposed to be fast; do not do anything slow in here!
504 * It is also illegal (and morally reprehensible) to insert any
505 * high-rate data here. "High-rate" is defined as a data source
506 * that will usually cause lots of failures of the "Lockless read"
507 * check a few lines below. This includes the "always-on" sources
508 * like the Intel "rdrand" or the VIA Nehamiah "xstore" sources.
510 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
511 * counters are built in, but on older hardware it will do a real time clock
512 * read which can be quite expensive.
515 random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin)
517 struct harvest_event *event;
520 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
521 RANDOM_HARVEST_LOCK();
522 ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX;
523 if (ring_in != harvest_context.hc_entropy_ring.out) {
524 /* The ring is not full */
525 event = harvest_context.hc_entropy_ring.ring + ring_in;
526 event->he_somecounter = (uint32_t)get_cyclecount();
527 event->he_source = origin;
528 event->he_destination = harvest_context.hc_destination[origin]++;
529 if (size <= sizeof(event->he_entropy)) {
530 event->he_size = size;
531 memcpy(event->he_entropy, entropy, size);
534 /* Big event, so squash it */
535 event->he_size = sizeof(event->he_entropy[0]);
536 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
538 harvest_context.hc_entropy_ring.in = ring_in;
540 RANDOM_HARVEST_UNLOCK();
544 * Entropy harvesting fast routine.
546 * This is supposed to be very fast; do not do anything slow in here!
547 * This is the right place for high-rate harvested data.
550 random_harvest_fast_(const void *entropy, u_int size)
554 pos = harvest_context.hc_entropy_fast_accumulator.pos;
555 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, (uint32_t)get_cyclecount());
556 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
560 * Entropy harvesting direct routine.
562 * This is not supposed to be fast, but will only be used during
563 * (e.g.) booting when initial entropy is being gathered.
566 random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin)
568 struct harvest_event event;
570 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
571 size = MIN(size, sizeof(event.he_entropy));
572 event.he_somecounter = (uint32_t)get_cyclecount();
573 event.he_size = size;
574 event.he_source = origin;
575 event.he_destination = harvest_context.hc_destination[origin]++;
576 memcpy(event.he_entropy, entropy, size);
577 random_harvestq_fast_process_event(&event);
581 random_harvest_register_source(enum random_entropy_source source)
584 hc_source_mask |= (1 << source);
588 random_harvest_deregister_source(enum random_entropy_source source)
591 hc_source_mask &= ~(1 << source);
595 random_source_register(struct random_source *rsource)
597 struct random_sources *rrs;
599 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
601 rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
602 rrs->rrs_source = rsource;
604 random_harvest_register_source(rsource->rs_source);
606 printf("random: registering fast source %s\n", rsource->rs_ident);
608 RANDOM_HARVEST_LOCK();
609 CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
610 RANDOM_HARVEST_UNLOCK();
614 random_source_deregister(struct random_source *rsource)
616 struct random_sources *rrs = NULL;
618 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
620 random_harvest_deregister_source(rsource->rs_source);
622 RANDOM_HARVEST_LOCK();
623 CK_LIST_FOREACH(rrs, &source_list, rrs_entries)
624 if (rrs->rrs_source == rsource) {
625 CK_LIST_REMOVE(rrs, rrs_entries);
628 RANDOM_HARVEST_UNLOCK();
630 if (rrs != NULL && epoch_inited)
631 epoch_wait_preempt(rs_epoch);
632 free(rrs, M_ENTROPY);
636 random_source_handler(SYSCTL_HANDLER_ARGS)
638 struct epoch_tracker et;
639 struct random_sources *rrs;
643 error = sysctl_wire_old_buffer(req, 0);
647 sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
649 epoch_enter_preempt(rs_epoch, &et);
650 CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
651 sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
652 sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
653 sbuf_cat(&sbuf, "'");
655 epoch_exit_preempt(rs_epoch, &et);
656 error = sbuf_finish(&sbuf);
660 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
661 NULL, 0, random_source_handler, "A",
662 "List of active fast entropy sources.");
664 MODULE_VERSION(random_harvestq, 1);