diff --git a/sys/dev/random/fenestrasX/fx_pool.c b/sys/dev/random/fenestrasX/fx_pool.c index 3aefe17a045a..35d06c2a9df1 100644 --- a/sys/dev/random/fenestrasX/fx_pool.c +++ b/sys/dev/random/fenestrasX/fx_pool.c @@ -1,629 +1,629 @@ /*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2019 Conrad Meyer * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * Timer-based reseed interval growth factor and limit in seconds. (§ 3.2) */ #define FXENT_RESSED_INTVL_GFACT 3 #define FXENT_RESEED_INTVL_MAX 3600 /* * Pool reseed schedule. Initially, only pool 0 is active. Until the timer * interval reaches INTVL_MAX, only pool 0 is used. * * After reaching INTVL_MAX, pool k is either activated (if inactive) or used * (if active) every 3^k timer reseeds. (§ 3.3) * * (Entropy harvesting only round robins across active pools.) */ #define FXENT_RESEED_BASE 3 /* * Number of bytes from high quality sources to allocate to pool 0 before * normal round-robin allocation after each timer reseed. (§ 3.4) */ #define FXENT_HI_SRC_POOL0_BYTES 32 /* * § 3.1 * * Low sources provide unconditioned entropy, such as mouse movements; high * sources are assumed to provide high-quality random bytes. Pull sources are * those which can be polled, i.e., anything randomdev calls a "random_source." * * In the whitepaper, low sources are pull. For us, at least in the existing * design, low-quality sources push into some global ring buffer and then get * forwarded into the RNG by a thread that continually polls. Presumably their * design batches low entopy signals in some way (SHA512?) and only requests * them dynamically on reseed. I'm not sure what the benefit is vs feeding * into the pools directly. */ enum fxrng_ent_access_cls { FXRNG_PUSH, FXRNG_PULL, }; enum fxrng_ent_source_cls { FXRNG_HI, FXRNG_LO, FXRNG_GARBAGE, }; struct fxrng_ent_cls { enum fxrng_ent_access_cls entc_axx_cls; enum fxrng_ent_source_cls entc_src_cls; }; static const struct fxrng_ent_cls fxrng_hi_pull = { .entc_axx_cls = FXRNG_PULL, .entc_src_cls = FXRNG_HI, }; static const struct fxrng_ent_cls fxrng_hi_push = { .entc_axx_cls = FXRNG_PUSH, .entc_src_cls = FXRNG_HI, }; static const struct fxrng_ent_cls fxrng_lo_push = { .entc_axx_cls = FXRNG_PUSH, .entc_src_cls = FXRNG_LO, }; static const struct fxrng_ent_cls fxrng_garbage = { .entc_axx_cls = FXRNG_PUSH, .entc_src_cls = FXRNG_GARBAGE, }; /* * This table is a mapping of randomdev's current source abstractions to the * designations above; at some point, if the design seems reasonable, it would * make more sense to pull this up into the abstraction layer instead. */ static const struct fxrng_ent_char { const struct fxrng_ent_cls *entc_cls; } fxrng_ent_char[/*ENTROPYSOURCE*/] = { [RANDOM_CACHED] = { .entc_cls = &fxrng_hi_push, }, [RANDOM_ATTACH] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_KEYBOARD] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_MOUSE] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_NET_TUN] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_NET_ETHER] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_NET_NG] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_INTERRUPT] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_SWI] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_FS_ATIME] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_UMA] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_CALLOUT] = { .entc_cls = &fxrng_lo_push, }, [RANDOM_RANDOMDEV] = { .entc_cls = &fxrng_lo_push, }, - [RANDOM_PURE_SAFE] = { - .entc_cls = &fxrng_hi_push, - }, - [RANDOM_PURE_GLXSB] = { - .entc_cls = &fxrng_hi_push, - }, - [RANDOM_PURE_HIFN] = { + [RANDOM_PURE_TPM] = { .entc_cls = &fxrng_hi_push, }, [RANDOM_PURE_RDRAND] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_RDSEED] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_NEHEMIAH] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_RNDTEST] = { .entc_cls = &fxrng_garbage, }, [RANDOM_PURE_VIRTIO] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_BROADCOM] = { .entc_cls = &fxrng_hi_push, }, [RANDOM_PURE_CCP] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_DARN] = { .entc_cls = &fxrng_hi_pull, }, - [RANDOM_PURE_TPM] = { - .entc_cls = &fxrng_hi_push, - }, [RANDOM_PURE_VMGENID] = { .entc_cls = &fxrng_hi_push, }, [RANDOM_PURE_QUALCOMM] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_ARMV8] = { .entc_cls = &fxrng_hi_pull, }, [RANDOM_PURE_ARM_TRNG] = { .entc_cls = &fxrng_hi_pull, }, + [RANDOM_PURE_SAFE] = { + .entc_cls = &fxrng_hi_push, + }, + [RANDOM_PURE_GLXSB] = { + .entc_cls = &fxrng_hi_push, + }, + [RANDOM_PURE_HIFN] = { + .entc_cls = &fxrng_hi_push, + }, }; CTASSERT(nitems(fxrng_ent_char) == ENTROPYSOURCE); /* Useful for single-bit-per-source state. */ BITSET_DEFINE(fxrng_bits, ENTROPYSOURCE); /* XXX Borrowed from not-yet-committed D22702. */ #ifndef BIT_TEST_SET_ATOMIC_ACQ #define BIT_TEST_SET_ATOMIC_ACQ(_s, n, p) \ (atomic_testandset_acq_long( \ &(p)->__bits[__bitset_word((_s), (n))], (n)) != 0) #endif #define FXENT_TEST_SET_ATOMIC_ACQ(n, p) \ BIT_TEST_SET_ATOMIC_ACQ(ENTROPYSOURCE, n, p) /* For special behavior on first-time entropy sources. (§ 3.1) */ static struct fxrng_bits __read_mostly fxrng_seen; /* For special behavior for high-entropy sources after a reseed. (§ 3.4) */ _Static_assert(FXENT_HI_SRC_POOL0_BYTES <= UINT8_MAX, ""); static uint8_t __read_mostly fxrng_reseed_seen[ENTROPYSOURCE]; /* Entropy pools. Lock order is ENT -> RNG(root) -> RNG(leaf). */ static struct mtx fxent_pool_lk; MTX_SYSINIT(fx_pool, &fxent_pool_lk, "fx entropy pool lock", MTX_DEF); #define FXENT_LOCK() mtx_lock(&fxent_pool_lk) #define FXENT_UNLOCK() mtx_unlock(&fxent_pool_lk) #define FXENT_ASSERT(rng) mtx_assert(&fxent_pool_lk, MA_OWNED) #define FXENT_ASSERT_NOT(rng) mtx_assert(&fxent_pool_lk, MA_NOTOWNED) static struct fxrng_hash fxent_pool[FXRNG_NPOOLS]; static unsigned __read_mostly fxent_nactpools = 1; static struct timeout_task fxent_reseed_timer; static int __read_mostly fxent_timer_ready; /* * Track number of bytes of entropy harvested from high-quality sources prior * to initial keying. The idea is to collect more jitter entropy when fewer * high-quality bytes were available and less if we had other good sources. We * want to provide always-on availability but don't necessarily have *any* * great sources on some platforms. * * Like fxrng_ent_char: at some point, if the design seems reasonable, it would * make more sense to pull this up into the abstraction layer instead. * * Jitter entropy is unimplemented for now. */ static unsigned long fxrng_preseed_ent; void fxrng_pools_init(void) { size_t i; for (i = 0; i < nitems(fxent_pool); i++) fxrng_hash_init(&fxent_pool[i]); } static inline bool fxrng_hi_source(enum random_entropy_source src) { return (fxrng_ent_char[src].entc_cls->entc_src_cls == FXRNG_HI); } /* * A racy check that this high-entropy source's event should contribute to * pool0 on the basis of per-source byte count. The check is racy for two * reasons: * - Performance: The vast majority of the time, we've already taken 32 bytes * from any present high quality source and the racy check lets us avoid * dirtying the cache for the global array. * - Correctness: It's fine that the check is racy. The failure modes are: * • False positive: We will detect when we take the lock. * • False negative: We still collect the entropy; it just won't be * preferentially placed in pool0 in this case. */ static inline bool fxrng_hi_pool0_eligible_racy(enum random_entropy_source src) { return (atomic_load_acq_8(&fxrng_reseed_seen[src]) < FXENT_HI_SRC_POOL0_BYTES); } /* * Top level entropy processing API from randomdev. * * Invoked by the core randomdev subsystem both for preload entropy, "push" * sources (like interrupts, keyboard, etc) and pull sources (RDRAND, etc). */ void fxrng_event_processor(struct harvest_event *event) { enum random_entropy_source src; unsigned pool; bool first_time, first_32; src = event->he_source; ASSERT_DEBUG(event->he_size <= sizeof(event->he_entropy), "%s: he_size: %u > sizeof(he_entropy): %zu", __func__, (unsigned)event->he_size, sizeof(event->he_entropy)); /* * Zero bytes of source entropy doesn't count as observing this source * for the first time. We still harvest the counter entropy. */ first_time = event->he_size > 0 && !FXENT_TEST_SET_ATOMIC_ACQ(src, &fxrng_seen); if (__predict_false(first_time)) { /* * "The first time [any source] provides entropy, it is used to * directly reseed the root PRNG. The entropy pools are * bypassed." (§ 3.1) * * Unlike Windows, we cannot rely on loader(8) seed material * being present, so we perform initial keying in the kernel. * We use brng_generation 0 to represent an unkeyed state. * * Prior to initial keying, it doesn't make sense to try to mix * the entropy directly with the root PRNG state, as the root * PRNG is unkeyed. Instead, we collect pre-keying dynamic * entropy in pool0 and do not bump the root PRNG seed version * or set its key. Initial keying will incorporate pool0 and * bump the brng_generation (seed version). * * After initial keying, we do directly mix in first-time * entropy sources. We use the root BRNG to generate 32 bytes * and use fxrng_hash to mix it with the new entropy source and * re-key with the first 256 bits of hash output. */ FXENT_LOCK(); FXRNG_BRNG_LOCK(&fxrng_root); if (__predict_true(fxrng_root.brng_generation > 0)) { /* Bypass the pools: */ FXENT_UNLOCK(); fxrng_brng_src_reseed(event); FXRNG_BRNG_ASSERT_NOT(&fxrng_root); return; } /* * Keying the root PRNG requires both FXENT_LOCK and the PRNG's * lock, so we only need to hold on to the pool lock to prevent * initial keying without this entropy. */ FXRNG_BRNG_UNLOCK(&fxrng_root); /* Root PRNG hasn't been keyed yet, just accumulate event. */ fxrng_hash_update(&fxent_pool[0], &event->he_somecounter, sizeof(event->he_somecounter)); fxrng_hash_update(&fxent_pool[0], event->he_entropy, event->he_size); if (fxrng_hi_source(src)) { /* Prevent overflow. */ if (fxrng_preseed_ent <= ULONG_MAX - event->he_size) fxrng_preseed_ent += event->he_size; } FXENT_UNLOCK(); return; } /* !first_time */ /* * "The first 32 bytes produced by a high entropy source after a reseed * from the pools is always put in pool 0." (§ 3.4) * * The first-32-byte tracking data in fxrng_reseed_seen is reset in * fxent_timer_reseed_npools() below. */ first_32 = event->he_size > 0 && fxrng_hi_source(src) && atomic_load_acq_int(&fxent_nactpools) > 1 && fxrng_hi_pool0_eligible_racy(src); if (__predict_false(first_32)) { unsigned rem, seen; FXENT_LOCK(); seen = fxrng_reseed_seen[src]; if (seen == FXENT_HI_SRC_POOL0_BYTES) goto round_robin; rem = FXENT_HI_SRC_POOL0_BYTES - seen; rem = MIN(rem, event->he_size); fxrng_reseed_seen[src] = seen + rem; /* * We put 'rem' bytes in pool0, and any remaining bytes are * round-robin'd across other pools. */ fxrng_hash_update(&fxent_pool[0], ((uint8_t *)event->he_entropy) + event->he_size - rem, rem); if (rem == event->he_size) { fxrng_hash_update(&fxent_pool[0], &event->he_somecounter, sizeof(event->he_somecounter)); FXENT_UNLOCK(); return; } /* * If fewer bytes were needed than this even provied, We only * take the last rem bytes of the entropy buffer and leave the * timecounter to be round-robin'd with the remaining entropy. */ event->he_size -= rem; goto round_robin; } /* !first_32 */ FXENT_LOCK(); round_robin: FXENT_ASSERT(); pool = event->he_destination % fxent_nactpools; fxrng_hash_update(&fxent_pool[pool], event->he_entropy, event->he_size); fxrng_hash_update(&fxent_pool[pool], &event->he_somecounter, sizeof(event->he_somecounter)); if (__predict_false(fxrng_hi_source(src) && atomic_load_acq_64(&fxrng_root_generation) == 0)) { /* Prevent overflow. */ if (fxrng_preseed_ent <= ULONG_MAX - event->he_size) fxrng_preseed_ent += event->he_size; } FXENT_UNLOCK(); } /* * Top level "seeded" API/signal from randomdev. * * This is our warning that a request is coming: we need to be seeded. In * fenestrasX, a request for random bytes _never_ fails. "We (ed: ditto) have * observed that there are many callers that never check for the error code, * even if they are generating cryptographic key material." (§ 1.6) * * If we returned 'false', both read_random(9) and chacha20_randomstir() * (arc4random(9)) will blindly charge on with something almost certainly worse * than what we've got, or are able to get quickly enough. */ bool fxrng_alg_seeded(void) { uint8_t hash[FXRNG_HASH_SZ]; sbintime_t sbt; /* The vast majority of the time, we expect to already be seeded. */ if (__predict_true(atomic_load_acq_64(&fxrng_root_generation) != 0)) return (true); /* * Take the lock and recheck; only one thread needs to do the initial * seeding work. */ FXENT_LOCK(); if (atomic_load_acq_64(&fxrng_root_generation) != 0) { FXENT_UNLOCK(); return (true); } /* XXX Any one-off initial seeding goes here. */ fxrng_hash_finish(&fxent_pool[0], hash, sizeof(hash)); fxrng_hash_init(&fxent_pool[0]); fxrng_brng_reseed(hash, sizeof(hash)); FXENT_UNLOCK(); randomdev_unblock(); explicit_bzero(hash, sizeof(hash)); /* * This may be called too early for taskqueue_thread to be initialized. * fxent_pool_timer_init will detect if we've already unblocked and * queue the first timer reseed at that point. */ if (atomic_load_acq_int(&fxent_timer_ready) != 0) { sbt = SBT_1S; taskqueue_enqueue_timeout_sbt(taskqueue_thread, &fxent_reseed_timer, -sbt, (sbt / 3), C_PREL(2)); } return (true); } /* * Timer-based reseeds and pool expansion. */ static void fxent_timer_reseed_npools(unsigned n) { /* * 64 * 8 => moderately large 512 bytes. Could be static, as we are * only used in a static context. On the other hand, this is in * threadqueue TASK context and we're likely nearly at top of stack * already. */ uint8_t hash[FXRNG_HASH_SZ * FXRNG_NPOOLS]; unsigned i; ASSERT_DEBUG(n > 0 && n <= FXRNG_NPOOLS, "n:%u", n); FXENT_ASSERT(); /* * Collect entropy from pools 0..n-1 by concatenating the output hashes * and then feeding them into fxrng_brng_reseed, which will hash the * aggregate together with the current root PRNG keystate to produce a * new key. It will also bump the global generation counter * appropriately. */ for (i = 0; i < n; i++) { fxrng_hash_finish(&fxent_pool[i], hash + i * FXRNG_HASH_SZ, FXRNG_HASH_SZ); fxrng_hash_init(&fxent_pool[i]); } fxrng_brng_reseed(hash, n * FXRNG_HASH_SZ); explicit_bzero(hash, n * FXRNG_HASH_SZ); /* * "The first 32 bytes produced by a high entropy source after a reseed * from the pools is always put in pool 0." (§ 3.4) * * So here we reset the tracking (somewhat naively given the majority * of sources on most machines are not what we consider "high", but at * 32 bytes it's smaller than a cache line), so the next 32 bytes are * prioritized into pool0. * * See corresponding use of fxrng_reseed_seen in fxrng_event_processor. */ memset(fxrng_reseed_seen, 0, sizeof(fxrng_reseed_seen)); FXENT_ASSERT(); } static void fxent_timer_reseed(void *ctx __unused, int pending __unused) { static unsigned reseed_intvl_sec = 1; /* Only reseeds after FXENT_RESEED_INTVL_MAX is achieved. */ static uint64_t reseed_number = 1; unsigned next_ival, i, k; sbintime_t sbt; if (reseed_intvl_sec < FXENT_RESEED_INTVL_MAX) { next_ival = FXENT_RESSED_INTVL_GFACT * reseed_intvl_sec; if (next_ival > FXENT_RESEED_INTVL_MAX) next_ival = FXENT_RESEED_INTVL_MAX; FXENT_LOCK(); fxent_timer_reseed_npools(1); FXENT_UNLOCK(); } else { /* * The creation of entropy pools beyond 0 is enabled when the * reseed interval hits the maximum. (§ 3.3) */ next_ival = reseed_intvl_sec; /* * Pool 0 is used every reseed; pool 1..0 every 3rd reseed; and in * general, pool n..0 every 3^n reseeds. */ k = reseed_number; reseed_number++; /* Count how many pools, from [0, i), to use for reseed. */ for (i = 1; i < MIN(fxent_nactpools + 1, FXRNG_NPOOLS); i++) { if ((k % FXENT_RESEED_BASE) != 0) break; k /= FXENT_RESEED_BASE; } /* * If we haven't activated pool i yet, activate it and only * reseed from [0, i-1). (§ 3.3) */ FXENT_LOCK(); if (i == fxent_nactpools + 1) { fxent_timer_reseed_npools(fxent_nactpools); fxent_nactpools++; } else { /* Just reseed from [0, i). */ fxent_timer_reseed_npools(i); } FXENT_UNLOCK(); } /* Schedule the next reseed. */ sbt = next_ival * SBT_1S; taskqueue_enqueue_timeout_sbt(taskqueue_thread, &fxent_reseed_timer, -sbt, (sbt / 3), C_PREL(2)); reseed_intvl_sec = next_ival; } static void fxent_pool_timer_init(void *dummy __unused) { sbintime_t sbt; TIMEOUT_TASK_INIT(taskqueue_thread, &fxent_reseed_timer, 0, fxent_timer_reseed, NULL); if (atomic_load_acq_64(&fxrng_root_generation) != 0) { sbt = SBT_1S; taskqueue_enqueue_timeout_sbt(taskqueue_thread, &fxent_reseed_timer, -sbt, (sbt / 3), C_PREL(2)); } atomic_store_rel_int(&fxent_timer_ready, 1); } /* After taskqueue_thread is initialized in SI_SUB_TASKQ:SI_ORDER_SECOND. */ SYSINIT(fxent_pool_timer_init, SI_SUB_TASKQ, SI_ORDER_ANY, fxent_pool_timer_init, NULL); diff --git a/sys/dev/random/random_harvestq.c b/sys/dev/random/random_harvestq.c index f2206044fe7d..0e90b4d6ef9b 100644 --- a/sys/dev/random/random_harvestq.c +++ b/sys/dev/random/random_harvestq.c @@ -1,985 +1,985 @@ /*- * Copyright (c) 2017 Oliver Pinter * Copyright (c) 2017 W. Dean Freeman * Copyright (c) 2000-2015 Mark R V Murray * Copyright (c) 2013 Arthur Mesh * Copyright (c) 2004 Robert N. M. Watson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(RANDOM_ENABLE_ETHER) #define _RANDOM_HARVEST_ETHER_OFF 0 #else #define _RANDOM_HARVEST_ETHER_OFF (1u << RANDOM_NET_ETHER) #endif #if defined(RANDOM_ENABLE_UMA) #define _RANDOM_HARVEST_UMA_OFF 0 #else #define _RANDOM_HARVEST_UMA_OFF (1u << RANDOM_UMA) #endif /* * Note that random_sources_feed() will also use this to try and split up * entropy into a subset of pools per iteration with the goal of feeding * HARVESTSIZE into every pool at least once per second. */ #define RANDOM_KTHREAD_HZ 10 static void random_kthread(void); static void random_sources_feed(void); /* * Random must initialize much earlier than epoch, but we can initialize the * epoch code before SMP starts. Prior to SMP, we can safely bypass * concurrency primitives. */ static __read_mostly bool epoch_inited; static __read_mostly epoch_t rs_epoch; static const char *random_source_descr[]; /* * How many events to queue up. We create this many items in * an 'empty' queue, then transfer them to the 'harvest' queue with * supplied junk. When used, they are transferred back to the * 'empty' queue. */ #define RANDOM_RING_MAX 1024 #define RANDOM_ACCUM_MAX 8 /* 1 to let the kernel thread run, 0 to terminate, -1 to mark completion */ volatile int random_kthread_control; /* * Allow the sysadmin to select the broad category of entropy types to harvest. * * Updates are synchronized by the harvest mutex. */ __read_frequently u_int hc_source_mask; CTASSERT(ENTROPYSOURCE <= sizeof(hc_source_mask) * NBBY); struct random_sources { CK_LIST_ENTRY(random_sources) rrs_entries; const struct random_source *rrs_source; }; static CK_LIST_HEAD(sources_head, random_sources) source_list = CK_LIST_HEAD_INITIALIZER(source_list); SYSCTL_NODE(_kern_random, OID_AUTO, harvest, CTLFLAG_RW | CTLFLAG_MPSAFE, 0, "Entropy Device Parameters"); /* * Put all the harvest queue context stuff in one place. * this make is a bit easier to lock and protect. */ static struct harvest_context { /* The harvest mutex protects all of harvest_context and * the related data. */ struct mtx hc_mtx; /* Round-robin destination cache. */ u_int hc_destination[ENTROPYSOURCE]; /* The context of the kernel thread processing harvested entropy */ struct proc *hc_kthread_proc; /* * A pair of buffers for queued events. New events are added to the * active queue while the kthread processes the other one in parallel. */ struct entropy_buffer { struct harvest_event ring[RANDOM_RING_MAX]; u_int pos; } hc_entropy_buf[2]; u_int hc_active_buf; struct fast_entropy_accumulator { volatile u_int pos; uint32_t buf[RANDOM_ACCUM_MAX]; } hc_entropy_fast_accumulator; } harvest_context; #define RANDOM_HARVEST_INIT_LOCK() mtx_init(&harvest_context.hc_mtx, \ "entropy harvest mutex", NULL, MTX_SPIN) #define RANDOM_HARVEST_LOCK() mtx_lock_spin(&harvest_context.hc_mtx) #define RANDOM_HARVEST_UNLOCK() mtx_unlock_spin(&harvest_context.hc_mtx) static struct kproc_desc random_proc_kp = { "rand_harvestq", random_kthread, &harvest_context.hc_kthread_proc, }; /* Pass the given event straight through to Fortuna/Whatever. */ static __inline void random_harvestq_fast_process_event(struct harvest_event *event) { p_random_alg_context->ra_event_processor(event); explicit_bzero(event, sizeof(*event)); } static void random_kthread(void) { struct harvest_context *hc; hc = &harvest_context; for (random_kthread_control = 1; random_kthread_control;) { struct entropy_buffer *buf; u_int entries; /* Deal with queued events. */ RANDOM_HARVEST_LOCK(); buf = &hc->hc_entropy_buf[hc->hc_active_buf]; entries = buf->pos; buf->pos = 0; hc->hc_active_buf = (hc->hc_active_buf + 1) % nitems(hc->hc_entropy_buf); RANDOM_HARVEST_UNLOCK(); for (u_int i = 0; i < entries; i++) random_harvestq_fast_process_event(&buf->ring[i]); /* Poll sources of noise. */ random_sources_feed(); /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */ for (u_int i = 0; i < RANDOM_ACCUM_MAX; i++) { if (hc->hc_entropy_fast_accumulator.buf[i]) { random_harvest_direct(&hc->hc_entropy_fast_accumulator.buf[i], sizeof(hc->hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA); hc->hc_entropy_fast_accumulator.buf[i] = 0; } } /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */ tsleep_sbt(&hc->hc_kthread_proc, 0, "-", SBT_1S/RANDOM_KTHREAD_HZ, 0, C_PREL(1)); } random_kthread_control = -1; wakeup(&hc->hc_kthread_proc); kproc_exit(0); /* NOTREACHED */ } SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start, &random_proc_kp); _Static_assert(SI_SUB_KICK_SCHEDULER > SI_SUB_RANDOM, "random kthread starting before subsystem initialization"); static void rs_epoch_init(void *dummy __unused) { rs_epoch = epoch_alloc("Random Sources", EPOCH_PREEMPT); epoch_inited = true; } SYSINIT(rs_epoch_init, SI_SUB_EPOCH, SI_ORDER_ANY, rs_epoch_init, NULL); /* * Run through all fast sources reading entropy for the given * number of rounds, which should be a multiple of the number * of entropy accumulation pools in use; it is 32 for Fortuna. */ static void random_sources_feed(void) { uint32_t entropy[HARVESTSIZE]; struct epoch_tracker et; struct random_sources *rrs; u_int i, n, npools; bool rse_warm; rse_warm = epoch_inited; /* * Evenly-ish distribute pool population across the second based on how * frequently random_kthread iterates. * * For Fortuna, the math currently works out as such: * * 64 bits * 4 pools = 256 bits per iteration * 256 bits * 10 Hz = 2560 bits per second, 320 B/s * */ npools = howmany(p_random_alg_context->ra_poolcount, RANDOM_KTHREAD_HZ); /*- * If we're not seeded yet, attempt to perform a "full seed", filling * all of the PRNG's pools with entropy; if there is enough entropy * available from "fast" entropy sources this will allow us to finish * seeding and unblock the boot process immediately rather than being * stuck for a few seconds with random_kthread gradually collecting a * small chunk of entropy every 1 / RANDOM_KTHREAD_HZ seconds. * * We collect RANDOM_FORTUNA_DEFPOOLSIZE bytes per pool, i.e. enough * to fill Fortuna's pools in the default configuration. With another * PRNG or smaller pools for Fortuna, we might collect more entropy * than needed to fill the pools, but this is harmless; alternatively, * a different PRNG, larger pools, or fast entropy sources which are * not able to provide as much entropy as we request may result in the * not being fully seeded (and thus remaining blocked) but in that * case we will return here after 1 / RANDOM_KTHREAD_HZ seconds and * try again for a large amount of entropy. */ if (!p_random_alg_context->ra_seeded()) npools = howmany(p_random_alg_context->ra_poolcount * RANDOM_FORTUNA_DEFPOOLSIZE, sizeof(entropy)); /* * Step over all of live entropy sources, and feed their output * to the system-wide RNG. */ if (rse_warm) epoch_enter_preempt(rs_epoch, &et); CK_LIST_FOREACH(rrs, &source_list, rrs_entries) { for (i = 0; i < npools; i++) { if (rrs->rrs_source->rs_read == NULL) { /* Source pushes entropy asynchronously. */ continue; } n = rrs->rrs_source->rs_read(entropy, sizeof(entropy)); KASSERT((n <= sizeof(entropy)), ("%s: rs_read returned too much data (%u > %zu)", __func__, n, sizeof(entropy))); /* * Sometimes the HW entropy source doesn't have anything * ready for us. This isn't necessarily untrustworthy. * We don't perform any other verification of an entropy * source (i.e., length is allowed to be anywhere from 1 * to sizeof(entropy), quality is unchecked, etc), so * don't balk verbosely at slow random sources either. * There are reports that RDSEED on x86 metal falls * behind the rate at which we query it, for example. * But it's still a better entropy source than RDRAND. */ if (n == 0) continue; random_harvest_direct(entropy, n, rrs->rrs_source->rs_source); } } if (rse_warm) epoch_exit_preempt(rs_epoch, &et); explicit_bzero(entropy, sizeof(entropy)); } /* * State used for conducting NIST SP 800-90B health tests on entropy sources. */ static struct health_test_softc { uint32_t ht_rct_value[HARVESTSIZE + 1]; u_int ht_rct_count; /* number of samples with the same value */ u_int ht_rct_limit; /* constant after init */ uint32_t ht_apt_value[HARVESTSIZE + 1]; u_int ht_apt_count; /* number of samples with the same value */ u_int ht_apt_seq; /* sequence number of the last sample */ u_int ht_apt_cutoff; /* constant after init */ uint64_t ht_total_samples; bool ondemand; /* Set to true to restart the state machine */ enum { INIT = 0, /* initial state */ DISABLED, /* health checking is disabled */ STARTUP, /* doing startup tests, samples are discarded */ STEADY, /* steady-state operation */ FAILED, /* health check failed, discard samples */ } ht_state; } healthtest[ENTROPYSOURCE]; #define RANDOM_SELFTEST_STARTUP_SAMPLES 1024 /* 4.3, requirement 4 */ #define RANDOM_SELFTEST_APT_WINDOW 512 /* 4.4.2 */ static void copy_event(uint32_t dst[static HARVESTSIZE + 1], const struct harvest_event *event) { memset(dst, 0, sizeof(uint32_t) * (HARVESTSIZE + 1)); memcpy(dst, event->he_entropy, event->he_size); if (event->he_source <= RANDOM_ENVIRONMENTAL_END) { /* * For pure entropy sources the timestamp counter is generally * quite determinstic since samples are taken at regular * intervals, so does not contribute much to the entropy. To * make health tests more effective, exclude it from the sample, * since it might otherwise defeat the health tests in a * scenario where the source is stuck. */ dst[HARVESTSIZE] = event->he_somecounter; } } static void random_healthtest_rct_init(struct health_test_softc *ht, const struct harvest_event *event) { ht->ht_rct_count = 1; copy_event(ht->ht_rct_value, event); } /* * Apply the repitition count test to a sample. * * Return false if the test failed, i.e., we observed >= C consecutive samples * with the same value, and true otherwise. */ static bool random_healthtest_rct_next(struct health_test_softc *ht, const struct harvest_event *event) { uint32_t val[HARVESTSIZE + 1]; copy_event(val, event); if (memcmp(val, ht->ht_rct_value, sizeof(ht->ht_rct_value)) != 0) { ht->ht_rct_count = 1; memcpy(ht->ht_rct_value, val, sizeof(ht->ht_rct_value)); return (true); } else { ht->ht_rct_count++; return (ht->ht_rct_count < ht->ht_rct_limit); } } static void random_healthtest_apt_init(struct health_test_softc *ht, const struct harvest_event *event) { ht->ht_apt_count = 1; ht->ht_apt_seq = 1; copy_event(ht->ht_apt_value, event); } static bool random_healthtest_apt_next(struct health_test_softc *ht, const struct harvest_event *event) { uint32_t val[HARVESTSIZE + 1]; if (ht->ht_apt_seq == 0) { random_healthtest_apt_init(ht, event); return (true); } copy_event(val, event); if (memcmp(val, ht->ht_apt_value, sizeof(ht->ht_apt_value)) == 0) { ht->ht_apt_count++; if (ht->ht_apt_count >= ht->ht_apt_cutoff) return (false); } ht->ht_apt_seq++; if (ht->ht_apt_seq == RANDOM_SELFTEST_APT_WINDOW) ht->ht_apt_seq = 0; return (true); } /* * Run the health tests for the given event. This is assumed to be called from * a serialized context. */ bool random_harvest_healthtest(const struct harvest_event *event) { struct health_test_softc *ht; ht = &healthtest[event->he_source]; /* * Was on-demand testing requested? Restart the state machine if so, * restarting the startup tests. */ if (atomic_load_bool(&ht->ondemand)) { atomic_store_bool(&ht->ondemand, false); ht->ht_state = INIT; } switch (ht->ht_state) { case __predict_false(INIT): /* Store the first sample and initialize test state. */ random_healthtest_rct_init(ht, event); random_healthtest_apt_init(ht, event); ht->ht_total_samples = 0; ht->ht_state = STARTUP; return (false); case DISABLED: /* No health testing for this source. */ return (true); case STEADY: case STARTUP: ht->ht_total_samples++; if (random_healthtest_rct_next(ht, event) && random_healthtest_apt_next(ht, event)) { if (ht->ht_state == STARTUP && ht->ht_total_samples >= RANDOM_SELFTEST_STARTUP_SAMPLES) { printf( "random: health test passed for source %s\n", random_source_descr[event->he_source]); ht->ht_state = STEADY; } return (ht->ht_state == STEADY); } ht->ht_state = FAILED; printf( "random: health test failed for source %s, discarding samples\n", random_source_descr[event->he_source]); /* FALLTHROUGH */ case FAILED: return (false); } } static bool nist_healthtest_enabled = false; SYSCTL_BOOL(_kern_random, OID_AUTO, nist_healthtest_enabled, CTLFLAG_RDTUN, &nist_healthtest_enabled, 0, "Enable NIST SP 800-90B health tests for noise sources"); static void random_healthtest_init(enum random_entropy_source source, int min_entropy) { struct health_test_softc *ht; ht = &healthtest[source]; memset(ht, 0, sizeof(*ht)); KASSERT(ht->ht_state == INIT, ("%s: health test state is %d for source %d", __func__, ht->ht_state, source)); /* * If health-testing is enabled, validate all sources except CACHED and * VMGENID: they are deterministic sources used only a small, fixed * number of times, so statistical testing is not applicable. */ if (!nist_healthtest_enabled || source == RANDOM_CACHED || source == RANDOM_PURE_VMGENID) { ht->ht_state = DISABLED; return; } /* * Set cutoff values for the two tests, given a min-entropy estimate for * the source and allowing for an error rate of 1 in 2^{34}. With a * min-entropy estimate of 1 bit and a sample rate of RANDOM_KTHREAD_HZ, * we expect to see an false positive once in ~54.5 years. * * The RCT limit comes from the formula in section 4.4.1. * * The APT cutoffs are calculated using the formula in section 4.4.2 * footnote 10 with the number of Bernoulli trials changed from W to * W-1, since the test as written counts the number of samples equal to * the first sample in the window, and thus tests W-1 samples. We * provide cutoffs for estimates up to sizeof(uint32_t)*HARVESTSIZE*8 * bits. */ const int apt_cutoffs[] = { [1] = 329, [2] = 195, [3] = 118, [4] = 73, [5] = 48, [6] = 33, [7] = 23, [8] = 17, [9] = 13, [10] = 11, [11] = 9, [12] = 8, [13] = 7, [14] = 6, [15] = 5, [16] = 5, [17 ... 19] = 4, [20 ... 25] = 3, [26 ... 42] = 2, [43 ... 64] = 1, }; const int error_rate = 34; if (min_entropy == 0) { /* * For environmental sources, the main source of entropy is the * associated timecounter value. Since these sources can be * influenced by unprivileged users, we conservatively use a * min-entropy estimate of 1 bit per sample. For "pure" * sources, we assume 8 bits per sample, as such sources provide * a variable amount of data per read and in particular might * only provide a single byte at a time. */ min_entropy = source >= RANDOM_PURE_START ? 8 : 1; } else if (min_entropy < 0 || min_entropy >= nitems(apt_cutoffs)) { panic("invalid min_entropy %d for %s", min_entropy, random_source_descr[source]); } ht->ht_rct_limit = 1 + howmany(error_rate, min_entropy); ht->ht_apt_cutoff = apt_cutoffs[min_entropy]; } static int random_healthtest_ondemand(SYSCTL_HANDLER_ARGS) { u_int mask, source; int error; mask = 0; error = sysctl_handle_int(oidp, &mask, 0, req); if (error != 0 || req->newptr == NULL) return (error); while (mask != 0) { source = ffs(mask) - 1; if (source < nitems(healthtest)) atomic_store_bool(&healthtest[source].ondemand, true); mask &= ~(1u << source); } return (0); } SYSCTL_PROC(_kern_random, OID_AUTO, nist_healthtest_ondemand, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0, random_healthtest_ondemand, "I", "Re-run NIST SP 800-90B startup health tests for a noise source"); static int random_check_uint_harvestmask(SYSCTL_HANDLER_ARGS) { static const u_int user_immutable_mask = (((1 << ENTROPYSOURCE) - 1) & (-1UL << RANDOM_PURE_START)) | _RANDOM_HARVEST_ETHER_OFF | _RANDOM_HARVEST_UMA_OFF; int error; u_int value; value = atomic_load_int(&hc_source_mask); error = sysctl_handle_int(oidp, &value, 0, req); if (error != 0 || req->newptr == NULL) return (error); if (flsl(value) > ENTROPYSOURCE) return (EINVAL); /* * Disallow userspace modification of pure entropy sources. */ RANDOM_HARVEST_LOCK(); hc_source_mask = (value & ~user_immutable_mask) | (hc_source_mask & user_immutable_mask); RANDOM_HARVEST_UNLOCK(); return (0); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask, CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0, random_check_uint_harvestmask, "IU", "Entropy harvesting mask"); static int random_print_harvestmask(SYSCTL_HANDLER_ARGS) { struct sbuf sbuf; int error, i; error = sysctl_wire_old_buffer(req, 0); if (error == 0) { u_int mask; sbuf_new_for_sysctl(&sbuf, NULL, 128, req); mask = atomic_load_int(&hc_source_mask); for (i = ENTROPYSOURCE - 1; i >= 0; i--) { bool present; present = (mask & (1u << i)) != 0; sbuf_cat(&sbuf, present ? "1" : "0"); } error = sbuf_finish(&sbuf); sbuf_delete(&sbuf); } return (error); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0, random_print_harvestmask, "A", "Entropy harvesting mask (printable)"); static const char *random_source_descr[/*ENTROPYSOURCE*/] = { [RANDOM_CACHED] = "CACHED", [RANDOM_ATTACH] = "ATTACH", [RANDOM_KEYBOARD] = "KEYBOARD", [RANDOM_MOUSE] = "MOUSE", [RANDOM_NET_TUN] = "NET_TUN", [RANDOM_NET_ETHER] = "NET_ETHER", [RANDOM_NET_NG] = "NET_NG", [RANDOM_INTERRUPT] = "INTERRUPT", [RANDOM_SWI] = "SWI", [RANDOM_FS_ATIME] = "FS_ATIME", [RANDOM_UMA] = "UMA", [RANDOM_CALLOUT] = "CALLOUT", [RANDOM_RANDOMDEV] = "RANDOMDEV", /* ENVIRONMENTAL_END */ - [RANDOM_PURE_SAFE] = "PURE_SAFE", /* PURE_START */ - [RANDOM_PURE_GLXSB] = "PURE_GLXSB", - [RANDOM_PURE_HIFN] = "PURE_HIFN", + [RANDOM_PURE_TPM] = "PURE_TPM", /* PURE_START */ [RANDOM_PURE_RDRAND] = "PURE_RDRAND", [RANDOM_PURE_RDSEED] = "PURE_RDSEED", [RANDOM_PURE_NEHEMIAH] = "PURE_NEHEMIAH", [RANDOM_PURE_RNDTEST] = "PURE_RNDTEST", [RANDOM_PURE_VIRTIO] = "PURE_VIRTIO", [RANDOM_PURE_BROADCOM] = "PURE_BROADCOM", [RANDOM_PURE_CCP] = "PURE_CCP", [RANDOM_PURE_DARN] = "PURE_DARN", - [RANDOM_PURE_TPM] = "PURE_TPM", [RANDOM_PURE_VMGENID] = "PURE_VMGENID", [RANDOM_PURE_QUALCOMM] = "PURE_QUALCOMM", [RANDOM_PURE_ARMV8] = "PURE_ARMV8", [RANDOM_PURE_ARM_TRNG] = "PURE_ARM_TRNG", + [RANDOM_PURE_SAFE] = "PURE_SAFE", + [RANDOM_PURE_GLXSB] = "PURE_GLXSB", + [RANDOM_PURE_HIFN] = "PURE_HIFN", /* "ENTROPYSOURCE" */ }; CTASSERT(nitems(random_source_descr) == ENTROPYSOURCE); static int random_print_harvestmask_symbolic(SYSCTL_HANDLER_ARGS) { struct sbuf sbuf; int error, i; bool first; first = true; error = sysctl_wire_old_buffer(req, 0); if (error == 0) { u_int mask; sbuf_new_for_sysctl(&sbuf, NULL, 128, req); mask = atomic_load_int(&hc_source_mask); for (i = ENTROPYSOURCE - 1; i >= 0; i--) { bool present; present = (mask & (1u << i)) != 0; if (i >= RANDOM_PURE_START && !present) continue; if (!first) sbuf_cat(&sbuf, ","); sbuf_cat(&sbuf, !present ? "[" : ""); sbuf_cat(&sbuf, random_source_descr[i]); sbuf_cat(&sbuf, !present ? "]" : ""); first = false; } error = sbuf_finish(&sbuf); sbuf_delete(&sbuf); } return (error); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)"); static void random_harvestq_init(void *unused __unused) { static const u_int almost_everything_mask = (((1 << (RANDOM_ENVIRONMENTAL_END + 1)) - 1) & ~_RANDOM_HARVEST_ETHER_OFF & ~_RANDOM_HARVEST_UMA_OFF); hc_source_mask = almost_everything_mask; RANDOM_HARVEST_INIT_LOCK(); harvest_context.hc_active_buf = 0; for (int i = RANDOM_START; i <= RANDOM_ENVIRONMENTAL_END; i++) random_healthtest_init(i, 0); } SYSINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_init, NULL); /* * Subroutine to slice up a contiguous chunk of 'entropy' and feed it into the * underlying algorithm. Returns number of bytes actually fed into underlying * algorithm. */ static size_t random_early_prime(char *entropy, size_t len) { struct harvest_event event; size_t i; len = rounddown(len, sizeof(event.he_entropy)); if (len == 0) return (0); for (i = 0; i < len; i += sizeof(event.he_entropy)) { event.he_somecounter = random_get_cyclecount(); event.he_size = sizeof(event.he_entropy); event.he_source = RANDOM_CACHED; event.he_destination = harvest_context.hc_destination[RANDOM_CACHED]++; memcpy(event.he_entropy, entropy + i, sizeof(event.he_entropy)); random_harvestq_fast_process_event(&event); } explicit_bzero(entropy, len); return (len); } /* * Subroutine to search for known loader-loaded files in memory and feed them * into the underlying algorithm early in boot. Returns the number of bytes * loaded (zero if none were loaded). */ static size_t random_prime_loader_file(const char *type) { uint8_t *keyfile, *data; size_t size; keyfile = preload_search_by_type(type); if (keyfile == NULL) return (0); data = preload_fetch_addr(keyfile); size = preload_fetch_size(keyfile); if (data == NULL) return (0); return (random_early_prime(data, size)); } /* * This is used to prime the RNG by grabbing any early random stuff * known to the kernel, and inserting it directly into the hashing * module, currently Fortuna. */ static void random_harvestq_prime(void *unused __unused) { size_t size; /* * Get entropy that may have been preloaded by loader(8) * and use it to pre-charge the entropy harvest queue. */ size = random_prime_loader_file(RANDOM_CACHED_BOOT_ENTROPY_MODULE); if (bootverbose) { if (size > 0) printf("random: read %zu bytes from preloaded cache\n", size); else printf("random: no preloaded entropy cache\n"); } size = random_prime_loader_file(RANDOM_PLATFORM_BOOT_ENTROPY_MODULE); if (bootverbose) { if (size > 0) printf("random: read %zu bytes from platform bootloader\n", size); else printf("random: no platform bootloader entropy\n"); } } SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL); static void random_harvestq_deinit(void *unused __unused) { /* Command the hash/reseed thread to end and wait for it to finish */ random_kthread_control = 0; while (random_kthread_control >= 0) tsleep(&harvest_context.hc_kthread_proc, 0, "harvqterm", hz/5); } SYSUNINIT(random_device_h_init, SI_SUB_RANDOM, SI_ORDER_THIRD, random_harvestq_deinit, NULL); /*- * Entropy harvesting queue routine. * * This is supposed to be fast; do not do anything slow in here! * It is also illegal (and morally reprehensible) to insert any * high-rate data here. "High-rate" is defined as a data source * that is likely to fill up the buffer in much less than 100ms. * This includes the "always-on" sources like the Intel "rdrand" * or the VIA Nehamiah "xstore" sources. */ /* XXXRW: get_cyclecount() is cheap on most modern hardware, where cycle * counters are built in, but on older hardware it will do a real time clock * read which can be quite expensive. */ void random_harvest_queue_(const void *entropy, u_int size, enum random_entropy_source origin) { struct harvest_context *hc; struct entropy_buffer *buf; struct harvest_event *event; KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid", __func__, origin)); hc = &harvest_context; RANDOM_HARVEST_LOCK(); buf = &hc->hc_entropy_buf[hc->hc_active_buf]; if (buf->pos < RANDOM_RING_MAX) { event = &buf->ring[buf->pos++]; event->he_somecounter = random_get_cyclecount(); event->he_source = origin; event->he_destination = hc->hc_destination[origin]++; if (size <= sizeof(event->he_entropy)) { event->he_size = size; memcpy(event->he_entropy, entropy, size); } else { /* Big event, so squash it */ event->he_size = sizeof(event->he_entropy[0]); event->he_entropy[0] = jenkins_hash(entropy, size, (uint32_t)(uintptr_t)event); } } RANDOM_HARVEST_UNLOCK(); } /*- * Entropy harvesting fast routine. * * This is supposed to be very fast; do not do anything slow in here! * This is the right place for high-rate harvested data. */ void random_harvest_fast_(const void *entropy, u_int size) { u_int pos; pos = harvest_context.hc_entropy_fast_accumulator.pos; harvest_context.hc_entropy_fast_accumulator.buf[pos] ^= jenkins_hash(entropy, size, random_get_cyclecount()); harvest_context.hc_entropy_fast_accumulator.pos = (pos + 1)%RANDOM_ACCUM_MAX; } /*- * Entropy harvesting direct routine. * * This is not supposed to be fast, but will only be used during * (e.g.) booting when initial entropy is being gathered. */ void random_harvest_direct_(const void *entropy, u_int size, enum random_entropy_source origin) { struct harvest_event event; KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin)); size = MIN(size, sizeof(event.he_entropy)); event.he_somecounter = random_get_cyclecount(); event.he_size = size; event.he_source = origin; event.he_destination = harvest_context.hc_destination[origin]++; memcpy(event.he_entropy, entropy, size); random_harvestq_fast_process_event(&event); } void random_source_register(const struct random_source *rsource) { struct random_sources *rrs; KASSERT(rsource != NULL, ("invalid input to %s", __func__)); rrs = malloc(sizeof(*rrs), M_ENTROPY, M_WAITOK); rrs->rrs_source = rsource; printf("random: registering fast source %s\n", rsource->rs_ident); random_healthtest_init(rsource->rs_source, rsource->rs_min_entropy); RANDOM_HARVEST_LOCK(); hc_source_mask |= (1 << rsource->rs_source); CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries); RANDOM_HARVEST_UNLOCK(); } void random_source_deregister(const struct random_source *rsource) { struct random_sources *rrs = NULL; KASSERT(rsource != NULL, ("invalid input to %s", __func__)); RANDOM_HARVEST_LOCK(); hc_source_mask &= ~(1 << rsource->rs_source); CK_LIST_FOREACH(rrs, &source_list, rrs_entries) if (rrs->rrs_source == rsource) { CK_LIST_REMOVE(rrs, rrs_entries); break; } RANDOM_HARVEST_UNLOCK(); if (rrs != NULL && epoch_inited) epoch_wait_preempt(rs_epoch); free(rrs, M_ENTROPY); } static int random_source_handler(SYSCTL_HANDLER_ARGS) { struct epoch_tracker et; struct random_sources *rrs; struct sbuf sbuf; int error, count; error = sysctl_wire_old_buffer(req, 0); if (error != 0) return (error); sbuf_new_for_sysctl(&sbuf, NULL, 64, req); count = 0; epoch_enter_preempt(rs_epoch, &et); CK_LIST_FOREACH(rrs, &source_list, rrs_entries) { sbuf_cat(&sbuf, (count++ ? ",'" : "'")); sbuf_cat(&sbuf, rrs->rrs_source->rs_ident); sbuf_cat(&sbuf, "'"); } epoch_exit_preempt(rs_epoch, &et); error = sbuf_finish(&sbuf); sbuf_delete(&sbuf); return (error); } SYSCTL_PROC(_kern_random, OID_AUTO, random_sources, CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0, random_source_handler, "A", "List of active fast entropy sources."); MODULE_VERSION(random_harvestq, 1); diff --git a/sys/sys/random.h b/sys/sys/random.h index af6b1e117423..64f2a1e1b40c 100644 --- a/sys/sys/random.h +++ b/sys/sys/random.h @@ -1,173 +1,173 @@ /*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2000-2015, 2017 Mark R. V. Murray * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SYS_RANDOM_H_ #define _SYS_RANDOM_H_ #include #ifdef _KERNEL struct uio; /* * In the loadable random world, there are set of dangling pointers left in the * core kernel: * * read_random, read_random_uio, is_random_seeded are function pointers, * rather than functions. * * p_random_alg_context is a true pointer in loadable random kernels. * * These are initialized at SI_SUB_RANDOM:SI_ORDER_SECOND during boot. The * read-type pointers are initialized by random_alg_context_init() in * randomdev.c and p_random_alg_context in the algorithm, e.g., fortuna.c's * random_fortuna_init_alg(). The nice thing about function pointers is they * have a similar calling convention to ordinary functions. * * (In !loadable, the read_random, etc, routines are just plain functions; * p_random_alg_context is a macro for the public visibility * &random_alg_context.) */ #if defined(RANDOM_LOADABLE) extern void (*_read_random)(void *, u_int); extern int (*_read_random_uio)(struct uio *, bool); extern bool (*_is_random_seeded)(void); #define read_random(a, b) (*_read_random)(a, b) #define read_random_uio(a, b) (*_read_random_uio)(a, b) #define is_random_seeded() (*_is_random_seeded)() #else void read_random(void *, u_int); int read_random_uio(struct uio *, bool); bool is_random_seeded(void); #endif /* * Note: if you add or remove members of random_entropy_source, remember to * also update the strings in the static array random_source_descr[] in * random_harvestq.c. */ enum random_entropy_source { RANDOM_START = 0, RANDOM_CACHED = 0, /* Environmental sources */ RANDOM_ATTACH, RANDOM_KEYBOARD, RANDOM_MOUSE, RANDOM_NET_TUN, RANDOM_NET_ETHER, RANDOM_NET_NG, RANDOM_INTERRUPT, RANDOM_SWI, RANDOM_FS_ATIME, RANDOM_UMA, /* Special!! UMA/SLAB Allocator */ RANDOM_CALLOUT, RANDOM_RANDOMDEV, RANDOM_ENVIRONMENTAL_END = RANDOM_RANDOMDEV, /* Fast hardware random-number sources from here on. */ RANDOM_PURE_START, - RANDOM_PURE_SAFE = RANDOM_PURE_START, - RANDOM_PURE_GLXSB, - RANDOM_PURE_HIFN, + RANDOM_PURE_TPM = RANDOM_PURE_START, RANDOM_PURE_RDRAND, RANDOM_PURE_RDSEED, RANDOM_PURE_NEHEMIAH, RANDOM_PURE_RNDTEST, RANDOM_PURE_VIRTIO, RANDOM_PURE_BROADCOM, RANDOM_PURE_CCP, RANDOM_PURE_DARN, - RANDOM_PURE_TPM, RANDOM_PURE_VMGENID, RANDOM_PURE_QUALCOMM, RANDOM_PURE_ARMV8, RANDOM_PURE_ARM_TRNG, + RANDOM_PURE_SAFE, + RANDOM_PURE_GLXSB, + RANDOM_PURE_HIFN, ENTROPYSOURCE }; _Static_assert(ENTROPYSOURCE <= 32, "hardcoded assumption that values fit in a typical word-sized bitset"); #define RANDOM_CACHED_BOOT_ENTROPY_MODULE "boot_entropy_cache" #define RANDOM_PLATFORM_BOOT_ENTROPY_MODULE "boot_entropy_platform" extern u_int hc_source_mask; void random_harvest_queue_(const void *, u_int, enum random_entropy_source); void random_harvest_fast_(const void *, u_int); void random_harvest_direct_(const void *, u_int, enum random_entropy_source); static __inline void random_harvest_queue(const void *entropy, u_int size, enum random_entropy_source origin) { if (hc_source_mask & (1 << origin)) random_harvest_queue_(entropy, size, origin); } static __inline void random_harvest_fast(const void *entropy, u_int size, enum random_entropy_source origin) { if (hc_source_mask & (1 << origin)) random_harvest_fast_(entropy, size); } static __inline void random_harvest_direct(const void *entropy, u_int size, enum random_entropy_source origin) { if (hc_source_mask & (1 << origin)) random_harvest_direct_(entropy, size, origin); } #if defined(RANDOM_ENABLE_UMA) #define random_harvest_fast_uma(a, b, c) random_harvest_fast(a, b, c) #else /* !defined(RANDOM_ENABLE_UMA) */ #define random_harvest_fast_uma(a, b, c) do {} while (0) #endif /* defined(RANDOM_ENABLE_UMA) */ #if defined(RANDOM_ENABLE_ETHER) #define random_harvest_queue_ether(a, b) random_harvest_queue(a, b, RANDOM_NET_ETHER) #else /* !defined(RANDOM_ENABLE_ETHER) */ #define random_harvest_queue_ether(a, b) do {} while (0) #endif /* defined(RANDOM_ENABLE_ETHER) */ #else /* !_KERNEL */ #if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0 #include #endif #endif /* _KERNEL */ #define GRND_NONBLOCK 0x1 #define GRND_RANDOM 0x2 #define GRND_INSECURE 0x4 __BEGIN_DECLS ssize_t getrandom(void *buf, size_t buflen, unsigned int flags); __END_DECLS #endif /* _SYS_RANDOM_H_ */