kern_entropy.c revision 1.2 1 /* $NetBSD: kern_entropy.c,v 1.2 2020/04/30 03:42:23 riastradh Exp $ */
2
3 /*-
4 * Copyright (c) 2019 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Taylor R. Campbell.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Entropy subsystem
34 *
35 * * Each CPU maintains a per-CPU entropy pool so that gathering
36 * entropy requires no interprocessor synchronization, except
37 * early at boot when we may be scrambling to gather entropy as
38 * soon as possible.
39 *
40 * - entropy_enter gathers entropy and never drops it on the
41 * floor, at the cost of sometimes having to do cryptography.
42 *
43 * - entropy_enter_intr gathers entropy or drops it on the
44 * floor, with low latency. Work to stir the pool or kick the
45 * housekeeping thread is scheduled in soft interrupts.
46 *
47 * * entropy_enter immediately enters into the global pool if it
48 * can transition to full entropy in one swell foop. Otherwise,
49 * it defers to a housekeeping thread that consolidates entropy,
50 * but only when the CPUs collectively have full entropy, in
51 * order to mitigate iterative-guessing attacks.
52 *
53 * * The entropy housekeeping thread continues to consolidate
54 * entropy even after we think we have full entropy, in case we
55 * are wrong, but is limited to one discretionary consolidation
56 * per minute, and only when new entropy is actually coming in,
57 * to limit performance impact.
58 *
59 * * The entropy epoch is the number that changes when we
60 * transition from partial entropy to full entropy, so that
61 * users can easily determine when to reseed. This also
62 * facilitates an operator explicitly causing everything to
63 * reseed by sysctl -w kern.entropy.consolidate=1, e.g. if they
64 * just flipped a coin 256 times and wrote `echo tthhhhhthh... >
65 * /dev/random'.
66 *
67 * * No entropy estimation based on the sample values, which is a
68 * contradiction in terms and a potential source of side
69 * channels. It is the responsibility of the driver author to
70 * study how predictable the physical source of input can ever
71 * be, and to furnish a lower bound on the amount of entropy it
72 * has.
73 *
74 * * Entropy depletion is available for testing (or if you're into
75 * that sort of thing), with sysctl -w kern.entropy.depletion=1;
76 * the logic to support it is small, to minimize chance of bugs.
77 */
78
79 #include <sys/cdefs.h>
80 __KERNEL_RCSID(0, "$NetBSD: kern_entropy.c,v 1.2 2020/04/30 03:42:23 riastradh Exp $");
81
82 #include <sys/param.h>
83 #include <sys/types.h>
84 #include <sys/atomic.h>
85 #include <sys/compat_stub.h>
86 #include <sys/condvar.h>
87 #include <sys/cpu.h>
88 #include <sys/entropy.h>
89 #include <sys/errno.h>
90 #include <sys/evcnt.h>
91 #include <sys/event.h>
92 #include <sys/file.h>
93 #include <sys/intr.h>
94 #include <sys/kauth.h>
95 #include <sys/kernel.h>
96 #include <sys/kmem.h>
97 #include <sys/kthread.h>
98 #include <sys/module_hook.h>
99 #include <sys/mutex.h>
100 #include <sys/percpu.h>
101 #include <sys/poll.h>
102 #include <sys/queue.h>
103 #include <sys/rnd.h> /* legacy kernel API */
104 #include <sys/rndio.h> /* userland ioctl interface */
105 #include <sys/rndsource.h> /* kernel rndsource driver API */
106 #include <sys/select.h>
107 #include <sys/selinfo.h>
108 #include <sys/sha1.h> /* for boot seed checksum */
109 #include <sys/stdint.h>
110 #include <sys/sysctl.h>
111 #include <sys/systm.h>
112 #include <sys/time.h>
113 #include <sys/xcall.h>
114
115 #include <lib/libkern/entpool.h>
116
117 #include <machine/limits.h>
118
119 #ifdef __HAVE_CPU_COUNTER
120 #include <machine/cpu_counter.h>
121 #endif
122
123 /*
124 * struct entropy_cpu
125 *
126 * Per-CPU entropy state. The pool is allocated separately
127 * because percpu(9) sometimes moves per-CPU objects around
128 * without zeroing them, which would lead to unwanted copies of
129 * sensitive secrets. The evcnt is allocated separately becuase
130 * evcnt(9) assumes it stays put in memory.
131 */
132 struct entropy_cpu {
133 struct evcnt *ec_softint_evcnt;
134 struct entpool *ec_pool;
135 unsigned ec_pending;
136 bool ec_locked;
137 };
138
139 /*
140 * struct rndsource_cpu
141 *
142 * Per-CPU rndsource state.
143 */
144 struct rndsource_cpu {
145 unsigned rc_nbits; /* bits of entropy added */
146 };
147
148 /*
149 * entropy_global (a.k.a. E for short in this file)
150 *
151 * Global entropy state. Writes protected by the global lock.
152 * Some fields, marked (A), can be read outside the lock, and are
153 * maintained with atomic_load/store_relaxed.
154 */
155 struct {
156 kmutex_t lock; /* covers all global state */
157 struct entpool pool; /* global pool for extraction */
158 unsigned needed; /* (A) needed globally */
159 unsigned pending; /* (A) pending in per-CPU pools */
160 unsigned timestamp; /* (A) time of last consolidation */
161 unsigned epoch; /* (A) changes when needed -> 0 */
162 kcondvar_t cv; /* notifies state changes */
163 struct selinfo selq; /* notifies needed -> 0 */
164 LIST_HEAD(,krndsource) sources; /* list of entropy sources */
165 enum entropy_stage {
166 ENTROPY_COLD = 0, /* single-threaded */
167 ENTROPY_WARM, /* multi-threaded at boot before CPUs */
168 ENTROPY_HOT, /* multi-threaded multi-CPU */
169 } stage;
170 bool requesting; /* busy requesting from sources */
171 bool consolidate; /* kick thread to consolidate */
172 bool seed_rndsource; /* true if seed source is attached */
173 bool seeded; /* true if seed file already loaded */
174 } entropy_global __cacheline_aligned = {
175 /* Fields that must be initialized when the kernel is loaded. */
176 .needed = ENTROPY_CAPACITY*NBBY,
177 .epoch = (unsigned)-1, /* -1 means not yet full entropy */
178 .sources = LIST_HEAD_INITIALIZER(entropy_global.sources),
179 .stage = ENTROPY_COLD,
180 };
181
182 #define E (&entropy_global) /* declutter */
183
184 /* Read-mostly globals */
185 static struct percpu *entropy_percpu __read_mostly; /* struct entropy_cpu */
186 static void *entropy_sih __read_mostly; /* softint handler */
187 static struct lwp *entropy_lwp __read_mostly; /* housekeeping thread */
188
189 int rnd_initial_entropy __read_mostly; /* XXX legacy */
190
191 static struct krndsource seed_rndsource __read_mostly;
192
193 /*
194 * Event counters
195 *
196 * Must be careful with adding these because they can serve as
197 * side channels.
198 */
199 static struct evcnt entropy_discretionary_evcnt =
200 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "discretionary");
201 EVCNT_ATTACH_STATIC(entropy_discretionary_evcnt);
202 static struct evcnt entropy_immediate_evcnt =
203 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "immediate");
204 EVCNT_ATTACH_STATIC(entropy_immediate_evcnt);
205 static struct evcnt entropy_partial_evcnt =
206 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "partial");
207 EVCNT_ATTACH_STATIC(entropy_partial_evcnt);
208 static struct evcnt entropy_consolidate_evcnt =
209 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "consolidate");
210 EVCNT_ATTACH_STATIC(entropy_consolidate_evcnt);
211 static struct evcnt entropy_extract_intr_evcnt =
212 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "extract intr");
213 EVCNT_ATTACH_STATIC(entropy_extract_intr_evcnt);
214 static struct evcnt entropy_extract_fail_evcnt =
215 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "extract fail");
216 EVCNT_ATTACH_STATIC(entropy_extract_fail_evcnt);
217 static struct evcnt entropy_request_evcnt =
218 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "request");
219 EVCNT_ATTACH_STATIC(entropy_request_evcnt);
220 static struct evcnt entropy_deplete_evcnt =
221 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "deplete");
222 EVCNT_ATTACH_STATIC(entropy_deplete_evcnt);
223 static struct evcnt entropy_notify_evcnt =
224 EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "entropy", "notify");
225 EVCNT_ATTACH_STATIC(entropy_notify_evcnt);
226
227 /* Sysctl knobs */
228 bool entropy_collection = 1;
229 bool entropy_depletion = 0; /* Silly! */
230
231 static const struct sysctlnode *entropy_sysctlroot;
232 static struct sysctllog *entropy_sysctllog;
233
234 /* Forward declarations */
235 static void entropy_init_cpu(void *, void *, struct cpu_info *);
236 static void entropy_fini_cpu(void *, void *, struct cpu_info *);
237 static void entropy_account_cpu(struct entropy_cpu *);
238 static void entropy_enter(const void *, size_t, unsigned);
239 static bool entropy_enter_intr(const void *, size_t, unsigned);
240 static void entropy_softintr(void *);
241 static void entropy_thread(void *);
242 static uint32_t entropy_pending(void);
243 static void entropy_pending_cpu(void *, void *, struct cpu_info *);
244 static void entropy_consolidate(void);
245 static void entropy_gather_xc(void *, void *);
246 static void entropy_notify(void);
247 static int sysctl_entropy_consolidate(SYSCTLFN_ARGS);
248 static void filt_entropy_read_detach(struct knote *);
249 static int filt_entropy_read_event(struct knote *, long);
250 static void entropy_request(size_t);
251 static void rnd_add_data_1(struct krndsource *, const void *, uint32_t,
252 uint32_t);
253 static unsigned rndsource_entropybits(struct krndsource *);
254 static void rndsource_entropybits_cpu(void *, void *, struct cpu_info *);
255 static void rndsource_to_user(struct krndsource *, rndsource_t *);
256 static void rndsource_to_user_est(struct krndsource *, rndsource_est_t *);
257
258 /*
259 * curcpu_available()
260 *
261 * True if we can inspect the current CPU. Early on this may not
262 * work. XXX On most if not all ports, this should work earlier.
263 */
264 static inline bool
265 curcpu_available(void)
266 {
267
268 return __predict_true(!cold);
269 }
270
271 /*
272 * entropy_timer()
273 *
274 * Cycle counter, time counter, or anything that changes a wee bit
275 * unpredictably.
276 */
277 static inline uint32_t
278 entropy_timer(void)
279 {
280 struct bintime bt;
281 uint32_t v;
282
283 /* Very early on, cpu_counter32() may not be available. */
284 if (!curcpu_available())
285 return 0;
286
287 /* If we have a CPU cycle counter, use the low 32 bits. */
288 #ifdef __HAVE_CPU_COUNTER
289 if (__predict_true(cpu_hascounter()))
290 return cpu_counter32();
291 #endif /* __HAVE_CPU_COUNTER */
292
293 /* If we're cold, tough. Can't binuptime while cold. */
294 if (__predict_false(cold))
295 return 0;
296
297 /* Fold the 128 bits of binuptime into 32 bits. */
298 binuptime(&bt);
299 v = bt.frac;
300 v ^= bt.frac >> 32;
301 v ^= bt.sec;
302 v ^= bt.sec >> 32;
303 return v;
304 }
305
306 static void
307 attach_seed_rndsource(void)
308 {
309
310 /*
311 * First called no later than entropy_init, while we are still
312 * single-threaded, so no need for RUN_ONCE.
313 */
314 if (E->stage >= ENTROPY_WARM || E->seed_rndsource)
315 return;
316 rnd_attach_source(&seed_rndsource, "seed", RND_TYPE_UNKNOWN,
317 RND_FLAG_COLLECT_VALUE);
318 E->seed_rndsource = true;
319 }
320
321 /*
322 * entropy_init()
323 *
324 * Initialize the entropy subsystem. Panic on failure.
325 *
326 * Requires percpu(9) and sysctl(9) to be initialized.
327 */
328 static void
329 entropy_init(void)
330 {
331 uint32_t extra[2];
332 struct krndsource *rs;
333 unsigned i = 0;
334
335 KASSERT(E->stage == ENTROPY_COLD);
336
337 /* Grab some cycle counts early at boot. */
338 extra[i++] = entropy_timer();
339
340 /* Run the entropy pool cryptography self-test. */
341 if (entpool_selftest() == -1)
342 panic("entropy pool crypto self-test failed");
343
344 /* Create the sysctl directory. */
345 sysctl_createv(&entropy_sysctllog, 0, NULL, &entropy_sysctlroot,
346 CTLFLAG_PERMANENT, CTLTYPE_NODE, "entropy",
347 SYSCTL_DESCR("Entropy (random number sources) options"),
348 NULL, 0, NULL, 0,
349 CTL_KERN, CTL_CREATE, CTL_EOL);
350
351 /* Create the sysctl knobs. */
352 /* XXX These shouldn't be writable at securelevel>0. */
353 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
354 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "collection",
355 SYSCTL_DESCR("Automatically collect entropy from hardware"),
356 NULL, 0, &entropy_collection, 0, CTL_CREATE, CTL_EOL);
357 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
358 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "depletion",
359 SYSCTL_DESCR("`Deplete' entropy pool when observed"),
360 NULL, 0, &entropy_depletion, 0, CTL_CREATE, CTL_EOL);
361 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
362 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "consolidate",
363 SYSCTL_DESCR("Trigger entropy consolidation now"),
364 sysctl_entropy_consolidate, 0, NULL, 0, CTL_CREATE, CTL_EOL);
365 /* XXX These should maybe not be readable at securelevel>0. */
366 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
367 CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
368 "needed", SYSCTL_DESCR("Systemwide entropy deficit"),
369 NULL, 0, &E->needed, 0, CTL_CREATE, CTL_EOL);
370 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
371 CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
372 "pending", SYSCTL_DESCR("Entropy pending on CPUs"),
373 NULL, 0, &E->pending, 0, CTL_CREATE, CTL_EOL);
374 sysctl_createv(&entropy_sysctllog, 0, &entropy_sysctlroot, NULL,
375 CTLFLAG_PERMANENT|CTLFLAG_READONLY|CTLFLAG_PRIVATE, CTLTYPE_INT,
376 "epoch", SYSCTL_DESCR("Entropy epoch"),
377 NULL, 0, &E->epoch, 0, CTL_CREATE, CTL_EOL);
378
379 /* Initialize the global state for multithreaded operation. */
380 mutex_init(&E->lock, MUTEX_DEFAULT, IPL_VM);
381 cv_init(&E->cv, "entropy");
382 selinit(&E->selq);
383
384 /* Make sure the seed source is attached. */
385 attach_seed_rndsource();
386
387 /* Note if the bootloader didn't provide a seed. */
388 if (!E->seeded)
389 printf("entropy: no seed from bootloader\n");
390
391 /* Allocate the per-CPU records for all early entropy sources. */
392 LIST_FOREACH(rs, &E->sources, list)
393 rs->state = percpu_alloc(sizeof(struct rndsource_cpu));
394
395 /* Enter the boot cycle count to get started. */
396 extra[i++] = entropy_timer();
397 KASSERT(i == __arraycount(extra));
398 entropy_enter(extra, sizeof extra, 0);
399 explicit_memset(extra, 0, sizeof extra);
400
401 /* We are now ready for multi-threaded operation. */
402 E->stage = ENTROPY_WARM;
403 }
404
405 /*
406 * entropy_init_late()
407 *
408 * Late initialization. Panic on failure.
409 *
410 * Requires CPUs to have been detected and LWPs to have started.
411 */
412 static void
413 entropy_init_late(void)
414 {
415 int error;
416
417 KASSERT(E->stage == ENTROPY_WARM);
418
419 /* Allocate and initialize the per-CPU state. */
420 entropy_percpu = percpu_create(sizeof(struct entropy_cpu),
421 entropy_init_cpu, entropy_fini_cpu, NULL);
422
423 /*
424 * Establish the softint at the highest softint priority level.
425 * Must happen after CPU detection.
426 */
427 entropy_sih = softint_establish(SOFTINT_SERIAL|SOFTINT_MPSAFE,
428 &entropy_softintr, NULL);
429 if (entropy_sih == NULL)
430 panic("unable to establish entropy softint");
431
432 /*
433 * Create the entropy housekeeping thread. Must happen after
434 * lwpinit.
435 */
436 error = kthread_create(PRI_NONE, KTHREAD_MPSAFE|KTHREAD_TS, NULL,
437 entropy_thread, NULL, &entropy_lwp, "entbutler");
438 if (error)
439 panic("unable to create entropy housekeeping thread: %d",
440 error);
441
442 /*
443 * Wait until the per-CPU initialization has hit all CPUs
444 * before proceeding to mark the entropy system hot.
445 */
446 xc_barrier(XC_HIGHPRI);
447 E->stage = ENTROPY_HOT;
448 }
449
450 /*
451 * entropy_init_cpu(ptr, cookie, ci)
452 *
453 * percpu(9) constructor for per-CPU entropy pool.
454 */
455 static void
456 entropy_init_cpu(void *ptr, void *cookie, struct cpu_info *ci)
457 {
458 struct entropy_cpu *ec = ptr;
459
460 ec->ec_softint_evcnt = kmem_alloc(sizeof(*ec->ec_softint_evcnt),
461 KM_SLEEP);
462 ec->ec_pool = kmem_zalloc(sizeof(*ec->ec_pool), KM_SLEEP);
463 ec->ec_pending = 0;
464 ec->ec_locked = false;
465
466 evcnt_attach_dynamic(ec->ec_softint_evcnt, EVCNT_TYPE_MISC, NULL,
467 ci->ci_cpuname, "entropy softint");
468 }
469
470 /*
471 * entropy_fini_cpu(ptr, cookie, ci)
472 *
473 * percpu(9) destructor for per-CPU entropy pool.
474 */
475 static void
476 entropy_fini_cpu(void *ptr, void *cookie, struct cpu_info *ci)
477 {
478 struct entropy_cpu *ec = ptr;
479
480 /*
481 * Zero any lingering data. Disclosure of the per-CPU pool
482 * shouldn't retroactively affect the security of any keys
483 * generated, because entpool(9) erases whatever we have just
484 * drawn out of any pool, but better safe than sorry.
485 */
486 explicit_memset(ec->ec_pool, 0, sizeof(*ec->ec_pool));
487
488 evcnt_detach(ec->ec_softint_evcnt);
489
490 kmem_free(ec->ec_pool, sizeof(*ec->ec_pool));
491 kmem_free(ec->ec_softint_evcnt, sizeof(*ec->ec_softint_evcnt));
492 }
493
494 /*
495 * entropy_seed(seed)
496 *
497 * Seed the entropy pool with seed. Meant to be called as early
498 * as possible by the bootloader; may be called before or after
499 * entropy_init. Must be called before system reaches userland.
500 * Must be called in thread or soft interrupt context, not in hard
501 * interrupt context. Must be called at most once.
502 *
503 * Overwrites the seed in place. Caller may then free the memory.
504 */
505 static void
506 entropy_seed(rndsave_t *seed)
507 {
508 SHA1_CTX ctx;
509 uint8_t digest[SHA1_DIGEST_LENGTH];
510 bool seeded;
511
512 /*
513 * Verify the checksum. If the checksum fails, take the data
514 * but ignore the entropy estimate -- the file may have been
515 * incompletely written with garbage, which is harmless to add
516 * but may not be as unpredictable as alleged.
517 */
518 SHA1Init(&ctx);
519 SHA1Update(&ctx, (const void *)&seed->entropy, sizeof(seed->entropy));
520 SHA1Update(&ctx, seed->data, sizeof(seed->data));
521 SHA1Final(digest, &ctx);
522 CTASSERT(sizeof(seed->digest) == sizeof(digest));
523 if (!consttime_memequal(digest, seed->digest, sizeof(digest))) {
524 printf("entropy: invalid seed checksum\n");
525 seed->entropy = 0;
526 }
527 explicit_memset(&ctx, 0, sizeof ctx);
528 explicit_memset(digest, 0, sizeof digest);
529
530 /*
531 * If the entropy is insensibly large, try byte-swapping.
532 * Otherwise assume the file is corrupted and act as though it
533 * has zero entropy.
534 */
535 if (howmany(seed->entropy, NBBY) > sizeof(seed->data)) {
536 seed->entropy = bswap32(seed->entropy);
537 if (howmany(seed->entropy, NBBY) > sizeof(seed->data))
538 seed->entropy = 0;
539 }
540
541 /* Make sure the seed source is attached. */
542 attach_seed_rndsource();
543
544 /* Test and set E->seeded. */
545 if (E->stage >= ENTROPY_WARM)
546 mutex_enter(&E->lock);
547 seeded = E->seeded;
548 E->seeded = true;
549 if (E->stage >= ENTROPY_WARM)
550 mutex_exit(&E->lock);
551
552 /*
553 * If we've been seeded, may be re-entering the same seed
554 * (e.g., bootloader vs module init, or something). No harm in
555 * entering it twice, but it contributes no additional entropy.
556 */
557 if (seeded) {
558 printf("entropy: double-seeded by bootloader\n");
559 seed->entropy = 0;
560 } else {
561 printf("entropy: entering seed from bootloader\n");
562 }
563
564 /* Enter it into the pool and promptly zero it. */
565 rnd_add_data(&seed_rndsource, seed->data, sizeof(seed->data),
566 seed->entropy);
567 explicit_memset(seed, 0, sizeof(*seed));
568 }
569
570 /*
571 * entropy_bootrequest()
572 *
573 * Request entropy from all sources at boot, once config is
574 * complete and interrupts are running.
575 */
576 void
577 entropy_bootrequest(void)
578 {
579
580 KASSERT(E->stage >= ENTROPY_WARM);
581
582 /*
583 * Request enough to satisfy the maximum entropy shortage.
584 * This is harmless overkill if the bootloader provided a seed.
585 */
586 mutex_enter(&E->lock);
587 entropy_request(ENTROPY_CAPACITY);
588 mutex_exit(&E->lock);
589 }
590
591 /*
592 * entropy_epoch()
593 *
594 * Returns the current entropy epoch. If this changes, you should
595 * reseed. If -1, means the system has not yet reached full
596 * entropy; never reverts back to -1 after full entropy has been
597 * reached. Never zero, so you can always use zero as an
598 * uninitialized sentinel value meaning `reseed ASAP'.
599 *
600 * Usage model:
601 *
602 * struct foo {
603 * struct crypto_prng prng;
604 * unsigned epoch;
605 * } *foo;
606 *
607 * unsigned epoch = entropy_epoch();
608 * if (__predict_false(epoch != foo->epoch)) {
609 * uint8_t seed[32];
610 * if (entropy_extract(seed, sizeof seed, 0) != 0)
611 * warn("no entropy");
612 * crypto_prng_reseed(&foo->prng, seed, sizeof seed);
613 * foo->epoch = epoch;
614 * }
615 */
616 unsigned
617 entropy_epoch(void)
618 {
619
620 /*
621 * Unsigned int, so no need for seqlock for an atomic read, but
622 * make sure we read it afresh each time.
623 */
624 return atomic_load_relaxed(&E->epoch);
625 }
626
627 /*
628 * entropy_account_cpu(ec)
629 *
630 * Consider whether to consolidate entropy into the global pool
631 * after we just added some into the current CPU's pending pool.
632 *
633 * - If this CPU can provide enough entropy now, do so.
634 *
635 * - If this and whatever else is available on other CPUs can
636 * provide enough entropy, kick the consolidation thread.
637 *
638 * - Otherwise, do as little as possible, except maybe consolidate
639 * entropy at most once a minute.
640 *
641 * Caller must be bound to a CPU and therefore have exclusive
642 * access to ec. Will acquire and release the global lock.
643 */
644 static void
645 entropy_account_cpu(struct entropy_cpu *ec)
646 {
647 unsigned diff;
648
649 KASSERT(E->stage == ENTROPY_HOT);
650
651 /*
652 * If there's no entropy needed, and entropy has been
653 * consolidated in the last minute, do nothing.
654 */
655 if (__predict_true(atomic_load_relaxed(&E->needed) == 0) &&
656 __predict_true(!atomic_load_relaxed(&entropy_depletion)) &&
657 __predict_true((time_uptime - E->timestamp) <= 60))
658 return;
659
660 /* If there's nothing pending, stop here. */
661 if (ec->ec_pending == 0)
662 return;
663
664 /* Consider consolidation, under the lock. */
665 mutex_enter(&E->lock);
666 if (E->needed != 0 && E->needed <= ec->ec_pending) {
667 /*
668 * If we have not yet attained full entropy but we can
669 * now, do so. This way we disseminate entropy
670 * promptly when it becomes available early at boot;
671 * otherwise we leave it to the entropy consolidation
672 * thread, which is rate-limited to mitigate side
673 * channels and abuse.
674 */
675 uint8_t buf[ENTPOOL_CAPACITY];
676
677 /* Transfer from the local pool to the global pool. */
678 entpool_extract(ec->ec_pool, buf, sizeof buf);
679 entpool_enter(&E->pool, buf, sizeof buf);
680 atomic_store_relaxed(&ec->ec_pending, 0);
681 atomic_store_relaxed(&E->needed, 0);
682
683 /* Notify waiters that we now have full entropy. */
684 entropy_notify();
685 entropy_immediate_evcnt.ev_count++;
686 } else if (ec->ec_pending) {
687 /* Record how much we can add to the global pool. */
688 diff = MIN(ec->ec_pending, ENTROPY_CAPACITY*NBBY - E->pending);
689 E->pending += diff;
690 atomic_store_relaxed(&ec->ec_pending, ec->ec_pending - diff);
691
692 /*
693 * This should have made a difference unless we were
694 * already saturated.
695 */
696 KASSERT(diff || E->pending == ENTROPY_CAPACITY*NBBY);
697 KASSERT(E->pending);
698
699 if (E->needed <= E->pending) {
700 /*
701 * Enough entropy between all the per-CPU
702 * pools. Wake up the housekeeping thread.
703 *
704 * If we don't need any entropy, this doesn't
705 * mean much, but it is the only time we ever
706 * gather additional entropy in case the
707 * accounting has been overly optimistic. This
708 * happens at most once a minute, so there's
709 * negligible performance cost.
710 */
711 E->consolidate = true;
712 cv_broadcast(&E->cv);
713 if (E->needed == 0)
714 entropy_discretionary_evcnt.ev_count++;
715 } else {
716 /* Can't get full entropy. Keep gathering. */
717 entropy_partial_evcnt.ev_count++;
718 }
719 }
720 mutex_exit(&E->lock);
721 }
722
723 /*
724 * entropy_enter_early(buf, len, nbits)
725 *
726 * Do entropy bookkeeping globally, before we have established
727 * per-CPU pools. Enter directly into the global pool in the hope
728 * that we enter enough before the first entropy_extract to thwart
729 * iterative-guessing attacks; entropy_extract will warn if not.
730 */
731 static void
732 entropy_enter_early(const void *buf, size_t len, unsigned nbits)
733 {
734 bool notify = false;
735
736 if (E->stage >= ENTROPY_WARM)
737 mutex_enter(&E->lock);
738
739 /* Enter it into the pool. */
740 entpool_enter(&E->pool, buf, len);
741
742 /*
743 * Decide whether to notify reseed -- we will do so if either:
744 * (a) we transition from partial entropy to full entropy, or
745 * (b) we get a batch of full entropy all at once.
746 */
747 notify |= (E->needed && E->needed <= nbits);
748 notify |= (nbits >= ENTROPY_CAPACITY*NBBY);
749
750 /* Subtract from the needed count and notify if appropriate. */
751 E->needed -= MIN(E->needed, nbits);
752 if (notify) {
753 entropy_notify();
754 entropy_immediate_evcnt.ev_count++;
755 }
756
757 if (E->stage >= ENTROPY_WARM)
758 mutex_exit(&E->lock);
759 }
760
761 /*
762 * entropy_enter(buf, len, nbits)
763 *
764 * Enter len bytes of data from buf into the system's entropy
765 * pool, stirring as necessary when the internal buffer fills up.
766 * nbits is a lower bound on the number of bits of entropy in the
767 * process that led to this sample.
768 */
769 static void
770 entropy_enter(const void *buf, size_t len, unsigned nbits)
771 {
772 struct entropy_cpu *ec;
773 uint32_t pending;
774 int s;
775
776 KASSERTMSG(!curcpu_available() || !cpu_intr_p(),
777 "use entropy_enter_intr from interrupt context");
778 KASSERTMSG(howmany(nbits, NBBY) <= len,
779 "impossible entropy rate: %u bits in %zu-byte string", nbits, len);
780
781 /* If it's too early after boot, just use entropy_enter_early. */
782 if (__predict_false(E->stage < ENTROPY_HOT)) {
783 entropy_enter_early(buf, len, nbits);
784 return;
785 }
786
787 /*
788 * Acquire the per-CPU state, blocking soft interrupts and
789 * causing hard interrupts to drop samples on the floor.
790 */
791 ec = percpu_getref(entropy_percpu);
792 s = splsoftserial();
793 KASSERT(!ec->ec_locked);
794 ec->ec_locked = true;
795 __insn_barrier();
796
797 /* Enter into the per-CPU pool. */
798 entpool_enter(ec->ec_pool, buf, len);
799
800 /* Count up what we can add. */
801 pending = ec->ec_pending;
802 pending += MIN(ENTROPY_CAPACITY*NBBY - pending, nbits);
803 atomic_store_relaxed(&ec->ec_pending, pending);
804
805 /* Consolidate globally if appropriate based on what we added. */
806 entropy_account_cpu(ec);
807
808 /* Release the per-CPU state. */
809 KASSERT(ec->ec_locked);
810 __insn_barrier();
811 ec->ec_locked = false;
812 splx(s);
813 percpu_putref(entropy_percpu);
814 }
815
816 /*
817 * entropy_enter_intr(buf, len, nbits)
818 *
819 * Enter up to len bytes of data from buf into the system's
820 * entropy pool without stirring. nbits is a lower bound on the
821 * number of bits of entropy in the process that led to this
822 * sample. If the sample could be entered completely, assume
823 * nbits of entropy pending; otherwise assume none, since we don't
824 * know whether some parts of the sample are constant, for
825 * instance. Schedule a softint to stir the entropy pool if
826 * needed. Return true if used fully, false if truncated at all.
827 *
828 * Using this in thread context will work, but you might as well
829 * use entropy_enter in that case.
830 */
831 static bool
832 entropy_enter_intr(const void *buf, size_t len, unsigned nbits)
833 {
834 struct entropy_cpu *ec;
835 bool fullyused = false;
836 uint32_t pending;
837
838 KASSERTMSG(howmany(nbits, NBBY) <= len,
839 "impossible entropy rate: %u bits in %zu-byte string", nbits, len);
840
841 /* If it's too early after boot, just use entropy_enter_early. */
842 if (__predict_false(E->stage < ENTROPY_HOT)) {
843 entropy_enter_early(buf, len, nbits);
844 return true;
845 }
846
847 /*
848 * Acquire the per-CPU state. If someone is in the middle of
849 * using it, drop the sample. Otherwise, take the lock so that
850 * higher-priority interrupts will drop their samples.
851 */
852 ec = percpu_getref(entropy_percpu);
853 if (ec->ec_locked)
854 goto out0;
855 ec->ec_locked = true;
856 __insn_barrier();
857
858 /*
859 * Enter as much as we can into the per-CPU pool. If it was
860 * truncated, schedule a softint to stir the pool and stop.
861 */
862 if (!entpool_enter_nostir(ec->ec_pool, buf, len)) {
863 softint_schedule(entropy_sih);
864 goto out1;
865 }
866 fullyused = true;
867
868 /* Count up what we can contribute. */
869 pending = ec->ec_pending;
870 pending += MIN(ENTROPY_CAPACITY*NBBY - pending, nbits);
871 atomic_store_relaxed(&ec->ec_pending, pending);
872
873 /* Schedule a softint if we added anything and it matters. */
874 if (__predict_false((atomic_load_relaxed(&E->needed) != 0) ||
875 atomic_load_relaxed(&entropy_depletion)) &&
876 nbits != 0)
877 softint_schedule(entropy_sih);
878
879 out1: /* Release the per-CPU state. */
880 KASSERT(ec->ec_locked);
881 __insn_barrier();
882 ec->ec_locked = false;
883 out0: percpu_putref(entropy_percpu);
884
885 return fullyused;
886 }
887
888 /*
889 * entropy_softintr(cookie)
890 *
891 * Soft interrupt handler for entering entropy. Takes care of
892 * stirring the local CPU's entropy pool if it filled up during
893 * hard interrupts, and promptly crediting entropy from the local
894 * CPU's entropy pool to the global entropy pool if needed.
895 */
896 static void
897 entropy_softintr(void *cookie)
898 {
899 struct entropy_cpu *ec;
900
901 /*
902 * Acquire the per-CPU state. Other users can lock this only
903 * while soft interrupts are blocked. Cause hard interrupts to
904 * drop samples on the floor.
905 */
906 ec = percpu_getref(entropy_percpu);
907 KASSERT(!ec->ec_locked);
908 ec->ec_locked = true;
909 __insn_barrier();
910
911 /* Count statistics. */
912 ec->ec_softint_evcnt->ev_count++;
913
914 /* Stir the pool if necessary. */
915 entpool_stir(ec->ec_pool);
916
917 /* Consolidate globally if appropriate based on what we added. */
918 entropy_account_cpu(ec);
919
920 /* Release the per-CPU state. */
921 KASSERT(ec->ec_locked);
922 __insn_barrier();
923 ec->ec_locked = false;
924 percpu_putref(entropy_percpu);
925 }
926
927 /*
928 * entropy_thread(cookie)
929 *
930 * Handle any asynchronous entropy housekeeping.
931 */
932 static void
933 entropy_thread(void *cookie)
934 {
935
936 for (;;) {
937 /*
938 * Wait until someone wants to consolidate or there's
939 * full entropy somewhere among the CPUs, as confirmed
940 * at most once per minute.
941 */
942 mutex_enter(&E->lock);
943 for (;;) {
944 if (E->consolidate ||
945 entropy_pending() >= ENTROPY_CAPACITY*NBBY) {
946 E->consolidate = false;
947 break;
948 }
949 cv_timedwait(&E->cv, &E->lock, 60*hz);
950 }
951 mutex_exit(&E->lock);
952
953 /* Do it. */
954 entropy_consolidate();
955
956 /* Mitigate abuse. */
957 kpause("entropy", false, hz, NULL);
958 }
959 }
960
961 /*
962 * entropy_pending()
963 *
964 * Count up the amount of entropy pending on other CPUs.
965 */
966 static uint32_t
967 entropy_pending(void)
968 {
969 uint32_t pending = 0;
970
971 percpu_foreach(entropy_percpu, &entropy_pending_cpu, &pending);
972
973 return pending;
974 }
975
976 static void
977 entropy_pending_cpu(void *ptr, void *cookie, struct cpu_info *ci)
978 {
979 struct entropy_cpu *ec = ptr;
980 uint32_t *pendingp = cookie;
981 uint32_t cpu_pending;
982
983 cpu_pending = atomic_load_relaxed(&ec->ec_pending);
984 *pendingp += MIN(ENTROPY_CAPACITY*NBBY - *pendingp, cpu_pending);
985 }
986
987 /*
988 * entropy_consolidate()
989 *
990 * Issue a cross-call to gather entropy on all CPUs and advance
991 * the entropy epoch.
992 */
993 static void
994 entropy_consolidate(void)
995 {
996 static const struct timeval interval = {.tv_sec = 60, .tv_usec = 0};
997 static struct timeval lasttime; /* serialized by E->lock */
998 unsigned diff;
999 uint64_t ticket;
1000
1001 /* Gather entropy on all CPUs. */
1002 ticket = xc_broadcast(0, &entropy_gather_xc, NULL, NULL);
1003 xc_wait(ticket);
1004
1005 /* Acquire the lock to notify waiters. */
1006 mutex_enter(&E->lock);
1007
1008 /* Count another consolidation. */
1009 entropy_consolidate_evcnt.ev_count++;
1010
1011 /* Note when we last consolidated, i.e. now. */
1012 E->timestamp = time_uptime;
1013
1014 /* Count the entropy that was gathered. */
1015 diff = MIN(E->needed, E->pending);
1016 atomic_store_relaxed(&E->needed, E->needed - diff);
1017 E->pending -= diff;
1018 if (__predict_false(E->needed > 0)) {
1019 if (ratecheck(&lasttime, &interval))
1020 printf("entropy: WARNING:"
1021 " consolidating less than full entropy\n");
1022 }
1023
1024 /* Advance the epoch and notify waiters. */
1025 entropy_notify();
1026
1027 /* Release the lock. */
1028 mutex_exit(&E->lock);
1029 }
1030
1031 /*
1032 * entropy_gather_xc(arg1, arg2)
1033 *
1034 * Extract output from the local CPU's input pool and enter it
1035 * into the global pool.
1036 */
1037 static void
1038 entropy_gather_xc(void *arg1 __unused, void *arg2 __unused)
1039 {
1040 struct entropy_cpu *ec;
1041 uint8_t buf[ENTPOOL_CAPACITY];
1042 uint32_t extra[7];
1043 unsigned i = 0;
1044 int s;
1045
1046 /* Grab CPU number and cycle counter to mix extra into the pool. */
1047 extra[i++] = cpu_number();
1048 extra[i++] = entropy_timer();
1049
1050 /*
1051 * Acquire the per-CPU state, blocking soft interrupts and
1052 * discarding entropy in hard interrupts, so that we can
1053 * extract from the per-CPU pool.
1054 */
1055 ec = percpu_getref(entropy_percpu);
1056 s = splsoftserial();
1057 KASSERT(!ec->ec_locked);
1058 ec->ec_locked = true;
1059 __insn_barrier();
1060 extra[i++] = entropy_timer();
1061
1062 /* Extract the data. */
1063 entpool_extract(ec->ec_pool, buf, sizeof buf);
1064 extra[i++] = entropy_timer();
1065
1066 /* Release the per-CPU state. */
1067 KASSERT(ec->ec_locked);
1068 __insn_barrier();
1069 ec->ec_locked = false;
1070 splx(s);
1071 percpu_putref(entropy_percpu);
1072 extra[i++] = entropy_timer();
1073
1074 /*
1075 * Copy over statistics, and enter the per-CPU extract and the
1076 * extra timing into the global pool, under the global lock.
1077 */
1078 mutex_enter(&E->lock);
1079 extra[i++] = entropy_timer();
1080 entpool_enter(&E->pool, buf, sizeof buf);
1081 explicit_memset(buf, 0, sizeof buf);
1082 extra[i++] = entropy_timer();
1083 KASSERT(i == __arraycount(extra));
1084 entpool_enter(&E->pool, extra, sizeof extra);
1085 explicit_memset(extra, 0, sizeof extra);
1086 mutex_exit(&E->lock);
1087 }
1088
1089 /*
1090 * entropy_notify()
1091 *
1092 * Caller just contributed entropy to the global pool. Advance
1093 * the entropy epoch and notify waiters.
1094 *
1095 * Caller must hold the global entropy lock. Except for the
1096 * `sysctl -w kern.entropy.consolidate=1` trigger, the caller must
1097 * have just have transitioned from partial entropy to full
1098 * entropy -- E->needed should be zero now.
1099 */
1100 static void
1101 entropy_notify(void)
1102 {
1103 unsigned epoch;
1104
1105 KASSERT(E->stage == ENTROPY_COLD || mutex_owned(&E->lock));
1106
1107 /*
1108 * If this is the first time, print a message to the console
1109 * that we're ready so operators can compare it to the timing
1110 * of other events.
1111 */
1112 if (E->epoch == (unsigned)-1)
1113 printf("entropy: ready\n");
1114
1115 /* Set the epoch; roll over from UINTMAX-1 to 1. */
1116 rnd_initial_entropy = 1; /* XXX legacy */
1117 epoch = E->epoch + 1;
1118 if (epoch == 0 || epoch == (unsigned)-1)
1119 epoch = 1;
1120 atomic_store_relaxed(&E->epoch, epoch);
1121
1122 /* Notify waiters. */
1123 if (E->stage >= ENTROPY_WARM) {
1124 cv_broadcast(&E->cv);
1125 selnotify(&E->selq, POLLIN|POLLRDNORM, NOTE_SUBMIT);
1126 }
1127
1128 /* Count another notification. */
1129 entropy_notify_evcnt.ev_count++;
1130 }
1131
1132 /*
1133 * sysctl -w kern.entropy.consolidate=1
1134 *
1135 * Trigger entropy consolidation and wait for it to complete.
1136 * Writable only by superuser. This is the only way for the
1137 * system to consolidate entropy if the operator knows something
1138 * the kernel doesn't about how unpredictable the pending entropy
1139 * pools are.
1140 */
1141 static int
1142 sysctl_entropy_consolidate(SYSCTLFN_ARGS)
1143 {
1144 struct sysctlnode node = *rnode;
1145 uint64_t ticket;
1146 int arg;
1147 int error;
1148
1149 KASSERT(E->stage == ENTROPY_HOT);
1150
1151 node.sysctl_data = &arg;
1152 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1153 if (error || newp == NULL)
1154 return error;
1155 if (arg) {
1156 mutex_enter(&E->lock);
1157 ticket = entropy_consolidate_evcnt.ev_count;
1158 E->consolidate = true;
1159 cv_broadcast(&E->cv);
1160 while (ticket == entropy_consolidate_evcnt.ev_count) {
1161 error = cv_wait_sig(&E->cv, &E->lock);
1162 if (error)
1163 break;
1164 }
1165 mutex_exit(&E->lock);
1166 }
1167
1168 return error;
1169 }
1170
1171 /*
1172 * entropy_extract(buf, len, flags)
1173 *
1174 * Extract len bytes from the global entropy pool into buf.
1175 *
1176 * Flags may have:
1177 *
1178 * ENTROPY_WAIT Wait for entropy if not available yet.
1179 * ENTROPY_SIG Allow interruption by a signal during wait.
1180 *
1181 * Return zero on success, or error on failure:
1182 *
1183 * EWOULDBLOCK No entropy and ENTROPY_WAIT not set.
1184 * EINTR/ERESTART No entropy, ENTROPY_SIG set, and interrupted.
1185 *
1186 * If ENTROPY_WAIT is set, allowed only in thread context. If
1187 * ENTROPY_WAIT is not set, allowed up to IPL_VM. (XXX That's
1188 * awfully high... Do we really need it in hard interrupts? This
1189 * arises from use of cprng_strong(9).)
1190 */
1191 int
1192 entropy_extract(void *buf, size_t len, int flags)
1193 {
1194 static const struct timeval interval = {.tv_sec = 60, .tv_usec = 0};
1195 static struct timeval lasttime; /* serialized by E->lock */
1196 int error;
1197
1198 if (ISSET(flags, ENTROPY_WAIT)) {
1199 ASSERT_SLEEPABLE();
1200 KASSERTMSG(E->stage >= ENTROPY_WARM,
1201 "can't wait for entropy until warm");
1202 }
1203
1204 /* Acquire the global lock to get at the global pool. */
1205 if (E->stage >= ENTROPY_WARM)
1206 mutex_enter(&E->lock);
1207
1208 /* Count up request for entropy in interrupt context. */
1209 if (curcpu_available() && cpu_intr_p())
1210 entropy_extract_intr_evcnt.ev_count++;
1211
1212 /* Wait until there is enough entropy in the system. */
1213 error = 0;
1214 while (E->needed) {
1215 /* Ask for more, synchronously if possible. */
1216 entropy_request(len);
1217
1218 /* If we got enough, we're done. */
1219 if (E->needed == 0) {
1220 KASSERT(error == 0);
1221 break;
1222 }
1223
1224 /* If not waiting, stop here. */
1225 if (!ISSET(flags, ENTROPY_WAIT)) {
1226 error = EWOULDBLOCK;
1227 break;
1228 }
1229
1230 /* Wait for some entropy to come in and try again. */
1231 KASSERT(E->stage >= ENTROPY_WARM);
1232 if (ISSET(flags, ENTROPY_SIG)) {
1233 error = cv_wait_sig(&E->cv, &E->lock);
1234 if (error)
1235 break;
1236 } else {
1237 cv_wait(&E->cv, &E->lock);
1238 }
1239 }
1240
1241 /* Count failure -- but fill the buffer nevertheless. */
1242 if (error)
1243 entropy_extract_fail_evcnt.ev_count++;
1244
1245 /*
1246 * Report a warning if we have never yet reached full entropy.
1247 * This is the only case where we consider entropy to be
1248 * `depleted' without kern.entropy.depletion enabled -- when we
1249 * only have partial entropy, an adversary may be able to
1250 * narrow the state of the pool down to a small number of
1251 * possibilities; the output then enables them to confirm a
1252 * guess, reducing its entropy from the adversary's perspective
1253 * to zero.
1254 */
1255 if (__predict_false(E->epoch == (unsigned)-1)) {
1256 if (ratecheck(&lasttime, &interval))
1257 printf("entropy: WARNING:"
1258 " extracting entropy too early\n");
1259 atomic_store_relaxed(&E->needed, ENTROPY_CAPACITY*NBBY);
1260 }
1261
1262 /* Extract data from the pool, and `deplete' if we're doing that. */
1263 entpool_extract(&E->pool, buf, len);
1264 if (__predict_false(atomic_load_relaxed(&entropy_depletion)) &&
1265 error == 0) {
1266 unsigned cost = MIN(len, ENTROPY_CAPACITY)*NBBY;
1267
1268 atomic_store_relaxed(&E->needed,
1269 E->needed + MIN(ENTROPY_CAPACITY*NBBY - E->needed, cost));
1270 entropy_deplete_evcnt.ev_count++;
1271 }
1272
1273 /* Release the global lock and return the error. */
1274 if (E->stage >= ENTROPY_WARM)
1275 mutex_exit(&E->lock);
1276 return error;
1277 }
1278
1279 /*
1280 * entropy_poll(events)
1281 *
1282 * Return the subset of events ready, and if it is not all of
1283 * events, record curlwp as waiting for entropy.
1284 */
1285 int
1286 entropy_poll(int events)
1287 {
1288 int revents = 0;
1289
1290 KASSERT(E->stage >= ENTROPY_WARM);
1291
1292 /* Always ready for writing. */
1293 revents |= events & (POLLOUT|POLLWRNORM);
1294
1295 /* Narrow it down to reads. */
1296 events &= POLLIN|POLLRDNORM;
1297 if (events == 0)
1298 return revents;
1299
1300 /*
1301 * If we have reached full entropy and we're not depleting
1302 * entropy, we are forever ready.
1303 */
1304 if (__predict_true(atomic_load_relaxed(&E->needed) == 0) &&
1305 __predict_true(!atomic_load_relaxed(&entropy_depletion)))
1306 return revents | events;
1307
1308 /*
1309 * Otherwise, check whether we need entropy under the lock. If
1310 * we don't, we're ready; if we do, add ourselves to the queue.
1311 */
1312 mutex_enter(&E->lock);
1313 if (E->needed == 0)
1314 revents |= events;
1315 else
1316 selrecord(curlwp, &E->selq);
1317 mutex_exit(&E->lock);
1318
1319 return revents;
1320 }
1321
1322 /*
1323 * filt_entropy_read_detach(kn)
1324 *
1325 * struct filterops::f_detach callback for entropy read events:
1326 * remove kn from the list of waiters.
1327 */
1328 static void
1329 filt_entropy_read_detach(struct knote *kn)
1330 {
1331
1332 KASSERT(E->stage >= ENTROPY_WARM);
1333
1334 mutex_enter(&E->lock);
1335 SLIST_REMOVE(&E->selq.sel_klist, kn, knote, kn_selnext);
1336 mutex_exit(&E->lock);
1337 }
1338
1339 /*
1340 * filt_entropy_read_event(kn, hint)
1341 *
1342 * struct filterops::f_event callback for entropy read events:
1343 * poll for entropy. Caller must hold the global entropy lock if
1344 * hint is NOTE_SUBMIT, and must not if hint is not NOTE_SUBMIT.
1345 */
1346 static int
1347 filt_entropy_read_event(struct knote *kn, long hint)
1348 {
1349 int ret;
1350
1351 KASSERT(E->stage >= ENTROPY_WARM);
1352
1353 /* Acquire the lock, if caller is outside entropy subsystem. */
1354 if (hint == NOTE_SUBMIT)
1355 KASSERT(mutex_owned(&E->lock));
1356 else
1357 mutex_enter(&E->lock);
1358
1359 /*
1360 * If we still need entropy, can't read anything; if not, can
1361 * read arbitrarily much.
1362 */
1363 if (E->needed != 0) {
1364 ret = 0;
1365 } else {
1366 if (atomic_load_relaxed(&entropy_depletion))
1367 kn->kn_data = ENTROPY_CAPACITY*NBBY;
1368 else
1369 kn->kn_data = MIN(INT64_MAX, SSIZE_MAX);
1370 ret = 1;
1371 }
1372
1373 /* Release the lock, if caller is outside entropy subsystem. */
1374 if (hint == NOTE_SUBMIT)
1375 KASSERT(mutex_owned(&E->lock));
1376 else
1377 mutex_exit(&E->lock);
1378
1379 return ret;
1380 }
1381
1382 static const struct filterops entropy_read_filtops = {
1383 .f_isfd = 1, /* XXX Makes sense only for /dev/u?random. */
1384 .f_attach = NULL,
1385 .f_detach = filt_entropy_read_detach,
1386 .f_event = filt_entropy_read_event,
1387 };
1388
1389 /*
1390 * entropy_kqfilter(kn)
1391 *
1392 * Register kn to receive entropy event notifications. May be
1393 * EVFILT_READ or EVFILT_WRITE; anything else yields EINVAL.
1394 */
1395 int
1396 entropy_kqfilter(struct knote *kn)
1397 {
1398
1399 KASSERT(E->stage >= ENTROPY_WARM);
1400
1401 switch (kn->kn_filter) {
1402 case EVFILT_READ:
1403 /* Enter into the global select queue. */
1404 mutex_enter(&E->lock);
1405 kn->kn_fop = &entropy_read_filtops;
1406 SLIST_INSERT_HEAD(&E->selq.sel_klist, kn, kn_selnext);
1407 mutex_exit(&E->lock);
1408 return 0;
1409 case EVFILT_WRITE:
1410 /* Can always dump entropy into the system. */
1411 kn->kn_fop = &seltrue_filtops;
1412 return 0;
1413 default:
1414 return EINVAL;
1415 }
1416 }
1417
1418 /*
1419 * rndsource_setcb(rs, get, getarg)
1420 *
1421 * Set the request callback for the entropy source rs, if it can
1422 * provide entropy on demand. Must precede rnd_attach_source.
1423 */
1424 void
1425 rndsource_setcb(struct krndsource *rs, void (*get)(size_t, void *),
1426 void *getarg)
1427 {
1428
1429 rs->get = get;
1430 rs->getarg = getarg;
1431 }
1432
1433 /*
1434 * rnd_attach_source(rs, name, type, flags)
1435 *
1436 * Attach the entropy source rs. Must be done after
1437 * rndsource_setcb, if any, and before any calls to rnd_add_data.
1438 */
1439 void
1440 rnd_attach_source(struct krndsource *rs, const char *name, uint32_t type,
1441 uint32_t flags)
1442 {
1443 uint32_t extra[4];
1444 unsigned i = 0;
1445
1446 /* Grab cycle counter to mix extra into the pool. */
1447 extra[i++] = entropy_timer();
1448
1449 /*
1450 * Apply some standard flags:
1451 *
1452 * - We do not bother with network devices by default, for
1453 * hysterical raisins (perhaps: because it is often the case
1454 * that an adversary can influence network packet timings).
1455 */
1456 switch (type) {
1457 case RND_TYPE_NET:
1458 flags |= RND_FLAG_NO_COLLECT;
1459 break;
1460 }
1461
1462 /* Sanity-check the callback if RND_FLAG_HASCB is set. */
1463 KASSERT(!ISSET(flags, RND_FLAG_HASCB) || rs->get != NULL);
1464
1465 /* Initialize the random source. */
1466 memset(rs->name, 0, sizeof(rs->name)); /* paranoia */
1467 strlcpy(rs->name, name, sizeof(rs->name));
1468 rs->type = type;
1469 rs->flags = flags;
1470 if (E->stage >= ENTROPY_WARM)
1471 rs->state = percpu_alloc(sizeof(struct rndsource_cpu));
1472 extra[i++] = entropy_timer();
1473
1474 /* Wire it into the global list of random sources. */
1475 if (E->stage >= ENTROPY_WARM)
1476 mutex_enter(&E->lock);
1477 LIST_INSERT_HEAD(&E->sources, rs, list);
1478 if (E->stage >= ENTROPY_WARM)
1479 mutex_exit(&E->lock);
1480 extra[i++] = entropy_timer();
1481
1482 /* Request that it provide entropy ASAP, if we can. */
1483 if (ISSET(flags, RND_FLAG_HASCB))
1484 (*rs->get)(ENTROPY_CAPACITY, rs->getarg);
1485 extra[i++] = entropy_timer();
1486
1487 /* Mix the extra into the pool. */
1488 KASSERT(i == __arraycount(extra));
1489 entropy_enter(extra, sizeof extra, 0);
1490 explicit_memset(extra, 0, sizeof extra);
1491 }
1492
1493 /*
1494 * rnd_detach_source(rs)
1495 *
1496 * Detach the entropy source rs. May sleep waiting for users to
1497 * drain. Further use is not allowed.
1498 */
1499 void
1500 rnd_detach_source(struct krndsource *rs)
1501 {
1502
1503 /*
1504 * If we're cold (shouldn't happen, but hey), just remove it
1505 * from the list -- there's nothing allocated.
1506 */
1507 if (E->stage == ENTROPY_COLD) {
1508 LIST_REMOVE(rs, list);
1509 return;
1510 }
1511
1512 /* We may have to wait for entropy_request. */
1513 ASSERT_SLEEPABLE();
1514
1515 /* Remove it from the list and wait for entropy_request. */
1516 mutex_enter(&E->lock);
1517 LIST_REMOVE(rs, list);
1518 while (E->requesting)
1519 cv_wait(&E->cv, &E->lock);
1520 mutex_exit(&E->lock);
1521
1522 /* Free the per-CPU data. */
1523 percpu_free(rs->state, sizeof(struct rndsource_cpu));
1524 }
1525
1526 /*
1527 * entropy_request(nbytes)
1528 *
1529 * Request nbytes bytes of entropy from all sources in the system.
1530 * OK if we overdo it. Caller must hold the global entropy lock;
1531 * will release and re-acquire it.
1532 */
1533 static void
1534 entropy_request(size_t nbytes)
1535 {
1536 struct krndsource *rs, *next;
1537
1538 KASSERT(E->stage == ENTROPY_COLD || mutex_owned(&E->lock));
1539
1540 /*
1541 * If there is a request in progress, let it proceed.
1542 * Otherwise, note that a request is in progress to avoid
1543 * reentry and to block rnd_detach_source until we're done.
1544 */
1545 if (E->requesting)
1546 return;
1547 E->requesting = true;
1548 entropy_request_evcnt.ev_count++;
1549
1550 /* Clamp to the maximum reasonable request. */
1551 nbytes = MIN(nbytes, ENTROPY_CAPACITY);
1552
1553 /* Walk the list of sources. */
1554 LIST_FOREACH_SAFE(rs, &E->sources, list, next) {
1555 /* Skip sources without callbacks. */
1556 if (!ISSET(rs->flags, RND_FLAG_HASCB))
1557 continue;
1558
1559 /* Drop the lock while we call the callback. */
1560 if (E->stage >= ENTROPY_WARM)
1561 mutex_exit(&E->lock);
1562 (*rs->get)(nbytes, rs->getarg);
1563 if (E->stage >= ENTROPY_WARM)
1564 mutex_enter(&E->lock);
1565 }
1566
1567 /* Notify rnd_detach_source that the request is done. */
1568 E->requesting = false;
1569 if (E->stage >= ENTROPY_WARM)
1570 cv_broadcast(&E->cv);
1571 }
1572
1573 /*
1574 * rnd_add_uint32(rs, value)
1575 *
1576 * Enter 32 bits of data from an entropy source into the pool.
1577 *
1578 * If rs is NULL, may not be called from interrupt context.
1579 *
1580 * If rs is non-NULL, may be called from any context. May drop
1581 * data if called from interrupt context.
1582 */
1583 void
1584 rnd_add_uint32(struct krndsource *rs, uint32_t value)
1585 {
1586
1587 rnd_add_data(rs, &value, sizeof value, 0);
1588 }
1589
1590 void
1591 _rnd_add_uint32(struct krndsource *rs, uint32_t value)
1592 {
1593
1594 rnd_add_data(rs, &value, sizeof value, 0);
1595 }
1596
1597 void
1598 _rnd_add_uint64(struct krndsource *rs, uint64_t value)
1599 {
1600
1601 rnd_add_data(rs, &value, sizeof value, 0);
1602 }
1603
1604 /*
1605 * rnd_add_data(rs, buf, len, entropybits)
1606 *
1607 * Enter data from an entropy source into the pool, with a
1608 * driver's estimate of how much entropy the physical source of
1609 * the data has. If RND_FLAG_NO_ESTIMATE, we ignore the driver's
1610 * estimate and treat it as zero.
1611 *
1612 * If rs is NULL, may not be called from interrupt context.
1613 *
1614 * If rs is non-NULL, may be called from any context. May drop
1615 * data if called from interrupt context.
1616 */
1617 void
1618 rnd_add_data(struct krndsource *rs, const void *buf, uint32_t len,
1619 uint32_t entropybits)
1620 {
1621 uint32_t extra;
1622 uint32_t flags;
1623
1624 KASSERTMSG(howmany(entropybits, NBBY) <= len,
1625 "%s: impossible entropy rate:"
1626 " %"PRIu32" bits in %"PRIu32"-byte string",
1627 rs ? rs->name : "(anonymous)", entropybits, len);
1628
1629 /* If there's no rndsource, just enter the data and time now. */
1630 if (rs == NULL) {
1631 entropy_enter(buf, len, entropybits);
1632 extra = entropy_timer();
1633 entropy_enter(&extra, sizeof extra, 0);
1634 explicit_memset(&extra, 0, sizeof extra);
1635 return;
1636 }
1637
1638 /* Load a snapshot of the flags. Ioctl may change them under us. */
1639 flags = atomic_load_relaxed(&rs->flags);
1640
1641 /*
1642 * Skip if:
1643 * - we're not collecting entropy, or
1644 * - the operator doesn't want to collect entropy from this, or
1645 * - neither data nor timings are being collected from this.
1646 */
1647 if (!atomic_load_relaxed(&entropy_collection) ||
1648 ISSET(flags, RND_FLAG_NO_COLLECT) ||
1649 !ISSET(flags, RND_FLAG_COLLECT_VALUE|RND_FLAG_COLLECT_TIME))
1650 return;
1651
1652 /* If asked, ignore the estimate. */
1653 if (ISSET(flags, RND_FLAG_NO_ESTIMATE))
1654 entropybits = 0;
1655
1656 /* If we are collecting data, enter them. */
1657 if (ISSET(flags, RND_FLAG_COLLECT_VALUE))
1658 rnd_add_data_1(rs, buf, len, entropybits);
1659
1660 /* If we are collecting timings, enter one. */
1661 if (ISSET(flags, RND_FLAG_COLLECT_TIME)) {
1662 extra = entropy_timer();
1663 rnd_add_data_1(rs, &extra, sizeof extra, 0);
1664 }
1665 }
1666
1667 /*
1668 * rnd_add_data_1(rs, buf, len, entropybits)
1669 *
1670 * Internal subroutine to call either entropy_enter_intr, if we're
1671 * in interrupt context, or entropy_enter if not, and to count the
1672 * entropy in an rndsource.
1673 */
1674 static void
1675 rnd_add_data_1(struct krndsource *rs, const void *buf, uint32_t len,
1676 uint32_t entropybits)
1677 {
1678 bool fullyused;
1679
1680 /*
1681 * If we're in interrupt context, use entropy_enter_intr and
1682 * take note of whether it consumed the full sample; if not,
1683 * use entropy_enter, which always consumes the full sample.
1684 */
1685 if (curcpu_available() && cpu_intr_p()) {
1686 fullyused = entropy_enter_intr(buf, len, entropybits);
1687 } else {
1688 entropy_enter(buf, len, entropybits);
1689 fullyused = true;
1690 }
1691
1692 /*
1693 * If we used the full sample, note how many bits were
1694 * contributed from this source.
1695 */
1696 if (fullyused) {
1697 if (E->stage < ENTROPY_HOT) {
1698 if (E->stage >= ENTROPY_WARM)
1699 mutex_enter(&E->lock);
1700 rs->total += MIN(UINT_MAX - rs->total, entropybits);
1701 if (E->stage >= ENTROPY_WARM)
1702 mutex_exit(&E->lock);
1703 } else {
1704 struct rndsource_cpu *rc = percpu_getref(rs->state);
1705 unsigned nbits = rc->rc_nbits;
1706
1707 nbits += MIN(UINT_MAX - nbits, entropybits);
1708 atomic_store_relaxed(&rc->rc_nbits, nbits);
1709 percpu_putref(rs->state);
1710 }
1711 }
1712 }
1713
1714 /*
1715 * rnd_add_data_sync(rs, buf, len, entropybits)
1716 *
1717 * Same as rnd_add_data. Originally used in rndsource callbacks,
1718 * to break an unnecessary cycle; no longer really needed.
1719 */
1720 void
1721 rnd_add_data_sync(struct krndsource *rs, const void *buf, uint32_t len,
1722 uint32_t entropybits)
1723 {
1724
1725 rnd_add_data(rs, buf, len, entropybits);
1726 }
1727
1728 /*
1729 * rndsource_entropybits(rs)
1730 *
1731 * Return approximately the number of bits of entropy that have
1732 * been contributed via rs so far. Approximate if other CPUs may
1733 * be calling rnd_add_data concurrently.
1734 */
1735 static unsigned
1736 rndsource_entropybits(struct krndsource *rs)
1737 {
1738 unsigned nbits = rs->total;
1739
1740 KASSERT(E->stage >= ENTROPY_WARM);
1741 KASSERT(mutex_owned(&E->lock));
1742 percpu_foreach(rs->state, rndsource_entropybits_cpu, &nbits);
1743 return nbits;
1744 }
1745
1746 static void
1747 rndsource_entropybits_cpu(void *ptr, void *cookie, struct cpu_info *ci)
1748 {
1749 struct rndsource_cpu *rc = ptr;
1750 unsigned *nbitsp = cookie;
1751 unsigned cpu_nbits;
1752
1753 cpu_nbits = atomic_load_relaxed(&rc->rc_nbits);
1754 *nbitsp += MIN(UINT_MAX - *nbitsp, cpu_nbits);
1755 }
1756
1757 /*
1758 * rndsource_to_user(rs, urs)
1759 *
1760 * Copy a description of rs out to urs for userland.
1761 */
1762 static void
1763 rndsource_to_user(struct krndsource *rs, rndsource_t *urs)
1764 {
1765
1766 KASSERT(E->stage >= ENTROPY_WARM);
1767 KASSERT(mutex_owned(&E->lock));
1768
1769 /* Avoid kernel memory disclosure. */
1770 memset(urs, 0, sizeof(*urs));
1771
1772 CTASSERT(sizeof(urs->name) == sizeof(rs->name));
1773 strlcpy(urs->name, rs->name, sizeof(urs->name));
1774 urs->total = rndsource_entropybits(rs);
1775 urs->type = rs->type;
1776 urs->flags = atomic_load_relaxed(&rs->flags);
1777 }
1778
1779 /*
1780 * rndsource_to_user_est(rs, urse)
1781 *
1782 * Copy a description of rs and estimation statistics out to urse
1783 * for userland.
1784 */
1785 static void
1786 rndsource_to_user_est(struct krndsource *rs, rndsource_est_t *urse)
1787 {
1788
1789 KASSERT(E->stage >= ENTROPY_WARM);
1790 KASSERT(mutex_owned(&E->lock));
1791
1792 /* Avoid kernel memory disclosure. */
1793 memset(urse, 0, sizeof(*urse));
1794
1795 /* Copy out the rndsource description. */
1796 rndsource_to_user(rs, &urse->rt);
1797
1798 /* Zero out the statistics because we don't do estimation. */
1799 urse->dt_samples = 0;
1800 urse->dt_total = 0;
1801 urse->dv_samples = 0;
1802 urse->dv_total = 0;
1803 }
1804
1805 /*
1806 * entropy_ioctl(cmd, data)
1807 *
1808 * Handle various /dev/random ioctl queries.
1809 */
1810 int
1811 entropy_ioctl(unsigned long cmd, void *data)
1812 {
1813 struct krndsource *rs;
1814 bool privileged;
1815 int error;
1816
1817 KASSERT(E->stage >= ENTROPY_WARM);
1818
1819 /* Verify user's authorization to perform the ioctl. */
1820 switch (cmd) {
1821 case RNDGETENTCNT:
1822 case RNDGETPOOLSTAT:
1823 case RNDGETSRCNUM:
1824 case RNDGETSRCNAME:
1825 case RNDGETESTNUM:
1826 case RNDGETESTNAME:
1827 error = kauth_authorize_device(curlwp->l_cred,
1828 KAUTH_DEVICE_RND_GETPRIV, NULL, NULL, NULL, NULL);
1829 break;
1830 case RNDCTL:
1831 error = kauth_authorize_device(curlwp->l_cred,
1832 KAUTH_DEVICE_RND_SETPRIV, NULL, NULL, NULL, NULL);
1833 break;
1834 case RNDADDDATA:
1835 error = kauth_authorize_device(curlwp->l_cred,
1836 KAUTH_DEVICE_RND_ADDDATA, NULL, NULL, NULL, NULL);
1837 /* Ascertain whether the user's inputs should be counted. */
1838 if (kauth_authorize_device(curlwp->l_cred,
1839 KAUTH_DEVICE_RND_ADDDATA_ESTIMATE,
1840 NULL, NULL, NULL, NULL) == 0)
1841 privileged = true;
1842 break;
1843 default: {
1844 /*
1845 * XXX Hack to avoid changing module ABI so this can be
1846 * pulled up. Later, we can just remove the argument.
1847 */
1848 static const struct fileops fops = {
1849 .fo_ioctl = rnd_system_ioctl,
1850 };
1851 struct file f = {
1852 .f_ops = &fops,
1853 };
1854 MODULE_HOOK_CALL(rnd_ioctl_50_hook, (&f, cmd, data),
1855 enosys(), error);
1856 #if defined(_LP64)
1857 if (error == ENOSYS)
1858 MODULE_HOOK_CALL(rnd_ioctl32_50_hook, (&f, cmd, data),
1859 enosys(), error);
1860 #endif
1861 if (error == ENOSYS)
1862 error = ENOTTY;
1863 break;
1864 }
1865 }
1866
1867 /* If anything went wrong with authorization, stop here. */
1868 if (error)
1869 return error;
1870
1871 /* Dispatch on the command. */
1872 switch (cmd) {
1873 case RNDGETENTCNT: { /* Get current entropy count in bits. */
1874 uint32_t *countp = data;
1875
1876 mutex_enter(&E->lock);
1877 *countp = ENTROPY_CAPACITY*NBBY - E->needed;
1878 mutex_exit(&E->lock);
1879
1880 break;
1881 }
1882 case RNDGETPOOLSTAT: { /* Get entropy pool statistics. */
1883 rndpoolstat_t *pstat = data;
1884
1885 mutex_enter(&E->lock);
1886
1887 /* parameters */
1888 pstat->poolsize = ENTPOOL_SIZE/sizeof(uint32_t); /* words */
1889 pstat->threshold = ENTROPY_CAPACITY*1; /* bytes */
1890 pstat->maxentropy = ENTROPY_CAPACITY*NBBY; /* bits */
1891
1892 /* state */
1893 pstat->added = 0; /* XXX total entropy_enter count */
1894 pstat->curentropy = ENTROPY_CAPACITY*NBBY - E->needed;
1895 pstat->removed = 0; /* XXX total entropy_extract count */
1896 pstat->discarded = 0; /* XXX bits of entropy beyond capacity */
1897 pstat->generated = 0; /* XXX bits of data...fabricated? */
1898
1899 mutex_exit(&E->lock);
1900 break;
1901 }
1902 case RNDGETSRCNUM: { /* Get entropy sources by number. */
1903 rndstat_t *stat = data;
1904 uint32_t start = 0, i = 0;
1905
1906 /* Skip if none requested; fail if too many requested. */
1907 if (stat->count == 0)
1908 break;
1909 if (stat->count > RND_MAXSTATCOUNT)
1910 return EINVAL;
1911
1912 /*
1913 * Under the lock, find the first one, copy out as many
1914 * as requested, and report how many we copied out.
1915 */
1916 mutex_enter(&E->lock);
1917 LIST_FOREACH(rs, &E->sources, list) {
1918 if (start++ == stat->start)
1919 break;
1920 }
1921 while (i < stat->count && rs != NULL) {
1922 rndsource_to_user(rs, &stat->source[i++]);
1923 rs = LIST_NEXT(rs, list);
1924 }
1925 KASSERT(i <= stat->count);
1926 stat->count = i;
1927 mutex_exit(&E->lock);
1928 break;
1929 }
1930 case RNDGETESTNUM: { /* Get sources and estimates by number. */
1931 rndstat_est_t *estat = data;
1932 uint32_t start = 0, i = 0;
1933
1934 /* Skip if none requested; fail if too many requested. */
1935 if (estat->count == 0)
1936 break;
1937 if (estat->count > RND_MAXSTATCOUNT)
1938 return EINVAL;
1939
1940 /*
1941 * Under the lock, find the first one, copy out as many
1942 * as requested, and report how many we copied out.
1943 */
1944 mutex_enter(&E->lock);
1945 LIST_FOREACH(rs, &E->sources, list) {
1946 if (start++ == estat->start)
1947 break;
1948 }
1949 while (i < estat->count && rs != NULL) {
1950 rndsource_to_user_est(rs, &estat->source[i++]);
1951 rs = LIST_NEXT(rs, list);
1952 }
1953 KASSERT(i <= estat->count);
1954 estat->count = i;
1955 mutex_exit(&E->lock);
1956 break;
1957 }
1958 case RNDGETSRCNAME: { /* Get entropy sources by name. */
1959 rndstat_name_t *nstat = data;
1960 const size_t n = sizeof(rs->name);
1961
1962 CTASSERT(sizeof(rs->name) == sizeof(nstat->name));
1963
1964 /*
1965 * Under the lock, search by name. If found, copy it
1966 * out; if not found, fail with ENOENT.
1967 */
1968 mutex_enter(&E->lock);
1969 LIST_FOREACH(rs, &E->sources, list) {
1970 if (strncmp(rs->name, nstat->name, n) == 0)
1971 break;
1972 }
1973 if (rs != NULL)
1974 rndsource_to_user(rs, &nstat->source);
1975 else
1976 error = ENOENT;
1977 mutex_exit(&E->lock);
1978 break;
1979 }
1980 case RNDGETESTNAME: { /* Get sources and estimates by name. */
1981 rndstat_est_name_t *enstat = data;
1982 const size_t n = sizeof(rs->name);
1983
1984 CTASSERT(sizeof(rs->name) == sizeof(enstat->name));
1985
1986 /*
1987 * Under the lock, search by name. If found, copy it
1988 * out; if not found, fail with ENOENT.
1989 */
1990 mutex_enter(&E->lock);
1991 LIST_FOREACH(rs, &E->sources, list) {
1992 if (strncmp(rs->name, enstat->name, n) == 0)
1993 break;
1994 }
1995 if (rs != NULL)
1996 rndsource_to_user_est(rs, &enstat->source);
1997 else
1998 error = ENOENT;
1999 mutex_exit(&E->lock);
2000 break;
2001 }
2002 case RNDCTL: { /* Modify entropy source flags. */
2003 rndctl_t *rndctl = data;
2004 const size_t n = sizeof(rs->name);
2005 uint32_t flags;
2006
2007 CTASSERT(sizeof(rs->name) == sizeof(rndctl->name));
2008
2009 /* Whitelist the flags that user can change. */
2010 rndctl->mask &= RND_FLAG_NO_ESTIMATE|RND_FLAG_NO_COLLECT;
2011
2012 /*
2013 * For each matching rndsource, either by type if
2014 * specified or by name if not, set the masked flags.
2015 */
2016 mutex_enter(&E->lock);
2017 LIST_FOREACH(rs, &E->sources, list) {
2018 if (rndctl->type != 0xff) {
2019 if (rs->type != rndctl->type)
2020 continue;
2021 } else {
2022 if (strncmp(rs->name, rndctl->name, n) != 0)
2023 continue;
2024 }
2025 flags = rs->flags & ~rndctl->mask;
2026 flags |= rndctl->flags & rndctl->mask;
2027 atomic_store_relaxed(&rs->flags, flags);
2028 }
2029 mutex_exit(&E->lock);
2030 break;
2031 }
2032 case RNDADDDATA: { /* Enter seed into entropy pool. */
2033 rnddata_t *rdata = data;
2034 unsigned entropybits = 0;
2035
2036 if (!atomic_load_relaxed(&entropy_collection))
2037 break; /* thanks but no thanks */
2038 if (rdata->len > MIN(sizeof(rdata->data), UINT32_MAX/NBBY))
2039 return EINVAL;
2040
2041 /*
2042 * This ioctl serves as the userland alternative a
2043 * bootloader-provided seed -- typically furnished by
2044 * /etc/rc.d/random_seed. We accept the user's entropy
2045 * claim only if
2046 *
2047 * (a) the user is privileged, and
2048 * (b) we have not entered a bootloader seed.
2049 *
2050 * under the assumption that the user may use this to
2051 * load a seed from disk that we have already loaded
2052 * from the bootloader, so we don't double-count it.
2053 */
2054 if (privileged) {
2055 mutex_enter(&E->lock);
2056 if (!E->seeded) {
2057 entropybits = MIN(rdata->entropy,
2058 MIN(rdata->len, ENTROPY_CAPACITY)*NBBY);
2059 E->seeded = true;
2060 }
2061 mutex_exit(&E->lock);
2062 }
2063
2064 /* Enter the data. */
2065 rnd_add_data(&seed_rndsource, rdata->data, rdata->len,
2066 entropybits);
2067 break;
2068 }
2069 default:
2070 error = ENOTTY;
2071 }
2072
2073 /* Return any error that may have come up. */
2074 return error;
2075 }
2076
2077 /* Legacy entry points */
2078
2079 void
2080 rnd_seed(void *seed, size_t len)
2081 {
2082
2083 if (len != sizeof(rndsave_t)) {
2084 printf("entropy: invalid seed length: %zu,"
2085 " expected sizeof(rndsave_t) = %zu\n",
2086 len, sizeof(rndsave_t));
2087 return;
2088 }
2089 entropy_seed(seed);
2090 }
2091
2092 void
2093 rnd_init(void)
2094 {
2095
2096 entropy_init();
2097 }
2098
2099 void
2100 rnd_init_softint(void)
2101 {
2102
2103 entropy_init_late();
2104 }
2105
2106 int
2107 rnd_system_ioctl(struct file *fp, unsigned long cmd, void *data)
2108 {
2109
2110 return entropy_ioctl(cmd, data);
2111 }
2112