Index: head/sys/dev/random/fortuna.c =================================================================== --- head/sys/dev/random/fortuna.c (revision 356244) +++ head/sys/dev/random/fortuna.c (revision 356245) @@ -1,813 +1,820 @@ /*- * Copyright (c) 2017 W. Dean Freeman * Copyright (c) 2013-2015 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. * */ /* * This implementation of Fortuna is based on the descriptions found in * ISBN 978-0-470-47424-2 "Cryptography Engineering" by Ferguson, Schneier * and Kohno ("FS&K"). */ #include __FBSDID("$FreeBSD$"); #include #include #ifdef _KERNEL #include #include #include #include #include #include #include #include #include #include #else /* !_KERNEL */ #include #include #include #include #include #include #include "unit_test.h" #endif /* _KERNEL */ #include #include #include #include #include #ifdef _KERNEL #include #endif #include #include /* Defined in FS&K */ #define RANDOM_FORTUNA_NPOOLS 32 /* The number of accumulation pools */ #define RANDOM_FORTUNA_DEFPOOLSIZE 64 /* The default pool size/length for a (re)seed */ #define RANDOM_FORTUNA_MAX_READ (1 << 20) /* Max bytes from AES before rekeying */ #define RANDOM_FORTUNA_BLOCKS_PER_KEY (1 << 16) /* Max blocks from AES before rekeying */ CTASSERT(RANDOM_FORTUNA_BLOCKS_PER_KEY * RANDOM_BLOCKSIZE == RANDOM_FORTUNA_MAX_READ); /* * The allowable range of RANDOM_FORTUNA_DEFPOOLSIZE. The default value is above. * Making RANDOM_FORTUNA_DEFPOOLSIZE too large will mean a long time between reseeds, * and too small may compromise initial security but get faster reseeds. */ #define RANDOM_FORTUNA_MINPOOLSIZE 16 #define RANDOM_FORTUNA_MAXPOOLSIZE INT_MAX CTASSERT(RANDOM_FORTUNA_MINPOOLSIZE <= RANDOM_FORTUNA_DEFPOOLSIZE); CTASSERT(RANDOM_FORTUNA_DEFPOOLSIZE <= RANDOM_FORTUNA_MAXPOOLSIZE); /* This algorithm (and code) presumes that RANDOM_KEYSIZE is twice as large as RANDOM_BLOCKSIZE */ CTASSERT(RANDOM_BLOCKSIZE == sizeof(uint128_t)); CTASSERT(RANDOM_KEYSIZE == 2*RANDOM_BLOCKSIZE); /* Probes for dtrace(1) */ #ifdef _KERNEL SDT_PROVIDER_DECLARE(random); SDT_PROVIDER_DEFINE(random); SDT_PROBE_DEFINE2(random, fortuna, event_processor, debug, "u_int", "struct fs_pool *"); #endif /* _KERNEL */ /* * This is the beastie that needs protecting. It contains all of the * state that we are excited about. Exactly one is instantiated. */ static struct fortuna_state { struct fs_pool { /* P_i */ u_int fsp_length; /* Only the first one is used by Fortuna */ struct randomdev_hash fsp_hash; } fs_pool[RANDOM_FORTUNA_NPOOLS]; u_int fs_reseedcount; /* ReseedCnt */ uint128_t fs_counter; /* C */ union randomdev_key fs_key; /* K */ u_int fs_minpoolsize; /* Extras */ /* Extras for the OS */ #ifdef _KERNEL /* For use when 'pacing' the reseeds */ sbintime_t fs_lasttime; #endif /* Reseed lock */ mtx_t fs_mtx; } fortuna_state; /* * This knob enables or disables the "Concurrent Reads" Fortuna feature. * * The benefit of Concurrent Reads is improved concurrency in Fortuna. That is * reflected in two related aspects: * * 1. Concurrent full-rate devrandom readers can achieve similar throughput to * a single reader thread (at least up to a modest number of cores; the * non-concurrent design falls over at 2 readers). * * 2. The rand_harvestq process spends much less time spinning when one or more * readers is processing a large request. Partially this is due to * rand_harvestq / ra_event_processor design, which only passes one event at * a time to the underlying algorithm. Each time, Fortuna must take its * global state mutex, potentially blocking on a reader. Our adaptive * mutexes assume that a lock holder currently on CPU will release the lock * quickly, and spin if the owning thread is currently running. * * (There is no reason rand_harvestq necessarily has to use the same lock as * the generator, or that it must necessarily drop and retake locks * repeatedly, but that is the current status quo.) * * The concern is that the reduced lock scope might results in a less safe * random(4) design. However, the reduced-lock scope design is still * fundamentally Fortuna. This is discussed below. * * Fortuna Read() only needs mutual exclusion between readers to correctly * update the shared read-side state: C, the 128-bit counter; and K, the * current cipher/PRF key. * * In the Fortuna design, the global counter C should provide an independent * range of values per request. * * Under lock, we can save a copy of C on the stack, and increment the global C * by the number of blocks a Read request will require. * * Still under lock, we can save a copy of the key K on the stack, and then * perform the usual key erasure K' <- Keystream(C, K, ...). This does require * generating 256 bits (32 bytes) of cryptographic keystream output with the * global lock held, but that's all; none of the API keystream generation must * be performed under lock. * * At this point, we may unlock. * * Some example timelines below (to oversimplify, all requests are in units of * native blocks, and the keysize happens to be equal or less to the native * blocksize of the underlying cipher, and the same sequence of two requests * arrive in the same order). The possibly expensive consumer keystream * generation portion is marked with '**'. * * Status Quo fortuna_read() Reduced-scope locking * ------------------------- --------------------- * C=C_0, K=K_0 C=C_0, K=K_0 * * 1:Lock() 1:Lock() * * 1:GenBytes() 1:stack_C := C_0 * 1: Keystream(C_0, K_0, N) 1:stack_K := K_0 * 1: ** 1:C' := C_0 + N * 1: C' := C_0 + N 1:K' := Keystream(C', K_0, 1) * 1: <- Keystream 1: <1 block generated> * 1: K' := Keystream(C', K_0, 1) 1: C'' := C' + 1 * 1: <1 block generated> 1: <- Keystream * 1: C'' := C' + 1 1:Unlock() * 1: <- Keystream * 1: <- GenBytes() * 1:Unlock() * * Just prior to unlock, shared state is identical: * ------------------------------------------------ * C'' == C_0 + N + 1 C'' == C_0 + N + 1 * K' == keystream generated from K' == keystream generated from * C_0 + N, K_0. C_0 + N, K_0. * K_0 has been erased. K_0 has been erased. * * After both designs unlock, the 2nd reader is unblocked. * * 2:Lock() 2:Lock() * 2:GenBytes() 2:stack_C' := C'' * 2: Keystream(C'', K', M) 2:stack_K' := K' * 2: ** 2:C''' := C'' + M * 2: C''' := C'' + M 2:K'' := Keystream(C''', K', 1) * 2: <- Keystream 2: <1 block generated> * 2: K'' := Keystream(C''', K', 1) 2: C'''' := C''' + 1 * 2: <1 block generated> 2: <- Keystream * 2: C'''' := C''' + 1 2:Unlock() * 2: <- Keystream * 2: <- GenBytes() * 2:Unlock() * * Just prior to unlock, global state is identical: * ------------------------------------------------------ * * C'''' == (C_0 + N + 1) + M + 1 C'''' == (C_0 + N + 1) + M + 1 * K'' == keystream generated from K'' == keystream generated from * C_0 + N + 1 + M, K'. C_0 + N + 1 + M, K'. * K' has been erased. K' has been erased. * * Finally, in the new design, the two consumer threads can finish the * remainder of the generation at any time (including simultaneously): * * 1: GenBytes() * 1: Keystream(stack_C, stack_K, N) * 1: ** * 1: <- Keystream * 1: <- GenBytes * 1:ExplicitBzero(stack_C, stack_K) * * 2: GenBytes() * 2: Keystream(stack_C', stack_K', M) * 2: ** * 2: <- Keystream * 2: <- GenBytes * 2:ExplicitBzero(stack_C', stack_K') * * The generated user keystream for both threads is identical between the two * implementations: * * 1: Keystream(C_0, K_0, N) 1: Keystream(stack_C, stack_K, N) * 2: Keystream(C'', K', M) 2: Keystream(stack_C', stack_K', M) * * (stack_C == C_0; stack_K == K_0; stack_C' == C''; stack_K' == K'.) */ static bool fortuna_concurrent_read __read_frequently = true; #ifdef _KERNEL static struct sysctl_ctx_list random_clist; RANDOM_CHECK_UINT(fs_minpoolsize, RANDOM_FORTUNA_MINPOOLSIZE, RANDOM_FORTUNA_MAXPOOLSIZE); #else static uint8_t zero_region[RANDOM_ZERO_BLOCKSIZE]; #endif static void random_fortuna_pre_read(void); static void random_fortuna_read(uint8_t *, size_t); static bool random_fortuna_seeded(void); static bool random_fortuna_seeded_internal(void); static void random_fortuna_process_event(struct harvest_event *); static void random_fortuna_reseed_internal(uint32_t *entropy_data, u_int blockcount); #ifdef RANDOM_LOADABLE static #endif const struct random_algorithm random_alg_context = { .ra_ident = "Fortuna", .ra_pre_read = random_fortuna_pre_read, .ra_read = random_fortuna_read, .ra_seeded = random_fortuna_seeded, .ra_event_processor = random_fortuna_process_event, .ra_poolcount = RANDOM_FORTUNA_NPOOLS, }; /* ARGSUSED */ static void random_fortuna_init_alg(void *unused __unused) { int i; #ifdef _KERNEL struct sysctl_oid *random_fortuna_o; #endif #ifdef RANDOM_LOADABLE p_random_alg_context = &random_alg_context; #endif RANDOM_RESEED_INIT_LOCK(); /* * Fortuna parameters. Do not adjust these unless you have * have a very good clue about what they do! */ fortuna_state.fs_minpoolsize = RANDOM_FORTUNA_DEFPOOLSIZE; #ifdef _KERNEL fortuna_state.fs_lasttime = 0; random_fortuna_o = SYSCTL_ADD_NODE(&random_clist, SYSCTL_STATIC_CHILDREN(_kern_random), OID_AUTO, "fortuna", CTLFLAG_RW, 0, "Fortuna Parameters"); SYSCTL_ADD_PROC(&random_clist, SYSCTL_CHILDREN(random_fortuna_o), OID_AUTO, "minpoolsize", CTLTYPE_UINT | CTLFLAG_RWTUN, &fortuna_state.fs_minpoolsize, RANDOM_FORTUNA_DEFPOOLSIZE, random_check_uint_fs_minpoolsize, "IU", "Minimum pool size necessary to cause a reseed"); KASSERT(fortuna_state.fs_minpoolsize > 0, ("random: Fortuna threshold must be > 0 at startup")); SYSCTL_ADD_BOOL(&random_clist, SYSCTL_CHILDREN(random_fortuna_o), OID_AUTO, "concurrent_read", CTLFLAG_RDTUN, &fortuna_concurrent_read, 0, "If non-zero, enable " "feature to improve concurrent Fortuna performance."); #endif /*- * FS&K - InitializePRNG() * - P_i = \epsilon * - ReseedCNT = 0 */ for (i = 0; i < RANDOM_FORTUNA_NPOOLS; i++) { randomdev_hash_init(&fortuna_state.fs_pool[i].fsp_hash); fortuna_state.fs_pool[i].fsp_length = 0; } fortuna_state.fs_reseedcount = 0; /*- * FS&K - InitializeGenerator() * - C = 0 * - K = 0 */ fortuna_state.fs_counter = UINT128_ZERO; explicit_bzero(&fortuna_state.fs_key, sizeof(fortuna_state.fs_key)); } SYSINIT(random_alg, SI_SUB_RANDOM, SI_ORDER_SECOND, random_fortuna_init_alg, NULL); /*- * FS&K - AddRandomEvent() * Process a single stochastic event off the harvest queue */ static void random_fortuna_process_event(struct harvest_event *event) { u_int pl; RANDOM_RESEED_LOCK(); /*- * FS&K - P_i = P_i| * Accumulate the event into the appropriate pool * where each event carries the destination information. * * The hash_init() and hash_finish() calls are done in * random_fortuna_pre_read(). * * We must be locked against pool state modification which can happen * during accumulation/reseeding and reading/regating. */ pl = event->he_destination % RANDOM_FORTUNA_NPOOLS; /* + * If a VM generation ID changes (clone and play or VM rewind), we want + * to incorporate that as soon as possible. Override destingation pool + * for immediate next use. + */ + if (event->he_source == RANDOM_PURE_VMGENID) + pl = 0; + /* * We ignore low entropy static/counter fields towards the end of the * he_event structure in order to increase measurable entropy when * conducting SP800-90B entropy analysis measurements of seed material * fed into PRNG. * -- wdf */ KASSERT(event->he_size <= sizeof(event->he_entropy), ("%s: event->he_size: %hhu > sizeof(event->he_entropy): %zu\n", __func__, event->he_size, sizeof(event->he_entropy))); randomdev_hash_iterate(&fortuna_state.fs_pool[pl].fsp_hash, &event->he_somecounter, sizeof(event->he_somecounter)); randomdev_hash_iterate(&fortuna_state.fs_pool[pl].fsp_hash, event->he_entropy, event->he_size); /*- * Don't wrap the length. This is a "saturating" add. * XXX: FIX!!: We don't actually need lengths for anything but fs_pool[0], * but it's been useful debugging to see them all. */ fortuna_state.fs_pool[pl].fsp_length = MIN(RANDOM_FORTUNA_MAXPOOLSIZE, fortuna_state.fs_pool[pl].fsp_length + sizeof(event->he_somecounter) + event->he_size); RANDOM_RESEED_UNLOCK(); } /*- * FS&K - Reseed() * This introduces new key material into the output generator. * Additionally it increments the output generator's counter * variable C. When C > 0, the output generator is seeded and * will deliver output. * The entropy_data buffer passed is a very specific size; the * product of RANDOM_FORTUNA_NPOOLS and RANDOM_KEYSIZE. */ static void random_fortuna_reseed_internal(uint32_t *entropy_data, u_int blockcount) { struct randomdev_hash context; uint8_t hash[RANDOM_KEYSIZE]; const void *keymaterial; size_t keysz; bool seeded; RANDOM_RESEED_ASSERT_LOCK_OWNED(); seeded = random_fortuna_seeded_internal(); if (seeded) { randomdev_getkey(&fortuna_state.fs_key, &keymaterial, &keysz); KASSERT(keysz == RANDOM_KEYSIZE, ("%s: key size %zu not %u", __func__, keysz, (unsigned)RANDOM_KEYSIZE)); } /*- * FS&K - K = Hd(K|s) where Hd(m) is H(H(0^512|m)) * - C = C + 1 */ randomdev_hash_init(&context); randomdev_hash_iterate(&context, zero_region, RANDOM_ZERO_BLOCKSIZE); if (seeded) randomdev_hash_iterate(&context, keymaterial, keysz); randomdev_hash_iterate(&context, entropy_data, RANDOM_KEYSIZE*blockcount); randomdev_hash_finish(&context, hash); randomdev_hash_init(&context); randomdev_hash_iterate(&context, hash, RANDOM_KEYSIZE); randomdev_hash_finish(&context, hash); randomdev_encrypt_init(&fortuna_state.fs_key, hash); explicit_bzero(hash, sizeof(hash)); /* Unblock the device if this is the first time we are reseeding. */ if (uint128_is_zero(fortuna_state.fs_counter)) randomdev_unblock(); uint128_increment(&fortuna_state.fs_counter); } /*- * FS&K - RandomData() (Part 1) * Used to return processed entropy from the PRNG. There is a pre_read * required to be present (but it can be a stub) in order to allow * specific actions at the begin of the read. */ void random_fortuna_pre_read(void) { #ifdef _KERNEL sbintime_t now; #endif struct randomdev_hash context; uint32_t s[RANDOM_FORTUNA_NPOOLS*RANDOM_KEYSIZE_WORDS]; uint8_t temp[RANDOM_KEYSIZE]; u_int i; KASSERT(fortuna_state.fs_minpoolsize > 0, ("random: Fortuna threshold must be > 0")); RANDOM_RESEED_LOCK(); #ifdef _KERNEL /* FS&K - Use 'getsbinuptime()' to prevent reseed-spamming. */ now = getsbinuptime(); #endif if (fortuna_state.fs_pool[0].fsp_length < fortuna_state.fs_minpoolsize #ifdef _KERNEL /* * FS&K - Use 'getsbinuptime()' to prevent reseed-spamming, but do * not block initial seeding (fs_lasttime == 0). */ || (__predict_true(fortuna_state.fs_lasttime != 0) && now - fortuna_state.fs_lasttime <= SBT_1S/10) #endif ) { RANDOM_RESEED_UNLOCK(); return; } #ifdef _KERNEL /* * When set, pretend we do not have enough entropy to reseed yet. */ KFAIL_POINT_CODE(DEBUG_FP, random_fortuna_pre_read, { if (RETURN_VALUE != 0) { RANDOM_RESEED_UNLOCK(); return; } }); #endif #ifdef _KERNEL fortuna_state.fs_lasttime = now; #endif /* FS&K - ReseedCNT = ReseedCNT + 1 */ fortuna_state.fs_reseedcount++; /* s = \epsilon at start */ for (i = 0; i < RANDOM_FORTUNA_NPOOLS; i++) { /* FS&K - if Divides(ReseedCnt, 2^i) ... */ if ((fortuna_state.fs_reseedcount % (1 << i)) == 0) { /*- * FS&K - temp = (P_i) * - P_i = \epsilon * - s = s|H(temp) */ randomdev_hash_finish(&fortuna_state.fs_pool[i].fsp_hash, temp); randomdev_hash_init(&fortuna_state.fs_pool[i].fsp_hash); fortuna_state.fs_pool[i].fsp_length = 0; randomdev_hash_init(&context); randomdev_hash_iterate(&context, temp, RANDOM_KEYSIZE); randomdev_hash_finish(&context, s + i*RANDOM_KEYSIZE_WORDS); } else break; } #ifdef _KERNEL SDT_PROBE2(random, fortuna, event_processor, debug, fortuna_state.fs_reseedcount, fortuna_state.fs_pool); #endif /* FS&K */ random_fortuna_reseed_internal(s, i); RANDOM_RESEED_UNLOCK(); /* Clean up and secure */ explicit_bzero(s, sizeof(s)); explicit_bzero(temp, sizeof(temp)); } /* * This is basically GenerateBlocks() from FS&K. * * It differs in two ways: * * 1. Chacha20 is tolerant of non-block-multiple request sizes, so we do not * need to handle any remainder bytes specially and can just pass the length * directly to the PRF construction; and * * 2. Chacha20 is a 512-bit block size cipher (whereas AES has 128-bit block * size, regardless of key size). This means Chacha does not require re-keying * every 1MiB. This is implied by the math in FS&K 9.4 and mentioned * explicitly in the conclusion, "If we had a block cipher with a 256-bit [or * greater] block size, then the collisions would not have been an issue at * all" (p. 144). * * 3. In conventional ("locked") mode, we produce a maximum of PAGE_SIZE output * at a time before dropping the lock, to not bully the lock especially. This * has been the status quo since 2015 (r284959). * * The upstream caller random_fortuna_read is responsible for zeroing out * sensitive buffers provided as parameters to this routine. */ enum { FORTUNA_UNLOCKED = false, FORTUNA_LOCKED = true }; static void random_fortuna_genbytes(uint8_t *buf, size_t bytecount, uint8_t newkey[static RANDOM_KEYSIZE], uint128_t *p_counter, union randomdev_key *p_key, bool locked) { uint8_t remainder_buf[RANDOM_BLOCKSIZE]; size_t chunk_size; if (locked) RANDOM_RESEED_ASSERT_LOCK_OWNED(); else RANDOM_RESEED_ASSERT_LOCK_NOT_OWNED(); /* * Easy case: don't have to worry about bullying the global mutex, * don't have to worry about rekeying Chacha; API is byte-oriented. */ if (!locked && random_chachamode) { randomdev_keystream(p_key, p_counter, buf, bytecount); return; } if (locked) { /* * While holding the global lock, limit PRF generation to * mitigate, but not eliminate, bullying symptoms. */ chunk_size = PAGE_SIZE; } else { /* * 128-bit block ciphers like AES must be re-keyed at 1MB * intervals to avoid unacceptable statistical differentiation * from true random data (FS&K 9.4, p. 143-144). */ MPASS(!random_chachamode); chunk_size = RANDOM_FORTUNA_MAX_READ; } chunk_size = MIN(bytecount, chunk_size); if (!random_chachamode) chunk_size = rounddown(chunk_size, RANDOM_BLOCKSIZE); while (bytecount >= chunk_size && chunk_size > 0) { randomdev_keystream(p_key, p_counter, buf, chunk_size); buf += chunk_size; bytecount -= chunk_size; /* We have to rekey if there is any data remaining to be * generated, in two scenarios: * * locked: we need to rekey before we unlock and release the * global state to another consumer; or * * unlocked: we need to rekey because we're in AES mode and are * required to rekey at chunk_size==1MB. But we do not need to * rekey during the last trailing <1MB chunk. */ if (bytecount > 0) { if (locked || chunk_size == RANDOM_FORTUNA_MAX_READ) { randomdev_keystream(p_key, p_counter, newkey, RANDOM_KEYSIZE); randomdev_encrypt_init(p_key, newkey); } /* * If we're holding the global lock, yield it briefly * now. */ if (locked) { RANDOM_RESEED_UNLOCK(); RANDOM_RESEED_LOCK(); } /* * At the trailing end, scale down chunk_size from 1MB or * PAGE_SIZE to all remaining full blocks (AES) or all * remaining bytes (Chacha). */ if (bytecount < chunk_size) { if (random_chachamode) chunk_size = bytecount; else if (bytecount >= RANDOM_BLOCKSIZE) chunk_size = rounddown(bytecount, RANDOM_BLOCKSIZE); else break; } } } /* * Generate any partial AES block remaining into a temporary buffer and * copy the desired substring out. */ if (bytecount > 0) { MPASS(!random_chachamode); randomdev_keystream(p_key, p_counter, remainder_buf, sizeof(remainder_buf)); } /* * In locked mode, re-key global K before dropping the lock, which we * don't need for memcpy/bzero below. */ if (locked) { randomdev_keystream(p_key, p_counter, newkey, RANDOM_KEYSIZE); randomdev_encrypt_init(p_key, newkey); RANDOM_RESEED_UNLOCK(); } if (bytecount > 0) { memcpy(buf, remainder_buf, bytecount); explicit_bzero(remainder_buf, sizeof(remainder_buf)); } } /* * Handle only "concurrency-enabled" Fortuna reads to simplify logic. * * Caller (random_fortuna_read) is responsible for zeroing out sensitive * buffers provided as parameters to this routine. */ static void random_fortuna_read_concurrent(uint8_t *buf, size_t bytecount, uint8_t newkey[static RANDOM_KEYSIZE]) { union randomdev_key key_copy; uint128_t counter_copy; size_t blockcount; MPASS(fortuna_concurrent_read); /* * Compute number of blocks required for the PRF request ('delta C'). * We will step the global counter 'C' by this number under lock, and * then actually consume the counter values outside the lock. * * This ensures that contemporaneous but independent requests for * randomness receive distinct 'C' values and thus independent PRF * results. */ if (random_chachamode) { blockcount = howmany(bytecount, CHACHA_BLOCKLEN); } else { blockcount = howmany(bytecount, RANDOM_BLOCKSIZE); /* * Need to account for the additional blocks generated by * rekeying when updating the global fs_counter. */ blockcount += RANDOM_KEYS_PER_BLOCK * (blockcount / RANDOM_FORTUNA_BLOCKS_PER_KEY); } RANDOM_RESEED_LOCK(); KASSERT(!uint128_is_zero(fortuna_state.fs_counter), ("FS&K: C != 0")); /* * Save the original counter and key values that will be used as the * PRF for this particular consumer. */ memcpy(&counter_copy, &fortuna_state.fs_counter, sizeof(counter_copy)); memcpy(&key_copy, &fortuna_state.fs_key, sizeof(key_copy)); /* * Step the counter as if we had generated 'bytecount' blocks for this * consumer. I.e., ensure that the next consumer gets an independent * range of counter values once we drop the global lock. */ uint128_add64(&fortuna_state.fs_counter, blockcount); /* * We still need to Rekey the global 'K' between independent calls; * this is no different from conventional Fortuna. Note that * 'randomdev_keystream()' will step the fs_counter 'C' appropriately * for the blocks needed for the 'newkey'. * * (This is part of PseudoRandomData() in FS&K, 9.4.4.) */ randomdev_keystream(&fortuna_state.fs_key, &fortuna_state.fs_counter, newkey, RANDOM_KEYSIZE); randomdev_encrypt_init(&fortuna_state.fs_key, newkey); /* * We have everything we need to generate a unique PRF for this * consumer without touching global state. */ RANDOM_RESEED_UNLOCK(); random_fortuna_genbytes(buf, bytecount, newkey, &counter_copy, &key_copy, FORTUNA_UNLOCKED); RANDOM_RESEED_ASSERT_LOCK_NOT_OWNED(); explicit_bzero(&counter_copy, sizeof(counter_copy)); explicit_bzero(&key_copy, sizeof(key_copy)); } /*- * FS&K - RandomData() (Part 2) * Main read from Fortuna, continued. May be called multiple times after * the random_fortuna_pre_read() above. * * The supplied buf MAY not be a multiple of RANDOM_BLOCKSIZE in size; it is * the responsibility of the algorithm to accommodate partial block reads, if a * block output mode is used. */ void random_fortuna_read(uint8_t *buf, size_t bytecount) { uint8_t newkey[RANDOM_KEYSIZE]; if (fortuna_concurrent_read) { random_fortuna_read_concurrent(buf, bytecount, newkey); goto out; } RANDOM_RESEED_LOCK(); KASSERT(!uint128_is_zero(fortuna_state.fs_counter), ("FS&K: C != 0")); random_fortuna_genbytes(buf, bytecount, newkey, &fortuna_state.fs_counter, &fortuna_state.fs_key, FORTUNA_LOCKED); /* Returns unlocked */ RANDOM_RESEED_ASSERT_LOCK_NOT_OWNED(); out: explicit_bzero(newkey, sizeof(newkey)); } #ifdef _KERNEL static bool block_seeded_status = false; SYSCTL_BOOL(_kern_random, OID_AUTO, block_seeded_status, CTLFLAG_RWTUN, &block_seeded_status, 0, "If non-zero, pretend Fortuna is in an unseeded state. By setting " "this as a tunable, boot can be tested as if the random device is " "unavailable."); #endif static bool random_fortuna_seeded_internal(void) { return (!uint128_is_zero(fortuna_state.fs_counter)); } static bool random_fortuna_seeded(void) { #ifdef _KERNEL if (block_seeded_status) return (false); #endif if (__predict_true(random_fortuna_seeded_internal())) return (true); /* * Maybe we have enough entropy in the zeroth pool but just haven't * kicked the initial seed step. Do so now. */ random_fortuna_pre_read(); return (random_fortuna_seeded_internal()); } Index: head/sys/dev/random/random_harvestq.c =================================================================== --- head/sys/dev/random/random_harvestq.c (revision 356244) +++ head/sys/dev/random/random_harvestq.c (revision 356245) @@ -1,659 +1,660 @@ /*- * 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 __FBSDID("$FreeBSD$"); #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 static void random_kthread(void); static void random_sources_feed(void); static u_int read_rate; /* * 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; /* * 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. */ __read_frequently u_int hc_source_mask; struct random_sources { CK_LIST_ENTRY(random_sources) rrs_entries; 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, 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; /* * Lockless ring buffer holding entropy events * If ring.in == ring.out, * the buffer is empty. * If ring.in != ring.out, * the buffer contains harvested entropy. * If (ring.in + 1) == ring.out (mod RANDOM_RING_MAX), * the buffer is full. * * NOTE: ring.in points to the last added element, * and ring.out points to the last consumed element. * * The ring.in variable needs locking as there are multiple * sources to the ring. Only the sources may change ring.in, * but the consumer may examine it. * * The ring.out variable does not need locking as there is * only one consumer. Only the consumer may change ring.out, * but the sources may examine it. */ struct entropy_ring { struct harvest_event ring[RANDOM_RING_MAX]; volatile u_int in; volatile u_int out; } hc_entropy_ring; struct fast_entropy_accumulator { volatile u_int pos; uint32_t buf[RANDOM_ACCUM_MAX]; } hc_entropy_fast_accumulator; } harvest_context; 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) { u_int maxloop, ring_out, i; /* * Locking is not needed as this is the only place we modify ring.out, and * we only examine ring.in without changing it. Both of these are volatile, * and this is a unique thread. */ for (random_kthread_control = 1; random_kthread_control;) { /* Deal with events, if any. Restrict the number we do in one go. */ maxloop = RANDOM_RING_MAX; while (harvest_context.hc_entropy_ring.out != harvest_context.hc_entropy_ring.in) { ring_out = (harvest_context.hc_entropy_ring.out + 1)%RANDOM_RING_MAX; random_harvestq_fast_process_event(harvest_context.hc_entropy_ring.ring + ring_out); harvest_context.hc_entropy_ring.out = ring_out; if (!--maxloop) break; } random_sources_feed(); /* XXX: FIX!! Increase the high-performance data rate? Need some measurements first. */ for (i = 0; i < RANDOM_ACCUM_MAX; i++) { if (harvest_context.hc_entropy_fast_accumulator.buf[i]) { random_harvest_direct(harvest_context.hc_entropy_fast_accumulator.buf + i, sizeof(harvest_context.hc_entropy_fast_accumulator.buf[0]), RANDOM_UMA); harvest_context.hc_entropy_fast_accumulator.buf[i] = 0; } } /* XXX: FIX!! This is a *great* place to pass hardware/live entropy to random(9) */ tsleep_sbt(&harvest_context.hc_kthread_proc, 0, "-", SBT_1S/10, 0, C_PREL(1)); } random_kthread_control = -1; wakeup(&harvest_context.hc_kthread_proc); kproc_exit(0); /* NOTREACHED */ } /* This happens well after SI_SUB_RANDOM */ SYSINIT(random_device_h_proc, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, kproc_start, &random_proc_kp); 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, local_read_rate; bool rse_warm; rse_warm = epoch_inited; /* * Step over all of live entropy sources, and feed their output * to the system-wide RNG. */ local_read_rate = atomic_readandclear_32(&read_rate); /* Perform at least one read per round */ local_read_rate = MAX(local_read_rate, 1); /* But not exceeding RANDOM_KEYSIZE_WORDS */ local_read_rate = MIN(local_read_rate, RANDOM_KEYSIZE_WORDS); if (rse_warm) epoch_enter_preempt(rs_epoch, &et); CK_LIST_FOREACH(rrs, &source_list, rrs_entries) { for (i = 0; i < p_random_alg_context->ra_poolcount*local_read_rate; i++) { 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)); } void read_rate_increment(u_int chunk) { atomic_add_32(&read_rate, chunk); } /* ARGSUSED */ 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, orig_value; orig_value = value = 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. */ hc_source_mask = (value & ~user_immutable_mask) | (orig_value & user_immutable_mask); return (0); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask, CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, random_check_uint_harvestmask, "IU", "Entropy harvesting mask"); /* ARGSUSED */ static int random_print_harvestmask(SYSCTL_HANDLER_ARGS) { struct sbuf sbuf; int error, i; error = sysctl_wire_old_buffer(req, 0); if (error == 0) { sbuf_new_for_sysctl(&sbuf, NULL, 128, req); for (i = ENTROPYSOURCE - 1; i >= 0; i--) sbuf_cat(&sbuf, (hc_source_mask & (1 << i)) ? "1" : "0"); error = sbuf_finish(&sbuf); sbuf_delete(&sbuf); } return (error); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_bin, CTLTYPE_STRING | CTLFLAG_RD, 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", /* ENVIRONMENTAL_END */ [RANDOM_PURE_OCTEON] = "PURE_OCTEON", /* PURE_START */ [RANDOM_PURE_SAFE] = "PURE_SAFE", [RANDOM_PURE_GLXSB] = "PURE_GLXSB", [RANDOM_PURE_UBSEC] = "PURE_UBSEC", [RANDOM_PURE_HIFN] = "PURE_HIFN", [RANDOM_PURE_RDRAND] = "PURE_RDRAND", [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] = "VMGENID", /* "ENTROPYSOURCE" */ }; /* ARGSUSED */ 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) { sbuf_new_for_sysctl(&sbuf, NULL, 128, req); for (i = ENTROPYSOURCE - 1; i >= 0; i--) { if (i >= RANDOM_PURE_START && (hc_source_mask & (1 << i)) == 0) continue; if (!first) sbuf_cat(&sbuf, ","); sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "[" : ""); sbuf_cat(&sbuf, random_source_descr[i]); sbuf_cat(&sbuf, !(hc_source_mask & (1 << i)) ? "]" : ""); first = false; } error = sbuf_finish(&sbuf); sbuf_delete(&sbuf); } return (error); } SYSCTL_PROC(_kern_random_harvest, OID_AUTO, mask_symbolic, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0, random_print_harvestmask_symbolic, "A", "Entropy harvesting mask (symbolic)"); /* ARGSUSED */ 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_entropy_ring.in = harvest_context.hc_entropy_ring.out = 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 = (uint32_t)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. */ /* ARGSUSED */ 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"); } } SYSINIT(random_device_prime, SI_SUB_RANDOM, SI_ORDER_MIDDLE, random_harvestq_prime, NULL); /* ARGSUSED */ 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 will usually cause lots of failures of the "Lockless read" * check a few lines below. 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_event *event; u_int ring_in; KASSERT(origin >= RANDOM_START && origin < ENTROPYSOURCE, ("%s: origin %d invalid\n", __func__, origin)); RANDOM_HARVEST_LOCK(); ring_in = (harvest_context.hc_entropy_ring.in + 1)%RANDOM_RING_MAX; if (ring_in != harvest_context.hc_entropy_ring.out) { /* The ring is not full */ event = harvest_context.hc_entropy_ring.ring + ring_in; event->he_somecounter = (uint32_t)get_cyclecount(); event->he_source = origin; event->he_destination = harvest_context.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); } harvest_context.hc_entropy_ring.in = ring_in; } 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, (uint32_t)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 = (uint32_t)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_harvest_register_source(enum random_entropy_source source) { hc_source_mask |= (1 << source); } void random_harvest_deregister_source(enum random_entropy_source source) { hc_source_mask &= ~(1 << source); } void random_source_register(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; random_harvest_register_source(rsource->rs_source); printf("random: registering fast source %s\n", rsource->rs_ident); RANDOM_HARVEST_LOCK(); CK_LIST_INSERT_HEAD(&source_list, rrs, rrs_entries); RANDOM_HARVEST_UNLOCK(); } void random_source_deregister(struct random_source *rsource) { struct random_sources *rrs = NULL; KASSERT(rsource != NULL, ("invalid input to %s", __func__)); random_harvest_deregister_source(rsource->rs_source); RANDOM_HARVEST_LOCK(); 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); Index: head/sys/dev/vmgenc/vmgenc_acpi.c =================================================================== --- head/sys/dev/vmgenc/vmgenc_acpi.c (revision 356244) +++ head/sys/dev/vmgenc/vmgenc_acpi.c (revision 356245) @@ -1,240 +1,262 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2019 Conrad Meyer . 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. * 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. */ /* * VM Generation Counter driver * * See, e.g., the "Virtual Machine Generation ID" white paper: * https://go.microsoft.com/fwlink/p/?LinkID=260709 , and perhaps also: * https://docs.microsoft.com/en-us/windows/win32/hyperv_v2/virtual-machine-generation-identifier , * https://azure.microsoft.com/en-us/blog/accessing-and-using-azure-vm-unique-id/ * * Microsoft introduced the concept in 2013 or so and seems to have * successfully driven it to a consensus standard among hypervisors, not just * HyperV/Azure: * - QEMU: https://bugzilla.redhat.com/show_bug.cgi?id=1118834 * - VMware/ESXi: https://kb.vmware.com/s/article/2032586 * - Xen: https://github.com/xenserver/xen-4.5/blob/master/tools/firmware/hvmloader/acpi/dsdt.asl#L456 */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include +#include #include #include #include #include +#include #include #ifndef ACPI_NOTIFY_STATUS_CHANGED #define ACPI_NOTIFY_STATUS_CHANGED 0x80 #endif #define GUID_BYTES 16 static const char *vmgenc_ids[] = { "VM_GEN_COUNTER", NULL }; #if 0 MODULE_PNP_INFO("Z:_CID", acpi, vmgenc, vmgenc_ids, nitems(vmgenc_ids) - 1); #endif struct vmgenc_softc { volatile void *vmg_pguid; uint8_t vmg_cache_guid[GUID_BYTES]; }; static void +vmgenc_harvest_all(const void *p, size_t sz) +{ + size_t nbytes; + + while (sz > 0) { + nbytes = MIN(sz, + sizeof(((struct harvest_event *)0)->he_entropy)); + random_harvest_direct(p, nbytes, RANDOM_PURE_VMGENID); + p = (const char *)p + nbytes; + sz -= nbytes; + } +} + +static void vmgenc_status_changed(void *context) { uint8_t guid[GUID_BYTES]; struct vmgenc_softc *sc; device_t dev; dev = context; sc = device_get_softc(dev); /* Check for spurious notify events. */ memcpy(guid, __DEVOLATILE(void *, sc->vmg_pguid), sizeof(guid)); if (memcmp(guid, sc->vmg_cache_guid, GUID_BYTES) == 0) return; /* No change. */ /* Update cache. */ memcpy(sc->vmg_cache_guid, guid, GUID_BYTES); + vmgenc_harvest_all(sc->vmg_cache_guid, sizeof(sc->vmg_cache_guid)); + EVENTHANDLER_INVOKE(acpi_vmgenc_event); acpi_UserNotify("VMGenerationCounter", acpi_get_handle(dev), 0); } static void vmgenc_notify(ACPI_HANDLE h, UINT32 notify, void *context) { device_t dev; dev = context; switch (notify) { case ACPI_NOTIFY_STATUS_CHANGED: /* * We're possibly in GPE / interrupt context, kick the event up * to a taskqueue. */ AcpiOsExecute(OSL_NOTIFY_HANDLER, vmgenc_status_changed, dev); break; default: device_printf(dev, "unknown notify %#x\n", notify); break; } } static int vmgenc_probe(device_t dev) { int rv; if (acpi_disabled("vmgenc")) return (ENXIO); rv = ACPI_ID_PROBE(device_get_parent(dev), dev, __DECONST(char **, vmgenc_ids), NULL); if (rv <= 0) device_set_desc(dev, "VM Generation Counter"); return (rv); } static const char * vmgenc_acpi_getname(ACPI_HANDLE handle, char data[static 256]) { ACPI_BUFFER buf; buf.Length = 256; buf.Pointer = data; if (ACPI_SUCCESS(AcpiGetName(handle, ACPI_FULL_PATHNAME, &buf))) return (data); return ("(unknown)"); } static int acpi_GetPackedUINT64(device_t dev, ACPI_HANDLE handle, char *path, uint64_t *out) { char hpath[256]; ACPI_STATUS status; ACPI_BUFFER buf; ACPI_OBJECT param[3]; buf.Pointer = param; buf.Length = sizeof(param); status = AcpiEvaluateObject(handle, path, NULL, &buf); if (!ACPI_SUCCESS(status)) { device_printf(dev, "%s(%s::%s()): %s\n", __func__, vmgenc_acpi_getname(handle, hpath), path, AcpiFormatException(status)); return (ENXIO); } if (param[0].Type != ACPI_TYPE_PACKAGE) { device_printf(dev, "%s(%s::%s()): Wrong type %#x\n", __func__, vmgenc_acpi_getname(handle, hpath), path, param[0].Type); return (ENXIO); } if (param[0].Package.Count != 2) { device_printf(dev, "%s(%s::%s()): Wrong number of results %u\n", __func__, vmgenc_acpi_getname(handle, hpath), path, param[0].Package.Count); return (ENXIO); } if (param[0].Package.Elements[0].Type != ACPI_TYPE_INTEGER || param[0].Package.Elements[1].Type != ACPI_TYPE_INTEGER) { device_printf(dev, "%s(%s::%s()): Wrong type results %#x, %#x\n", __func__, vmgenc_acpi_getname(handle, hpath), path, param[0].Package.Elements[0].Type, param[0].Package.Elements[1].Type); return (ENXIO); } *out = (param[0].Package.Elements[0].Integer.Value & UINT32_MAX) | ((uint64_t)param[0].Package.Elements[1].Integer.Value << 32); if (*out == 0) return (ENXIO); return (0); } static int vmgenc_attach(device_t dev) { struct vmgenc_softc *sc; uint64_t guid_physaddr; ACPI_HANDLE h; int error; h = acpi_get_handle(dev); sc = device_get_softc(dev); error = acpi_GetPackedUINT64(dev, h, "ADDR", &guid_physaddr); if (error != 0) return (error); SYSCTL_ADD_OPAQUE(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "guid", CTLFLAG_RD, sc->vmg_cache_guid, GUID_BYTES, "", "latest cached VM generation counter (128-bit UUID)"); sc->vmg_pguid = AcpiOsMapMemory(guid_physaddr, GUID_BYTES); memcpy(sc->vmg_cache_guid, __DEVOLATILE(void *, sc->vmg_pguid), sizeof(sc->vmg_cache_guid)); + random_harvest_register_source(RANDOM_PURE_VMGENID); + vmgenc_harvest_all(sc->vmg_cache_guid, sizeof(sc->vmg_cache_guid)); + AcpiInstallNotifyHandler(h, ACPI_DEVICE_NOTIFY, vmgenc_notify, dev); return (0); } static device_method_t vmgenc_methods[] = { DEVMETHOD(device_probe, vmgenc_probe), DEVMETHOD(device_attach, vmgenc_attach), DEVMETHOD_END }; static driver_t vmgenc_driver = { "vmgenc", vmgenc_methods, sizeof(struct vmgenc_softc), }; static devclass_t vmgenc_devclass; DRIVER_MODULE(vmgenc, acpi, vmgenc_driver, vmgenc_devclass, NULL, NULL); MODULE_DEPEND(vmgenc, acpi, 1, 1, 1); +MODULE_DEPEND(vemgenc, random_harvestq, 1, 1, 1); Index: head/sys/sys/random.h =================================================================== --- head/sys/sys/random.h (revision 356244) +++ head/sys/sys/random.h (revision 356245) @@ -1,166 +1,167 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * 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. * * $FreeBSD$ */ #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_ENVIRONMENTAL_END = RANDOM_UMA, /* Fast hardware random-number sources from here on. */ RANDOM_PURE_START, RANDOM_PURE_OCTEON = RANDOM_PURE_START, RANDOM_PURE_SAFE, RANDOM_PURE_GLXSB, RANDOM_PURE_UBSEC, RANDOM_PURE_HIFN, RANDOM_PURE_RDRAND, RANDOM_PURE_NEHEMIAH, RANDOM_PURE_RNDTEST, RANDOM_PURE_VIRTIO, RANDOM_PURE_BROADCOM, RANDOM_PURE_CCP, RANDOM_PURE_DARN, RANDOM_PURE_TPM, + RANDOM_PURE_VMGENID, 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" 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); } void random_harvest_register_source(enum random_entropy_source); void random_harvest_deregister_source(enum random_entropy_source); #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) */ #endif /* _KERNEL */ #define GRND_NONBLOCK 0x1 #define GRND_RANDOM 0x2 __BEGIN_DECLS ssize_t getrandom(void *buf, size_t buflen, unsigned int flags); __END_DECLS #endif /* _SYS_RANDOM_H_ */