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