1 /*-
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
7 * All rights reserved.
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, 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.
18 *
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.
29 *
30 */
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/ck.h>
35 #include <sys/conf.h>
36 #include <sys/epoch.h>
37 #include <sys/eventhandler.h>
38 #include <sys/hash.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/linker.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/module.h>
45 #include <sys/mutex.h>
46 #include <sys/random.h>
47 #include <sys/sbuf.h>
48 #include <sys/sysctl.h>
49 #include <sys/unistd.h>
50
51 #include <machine/atomic.h>
52 #include <machine/cpu.h>
53
54 #include <crypto/rijndael/rijndael-api-fst.h>
55 #include <crypto/sha2/sha256.h>
56
57 #include <dev/random/fortuna.h>
58 #include <dev/random/hash.h>
59 #include <dev/random/randomdev.h>
60 #include <dev/random/random_harvestq.h>
61
62 #if defined(RANDOM_ENABLE_ETHER)
63 #define _RANDOM_HARVEST_ETHER_OFF 0
64 #else
65 #define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER)
66 #endif
67 #if defined(RANDOM_ENABLE_UMA)
68 #define _RANDOM_HARVEST_UMA_OFF 0
69 #else
70 #define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA)
71 #endif
72
73 /*
74 * Note that random_sources_feed() will also use this to try and split up
75 * entropy into a subset of pools per iteration with the goal of feeding
76 * HARVESTSIZE into every pool at least once per second.
77 */
78 #define RANDOM_KTHREAD_HZ 10
79
80 static void random_kthread(void);
81 static void random_sources_feed(void);
82
83 /*
84 * Random must initialize much earlier than epoch, but we can initialize the
85 * epoch code before SMP starts. Prior to SMP, we can safely bypass
86 * concurrency primitives.
87 */
88 static __read_mostly bool epoch_inited;
89 static __read_mostly epoch_t rs_epoch;
90
91 /*
92 * How many events to queue up. We create this many items in
93 * an 'empty' queue, then transfer them to the 'harvest' queue with
94 * supplied junk. When used, they are transferred back to the
95 * 'empty' queue.
96 */
97 #define RANDOM_RING_MAX 1024
98 #define RANDOM_ACCUM_MAX 8
99
100 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */
101 volatile int random_kthread_control;
102
103
104 /* Allow the sysadmin to select the broad category of
105 * entropy types to harvest.
106 */
107 __read_frequently u_int hc_source_mask;
108
109 struct random_sources {
110 CK_LIST_ENTRY(random_sources) rrs_entries;
111 struct random_source *rrs_source;
112 };
113
114 static CK_LIST_HEAD(sources_head, random_sources) source_list =
115 CK_LIST_HEAD_INITIALIZER(source_list);
116
117 SYSCTL_NODE(_kern_random, OID_AUTO, harvest, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
118 "Entropy Device Parameters");
119
120 /*
121 * Put all the harvest queue context stuff in one place.
122 * this make is a bit easier to lock and protect.
123 */
124 static struct harvest_context {
125 /* The harvest mutex protects all of harvest_context and
126 * the related data.
127 */
128 struct mtx hc_mtx;
129 /* Round-robin destination cache. */
130 u_int hc_destination[ENTROPYSOURCE];
131 /* The context of the kernel thread processing harvested entropy */
132 struct proc *hc_kthread_proc;
133 /*
134 * A pair of buffers for queued events. New events are added to the
135 * active queue while the kthread processes the other one in parallel.
136 */
137 struct entropy_buffer {
138 struct harvest_event ring[RANDOM_RING_MAX];
139 u_int pos;
140 } hc_entropy_buf[2];
141 u_int hc_active_buf;
142 struct fast_entropy_accumulator {
143 volatile u_int pos;
144 uint32_t buf[RANDOM_ACCUM_MAX];
145 } hc_entropy_fast_accumulator;
146 } harvest_context;
147
148 #define RANDOM_HARVEST_INIT_LOCK() mtx_init(&harvest_context.hc_mtx, \
149 "entropy harvest mutex", NULL, MTX_SPIN)
150 #define RANDOM_HARVEST_LOCK() mtx_lock_spin(&harvest_context.hc_mtx)
151 #define RANDOM_HARVEST_UNLOCK() mtx_unlock_spin(&harvest_context.hc_mtx)
152
153 static struct kproc_desc random_proc_kp = {
154 "rand_harvestq",
155 random_kthread,
156 &harvest_context.hc_kthread_proc,
157 };
158
159 /* Pass the given event straight through to Fortuna/Whatever. */
160 static __inline void
random_harvestq_fast_process_event(struct harvest_event * event)161 random_harvestq_fast_process_event(struct harvest_event *event)
162 {
163 p_random_alg_context->ra_event_processor(event);
164 explicit_bzero(event, sizeof(*event));
165 }
166
167 static void
random_kthread(void)168 random_kthread(void)
169 {
170 struct harvest_context *hc;
171
172 hc = &harvest_context;
173 for (random_kthread_control = 1; random_kthread_control;) {
174 struct entropy_buffer *buf;
175 u_int entries;
176
177 /* Deal with queued events. */
178 RANDOM_HARVEST_LOCK();
179 buf = &hc->hc_entropy_buf[hc->hc_active_buf];
180 entries = buf->pos;
181 buf->pos = 0;
182 hc->hc_active_buf = (hc->hc_active_buf + 1) %
183 nitems(hc->hc_entropy_buf);
184 RANDOM_HARVEST_UNLOCK();
185 for (u_int i = 0; i < entries; i++)
186 random_harvestq_fast_process_event(&buf->ring[i]);
187
188 /* Poll sources of noise. */
189 random_sources_feed();
190
191 /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */
192 for (u_int i = 0; i < RANDOM_ACCUM_MAX; i++) {
193 if (hc->hc_entropy_fast_accumulator.buf[i]) {
194 random_harvest_direct(&hc->hc_entropy_fast_accumulator.buf[i],
195 sizeof(hc->hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA);
196 hc->hc_entropy_fast_accumulator.buf[i] = 0;
197 }
198 }
199 /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */
200 tsleep_sbt(&hc->hc_kthread_proc, 0, "-",
201 SBT_1S/RANDOM_KTHREAD_HZ, 0, C_PREL(1));
202 }
203 random_kthread_control = -1;
204 wakeup(&hc->hc_kthread_proc);
205 kproc_exit(0);
206 /* NOTREACHED */
207 }
208 SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start,
209 &random_proc_kp);
210 _Static_assert(SI_SUB_KICK_SCHEDULER > SI_SUB_RANDOM,
211 "random kthread starting before subsystem initialization");
212
213 static void
rs_epoch_init(void * dummy __unused)214 rs_epoch_init(void *dummy __unused)
215 {
216 rs_epoch = epoch_alloc("Random Sources", EPOCH_PREEMPT);
217 epoch_inited = true;
218 }
219 SYSINIT(rs_epoch_init, SI_SUB_EPOCH, SI_ORDER_ANY, rs_epoch_init, NULL);
220
221 /*
222 * Run through all fast sources reading entropy for the given
223 * number of rounds, which should be a multiple of the number
224 * of entropy accumulation pools in use; it is 32 for Fortuna.
225 */
226 static void
random_sources_feed(void)227 random_sources_feed(void)
228 {
229 uint32_t entropy[HARVESTSIZE];
230 struct epoch_tracker et;
231 struct random_sources *rrs;
232 u_int i, n, npools;
233 bool rse_warm;
234
235 rse_warm = epoch_inited;
236
237 /*
238 * Evenly-ish distribute pool population across the second based on how
239 * frequently random_kthread iterates.
240 *
241 * For Fortuna, the math currently works out as such:
242 *
243 * 64 bits * 4 pools = 256 bits per iteration
244 * 256 bits * 10 Hz = 2560 bits per second, 320 B/s
245 *
246 */
247 npools = howmany(p_random_alg_context->ra_poolcount, RANDOM_KTHREAD_HZ);
248
249 /*-
250 * If we're not seeded yet, attempt to perform a "full seed", filling
251 * all of the PRNG's pools with entropy; if there is enough entropy
252 * available from "fast" entropy sources this will allow us to finish
253 * seeding and unblock the boot process immediately rather than being
254 * stuck for a few seconds with random_kthread gradually collecting a
255 * small chunk of entropy every 1 / RANDOM_KTHREAD_HZ seconds.
256 *
257 * We collect RANDOM_FORTUNA_DEFPOOLSIZE bytes per pool, i.e. enough
258 * to fill Fortuna's pools in the default configuration. With another
259 * PRNG or smaller pools for Fortuna, we might collect more entropy
260 * than needed to fill the pools, but this is harmless; alternatively,
261 * a different PRNG, larger pools, or fast entropy sources which are
262 * not able to provide as much entropy as we request may result in the
263 * not being fully seeded (and thus remaining blocked) but in that
264 * case we will return here after 1 / RANDOM_KTHREAD_HZ seconds and
265 * try again for a large amount of entropy.
266 */
267 if (!p_random_alg_context->ra_seeded())
268 npools = howmany(p_random_alg_context->ra_poolcount *
269 RANDOM_FORTUNA_DEFPOOLSIZE, sizeof(entropy));
270
271 /*
272 * Step over all of live entropy sources, and feed their output
273 * to the system-wide RNG.
274 */
275 if (rse_warm)
276 epoch_enter_preempt(rs_epoch, &et);
277 CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
278 for (i = 0; i < npools; i++) {
279 n = rrs->rrs_source->rs_read(entropy, sizeof(entropy));
280 KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy)));
281 /*
282 * Sometimes the HW entropy source doesn't have anything
283 * ready for us. This isn't necessarily untrustworthy.
284 * We don't perform any other verification of an entropy
285 * source (i.e., length is allowed to be anywhere from 1
286 * to sizeof(entropy), quality is unchecked, etc), so
287 * don't balk verbosely at slow random sources either.
288 * There are reports that RDSEED on x86 metal falls
289 * behind the rate at which we query it, for example.
290 * But it's still a better entropy source than RDRAND.
291 */
292 if (n == 0)
293 continue;
294 random_harvest_direct(entropy, n, rrs->rrs_source->rs_source);
295 }
296 }
297 if (rse_warm)
298 epoch_exit_preempt(rs_epoch, &et);
299 explicit_bzero(entropy, sizeof(entropy));
300 }
301
302 static int
random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)303 random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS)
304 {
305 static const u_int user_immutable_mask =
306 (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) |
307 _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF;
308
309 int error;
310 u_int value, orig_value;
311
312 orig_value = value = hc_source_mask;
313 error = sysctl_handle_int(oidp, &value, 0, req);
314 if (error != 0 || req->newptr == NULL)
315 return (error);
316
317 if (flsl(value) > ENTROPYSOURCE)
318 return (EINVAL);
319
320 /*
321 * Disallow userspace modification of pure entropy sources.
322 */
323 hc_source_mask = (value & ~user_immutable_mask) |
324 (orig_value & user_immutable_mask);
325 return (0);
326 }
327 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask,
328 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, NULL, 0,
329 random_check_uint_harvestmask, "IU",
330 "Entropy harvesting mask");
331
332 static int
random_print_harvestmask(SYSCTL_HANDLER_ARGS)333 random_print_harvestmask(SYSCTL_HANDLER_ARGS)
334 {
335 struct sbuf sbuf;
336 int error, i;
337
338 error = sysctl_wire_old_buffer(req, 0);
339 if (error == 0) {
340 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
341 for (i = ENTROPYSOURCE - 1; i >= 0; i--)
342 sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0");
343 error = sbuf_finish(&sbuf);
344 sbuf_delete(&sbuf);
345 }
346 return (error);
347 }
348 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin,
349 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
350 random_print_harvestmask, "A",
351 "Entropy harvesting mask (printable)");
352
353 static const char *random_source_descr[ENTROPYSOURCE] = {
354 [RANDOM_CACHED] = "CACHED",
355 [RANDOM_ATTACH] = "ATTACH",
356 [RANDOM_KEYBOARD] = "KEYBOARD",
357 [RANDOM_MOUSE] = "MOUSE",
358 [RANDOM_NET_TUN] = "NET_TUN",
359 [RANDOM_NET_ETHER] = "NET_ETHER",
360 [RANDOM_NET_NG] = "NET_NG",
361 [RANDOM_INTERRUPT] = "INTERRUPT",
362 [RANDOM_SWI] = "SWI",
363 [RANDOM_FS_ATIME] = "FS_ATIME",
364 [RANDOM_UMA] = "UMA",
365 [RANDOM_CALLOUT] = "CALLOUT", /* ENVIRONMENTAL_END */
366 [RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */
367 [RANDOM_PURE_SAFE] = "PURE_SAFE",
368 [RANDOM_PURE_GLXSB] = "PURE_GLXSB",
369 [RANDOM_PURE_HIFN] = "PURE_HIFN",
370 [RANDOM_PURE_RDRAND] = "PURE_RDRAND",
371 [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH",
372 [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST",
373 [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO",
374 [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM",
375 [RANDOM_PURE_CCP] = "PURE_CCP",
376 [RANDOM_PURE_DARN] = "PURE_DARN",
377 [RANDOM_PURE_TPM] = "PURE_TPM",
378 [RANDOM_PURE_VMGENID] = "PURE_VMGENID",
379 [RANDOM_PURE_QUALCOMM] = "PURE_QUALCOMM",
380 [RANDOM_PURE_ARMV8] = "PURE_ARMV8",
381 [RANDOM_PURE_ARM_TRNG] = "PURE_ARM_TRNG",
382 /* "ENTROPYSOURCE" */
383 };
384
385 static int
random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)386 random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS)
387 {
388 struct sbuf sbuf;
389 int error, i;
390 bool first;
391
392 first = true;
393 error = sysctl_wire_old_buffer(req, 0);
394 if (error == 0) {
395 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
396 for (i = ENTROPYSOURCE - 1; i >= 0; i--) {
397 if (i >= RANDOM_PURE_START &&
398 (hc_source_mask & (1 << i)) == 0)
399 continue;
400 if (!first)
401 sbuf_cat(&sbuf, ",");
402 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : "");
403 sbuf_cat(&sbuf, random_source_descr[i]);
404 sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : "");
405 first = false;
406 }
407 error = sbuf_finish(&sbuf);
408 sbuf_delete(&sbuf);
409 }
410 return (error);
411 }
412 SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic,
413 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
414 random_print_harvestmask_symbolic, "A",
415 "Entropy harvesting mask (symbolic)");
416
417 static void
random_harvestq_init(void * unused __unused)418 random_harvestq_init(void *unused __unused)
419 {
420 static const u_int almost_everything_mask =
421 (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) &
422 ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF);
423
424 hc_source_mask = almost_everything_mask;
425 RANDOM_HARVEST_INIT_LOCK();
426 harvest_context.hc_active_buf = 0;
427 }
428 SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_init, NULL);
429
430 /*
431 * Subroutine to slice up a contiguous chunk of 'entropy' and feed it into the
432 * underlying algorithm. Returns number of bytes actually fed into underlying
433 * algorithm.
434 */
435 static size_t
random_early_prime(char * entropy,size_t len)436 random_early_prime(char *entropy, size_t len)
437 {
438 struct harvest_event event;
439 size_t i;
440
441 len = rounddown(len, sizeof(event.he_entropy));
442 if (len == 0)
443 return (0);
444
445 for (i = 0; i < len; i += sizeof(event.he_entropy)) {
446 event.he_somecounter = random_get_cyclecount();
447 event.he_size = sizeof(event.he_entropy);
448 event.he_source = RANDOM_CACHED;
449 event.he_destination =
450 harvest_context.hc_destination[RANDOM_CACHED]++;
451 memcpy(event.he_entropy, entropy + i, sizeof(event.he_entropy));
452 random_harvestq_fast_process_event(&event);
453 }
454 explicit_bzero(entropy, len);
455 return (len);
456 }
457
458 /*
459 * Subroutine to search for known loader-loaded files in memory and feed them
460 * into the underlying algorithm early in boot. Returns the number of bytes
461 * loaded (zero if none were loaded).
462 */
463 static size_t
random_prime_loader_file(const char * type)464 random_prime_loader_file(const char *type)
465 {
466 uint8_t *keyfile, *data;
467 size_t size;
468
469 keyfile = preload_search_by_type(type);
470 if (keyfile == NULL)
471 return (0);
472
473 data = preload_fetch_addr(keyfile);
474 size = preload_fetch_size(keyfile);
475 if (data == NULL)
476 return (0);
477
478 return (random_early_prime(data, size));
479 }
480
481 /*
482 * This is used to prime the RNG by grabbing any early random stuff
483 * known to the kernel, and inserting it directly into the hashing
484 * module, currently Fortuna.
485 */
486 static void
random_harvestq_prime(void * unused __unused)487 random_harvestq_prime(void *unused __unused)
488 {
489 size_t size;
490
491 /*
492 * Get entropy that may have been preloaded by loader(8)
493 * and use it to pre-charge the entropy harvest queue.
494 */
495 size = random_prime_loader_file(RANDOM_CACHED_BOOT_ENTROPY_MODULE);
496 if (bootverbose) {
497 if (size > 0)
498 printf("random: read %zu bytes from preloaded cache\n",
499 size);
500 else
501 printf("random: no preloaded entropy cache\n");
502 }
503 size = random_prime_loader_file(RANDOM_PLATFORM_BOOT_ENTROPY_MODULE);
504 if (bootverbose) {
505 if (size > 0)
506 printf("random: read %zu bytes from platform bootloader\n",
507 size);
508 else
509 printf("random: no platform bootloader entropy\n");
510 }
511 }
512 SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL);
513
514 static void
random_harvestq_deinit(void * unused __unused)515 random_harvestq_deinit(void *unused __unused)
516 {
517
518 /* Command the hash/reseed thread to end and wait for it to finish */
519 random_kthread_control = 0;
520 while (random_kthread_control >= 0)
521 tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5);
522 }
523 SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_deinit, NULL);
524
525 /*-
526 * Entropy harvesting queue routine.
527 *
528 * This is supposed to be fast; do not do anything slow in here!
529 * It is also illegal (and morally reprehensible) to insert any
530 * high-rate data here. "High-rate" is defined as a data source
531 * that is likely to fill up the buffer in much less than 100ms.
532 * This includes the "always-on" sources like the Intel "rdrand"
533 * or the VIA Nehamiah "xstore" sources.
534 */
535 /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle
536 * counters are built in, but on older hardware it will do a real time clock
537 * read which can be quite expensive.
538 */
539 void
random_harvest_queue_(const void * entropy,u_int size,enum random_entropy_source origin)540 random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin)
541 {
542 struct harvest_context *hc;
543 struct entropy_buffer *buf;
544 struct harvest_event *event;
545
546 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE,
547 ("%s: origin %d invalid", __func__, origin));
548
549 hc = &harvest_context;
550 RANDOM_HARVEST_LOCK();
551 buf = &hc->hc_entropy_buf[hc->hc_active_buf];
552 if (buf->pos < RANDOM_RING_MAX) {
553 event = &buf->ring[buf->pos++];
554 event->he_somecounter = random_get_cyclecount();
555 event->he_source = origin;
556 event->he_destination = hc->hc_destination[origin]++;
557 if (size <= sizeof(event->he_entropy)) {
558 event->he_size = size;
559 memcpy(event->he_entropy, entropy, size);
560 } else {
561 /* Big event, so squash it */
562 event->he_size = sizeof(event->he_entropy[0]);
563 event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event);
564 }
565 }
566 RANDOM_HARVEST_UNLOCK();
567 }
568
569 /*-
570 * Entropy harvesting fast routine.
571 *
572 * This is supposed to be very fast; do not do anything slow in here!
573 * This is the right place for high-rate harvested data.
574 */
575 void
random_harvest_fast_(const void * entropy,u_int size)576 random_harvest_fast_(const void *entropy, u_int size)
577 {
578 u_int pos;
579
580 pos = harvest_context.hc_entropy_fast_accumulator.pos;
581 harvest_context.hc_entropy_fast_accumulator.buf[pos] ^=
582 jenkins_hash(entropy, size, random_get_cyclecount());
583 harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX;
584 }
585
586 /*-
587 * Entropy harvesting direct routine.
588 *
589 * This is not supposed to be fast, but will only be used during
590 * (e.g.) booting when initial entropy is being gathered.
591 */
592 void
random_harvest_direct_(const void * entropy,u_int size,enum random_entropy_source origin)593 random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin)
594 {
595 struct harvest_event event;
596
597 KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin));
598 size = MIN(size, sizeof(event.he_entropy));
599 event.he_somecounter = random_get_cyclecount();
600 event.he_size = size;
601 event.he_source = origin;
602 event.he_destination = harvest_context.hc_destination[origin]++;
603 memcpy(event.he_entropy, entropy, size);
604 random_harvestq_fast_process_event(&event);
605 }
606
607 void
random_harvest_register_source(enum random_entropy_source source)608 random_harvest_register_source(enum random_entropy_source source)
609 {
610
611 hc_source_mask |= (1 << source);
612 }
613
614 void
random_harvest_deregister_source(enum random_entropy_source source)615 random_harvest_deregister_source(enum random_entropy_source source)
616 {
617
618 hc_source_mask &= ~(1 << source);
619 }
620
621 void
random_source_register(struct random_source * rsource)622 random_source_register(struct random_source *rsource)
623 {
624 struct random_sources *rrs;
625
626 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
627
628 rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK);
629 rrs->rrs_source = rsource;
630
631 random_harvest_register_source(rsource->rs_source);
632
633 printf("random: registering fast source %s\n", rsource->rs_ident);
634
635 RANDOM_HARVEST_LOCK();
636 CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries);
637 RANDOM_HARVEST_UNLOCK();
638 }
639
640 void
random_source_deregister(struct random_source * rsource)641 random_source_deregister(struct random_source *rsource)
642 {
643 struct random_sources *rrs = NULL;
644
645 KASSERT(rsource != NULL, ("invalid input to %s", __func__));
646
647 random_harvest_deregister_source(rsource->rs_source);
648
649 RANDOM_HARVEST_LOCK();
650 CK_LIST_FOREACH(rrs, &source_list, rrs_entries)
651 if (rrs->rrs_source == rsource) {
652 CK_LIST_REMOVE(rrs, rrs_entries);
653 break;
654 }
655 RANDOM_HARVEST_UNLOCK();
656
657 if (rrs != NULL && epoch_inited)
658 epoch_wait_preempt(rs_epoch);
659 free(rrs, M_ENTROPY);
660 }
661
662 static int
random_source_handler(SYSCTL_HANDLER_ARGS)663 random_source_handler(SYSCTL_HANDLER_ARGS)
664 {
665 struct epoch_tracker et;
666 struct random_sources *rrs;
667 struct sbuf sbuf;
668 int error, count;
669
670 error = sysctl_wire_old_buffer(req, 0);
671 if (error != 0)
672 return (error);
673
674 sbuf_new_for_sysctl(&sbuf, NULL, 64, req);
675 count = 0;
676 epoch_enter_preempt(rs_epoch, &et);
677 CK_LIST_FOREACH(rrs, &source_list, rrs_entries) {
678 sbuf_cat(&sbuf, (count++ ? ",'" : "'"));
679 sbuf_cat(&sbuf, rrs->rrs_source->rs_ident);
680 sbuf_cat(&sbuf, "'");
681 }
682 epoch_exit_preempt(rs_epoch, &et);
683 error = sbuf_finish(&sbuf);
684 sbuf_delete(&sbuf);
685 return (error);
686 }
687 SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
688 NULL, 0, random_source_handler, "A",
689 "List of active fast entropy sources.");
690
691 MODULE_VERSION(random_harvestq, 1);
692