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