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