Thomas Weißschuhrandom: vDSO: Remove ifdeffery260b98f8 months agoHistory
1712 lines · 52.2 KB · C
RawDownload
// SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)/* * Copyright (C) 2017-2024 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved. * * This driver produces cryptographically secure pseudorandom data. It is divided * into roughly six sections, each with a section header: * *   - Initialization and readiness waiting. *   - Fast key erasure RNG, the "crng". *   - Entropy accumulation and extraction routines. *   - Entropy collection routines. *   - Userspace reader/writer interfaces. *   - Sysctl interface. * * The high level overview is that there is one input pool, into which * various pieces of data are hashed. Prior to initialization, some of that * data is then "credited" as having a certain number of bits of entropy. * When enough bits of entropy are available, the hash is finalized and * handed as a key to a stream cipher that expands it indefinitely for * various consumers. This key is periodically refreshed as the various * entropy collectors, described below, add data to the input pool. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/utsname.h>#include <linux/module.h>#include <linux/kernel.h>#include <linux/major.h>#include <linux/string.h>#include <linux/fcntl.h>#include <linux/slab.h>#include <linux/random.h>#include <linux/poll.h>#include <linux/init.h>#include <linux/fs.h>#include <linux/blkdev.h>#include <linux/interrupt.h>#include <linux/mm.h>#include <linux/nodemask.h>#include <linux/spinlock.h>#include <linux/kthread.h>#include <linux/percpu.h>#include <linux/ptrace.h>#include <linux/workqueue.h>#include <linux/irq.h>#include <linux/ratelimit.h>#include <linux/syscalls.h>#include <linux/completion.h>#include <linux/uuid.h>#include <linux/uaccess.h>#include <linux/suspend.h>#include <linux/siphash.h>#include <linux/sched/isolation.h>#include <crypto/chacha.h>#include <crypto/blake2s.h>#include <vdso/datapage.h>#include <asm/archrandom.h>#include <asm/processor.h>#include <asm/irq.h>#include <asm/irq_regs.h>#include <asm/io.h> /********************************************************************* * * Initialization and readiness waiting. * * Much of the RNG infrastructure is devoted to various dependencies * being able to wait until the RNG has collected enough entropy and * is ready for safe consumption. * *********************************************************************/ /* * crng_init is protected by base_crng->lock, and only increases * its value (from empty->early->ready). */static enum {	CRNG_EMPTY = 0, /* Little to no entropy collected */	CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */	CRNG_READY = 2  /* Fully initialized with POOL_READY_BITS collected */} crng_init __read_mostly = CRNG_EMPTY;static DEFINE_STATIC_KEY_FALSE(crng_is_ready);#define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)/* Various types of waiters for crng_init->CRNG_READY transition. */static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);static struct fasync_struct *fasync;static ATOMIC_NOTIFIER_HEAD(random_ready_notifier); /* Control how we warn userspace. */static struct ratelimit_state urandom_warning =	RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);static int ratelimit_disable __read_mostly = 0;module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression"); /* * Returns whether or not the input pool has been seeded and thus guaranteed * to supply cryptographically secure random numbers. This applies to: the * /dev/urandom device, the get_random_bytes function, and the get_random_{u8, * u16,u32,u64,long} family of functions. * * Returns: true if the input pool has been seeded. *          false if the input pool has not been seeded. */bool rng_is_initialized(void){	return crng_ready();}EXPORT_SYMBOL(rng_is_initialized); static void __cold crng_set_ready(struct work_struct *work){	static_branch_enable(&crng_is_ready);} /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */static void try_to_generate_entropy(void); /* * Wait for the input pool to be seeded and thus guaranteed to supply * cryptographically secure random numbers. This applies to: the /dev/urandom * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64, * long} family of functions. Using any of these functions without first * calling this function forfeits the guarantee of security. * * Returns: 0 if the input pool has been seeded. *          -ERESTARTSYS if the function was interrupted by a signal. */int wait_for_random_bytes(void){	while (!crng_ready()) {		int ret; 		try_to_generate_entropy();		ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);		if (ret)			return ret > 0 ? 0 : ret;	}	return 0;}EXPORT_SYMBOL(wait_for_random_bytes); /* * Add a callback function that will be invoked when the crng is initialised, * or immediately if it already has been. Only use this is you are absolutely * sure it is required. Most users should instead be able to test * `rng_is_initialized()` on demand, or make use of `get_random_bytes_wait()`. */int __cold execute_with_initialized_rng(struct notifier_block *nb){	unsigned long flags;	int ret = 0; 	spin_lock_irqsave(&random_ready_notifier.lock, flags);	if (crng_ready())		nb->notifier_call(nb, 0, NULL);	else		ret = raw_notifier_chain_register((struct raw_notifier_head *)&random_ready_notifier.head, nb);	spin_unlock_irqrestore(&random_ready_notifier.lock, flags);	return ret;} /********************************************************************* * * Fast key erasure RNG, the "crng". * * These functions expand entropy from the entropy extractor into * long streams for external consumption using the "fast key erasure" * RNG described at <https://blog.cr.yp.to/20170723-random.html>. * * There are a few exported interfaces for use by other drivers: * *	void get_random_bytes(void *buf, size_t len) *	u8 get_random_u8() *	u16 get_random_u16() *	u32 get_random_u32() *	u32 get_random_u32_below(u32 ceil) *	u32 get_random_u32_above(u32 floor) *	u32 get_random_u32_inclusive(u32 floor, u32 ceil) *	u64 get_random_u64() *	unsigned long get_random_long() * * These interfaces will return the requested number of random bytes * into the given buffer or as a return value. This is equivalent to * a read from /dev/urandom. The u8, u16, u32, u64, long family of * functions may be higher performance for one-off random integers, * because they do a bit of buffering and do not invoke reseeding * until the buffer is emptied. * *********************************************************************/ enum {	CRNG_RESEED_START_INTERVAL = HZ,	CRNG_RESEED_INTERVAL = 60 * HZ}; static struct {	u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));	unsigned long generation;	spinlock_t lock;} base_crng = {	.lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)}; struct crng {	u8 key[CHACHA_KEY_SIZE];	unsigned long generation;	local_lock_t lock;}; static DEFINE_PER_CPU(struct crng, crngs) = {	.generation = ULONG_MAX,	.lock = INIT_LOCAL_LOCK(crngs.lock),}; /* * Return the interval until the next reseeding, which is normally * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval * proportional to the uptime. */static unsigned int crng_reseed_interval(void){	static bool early_boot = true; 	if (unlikely(READ_ONCE(early_boot))) {		time64_t uptime = ktime_get_seconds();		if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)			WRITE_ONCE(early_boot, false);		else			return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,				     (unsigned int)uptime / 2 * HZ);	}	return CRNG_RESEED_INTERVAL;} /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */static void extract_entropy(void *buf, size_t len); /* This extracts a new crng key from the input pool. */static void crng_reseed(struct work_struct *work){	static DECLARE_DELAYED_WORK(next_reseed, crng_reseed);	unsigned long flags;	unsigned long next_gen;	u8 key[CHACHA_KEY_SIZE]; 	/* Immediately schedule the next reseeding, so that it fires sooner rather than later. */	if (likely(system_dfl_wq))		queue_delayed_work(system_dfl_wq, &next_reseed, crng_reseed_interval()); 	extract_entropy(key, sizeof(key)); 	/*	 * We copy the new key into the base_crng, overwriting the old one,	 * and update the generation counter. We avoid hitting ULONG_MAX,	 * because the per-cpu crngs are initialized to ULONG_MAX, so this	 * forces new CPUs that come online to always initialize.	 */	spin_lock_irqsave(&base_crng.lock, flags);	memcpy(base_crng.key, key, sizeof(base_crng.key));	next_gen = base_crng.generation + 1;	if (next_gen == ULONG_MAX)		++next_gen;	WRITE_ONCE(base_crng.generation, next_gen); 	/* base_crng.generation's invalid value is ULONG_MAX, while	 * vdso_k_rng_data->generation's invalid value is 0, so add one to the	 * former to arrive at the latter. Use smp_store_release so that this	 * is ordered with the write above to base_crng.generation. Pairs with	 * the smp_rmb() before the syscall in the vDSO code.	 *	 * Cast to unsigned long for 32-bit architectures, since atomic 64-bit	 * operations are not supported on those architectures. This is safe	 * because base_crng.generation is a 32-bit value. On big-endian	 * architectures it will be stored in the upper 32 bits, but that's okay	 * because the vDSO side only checks whether the value changed, without	 * actually using or interpreting the value.	 */	if (IS_ENABLED(CONFIG_VDSO_GETRANDOM))		smp_store_release((unsigned long *)&vdso_k_rng_data->generation, next_gen + 1); 	if (!static_branch_likely(&crng_is_ready))		crng_init = CRNG_READY;	spin_unlock_irqrestore(&base_crng.lock, flags);	memzero_explicit(key, sizeof(key));} /* * This generates a ChaCha block using the provided key, and then * immediately overwrites that key with half the block. It returns * the resultant ChaCha state to the user, along with the second * half of the block containing 32 bytes of random data that may * be used; random_data_len may not be greater than 32. * * The returned ChaCha state contains within it a copy of the old * key value, at index 4, so the state should always be zeroed out * immediately after using in order to maintain forward secrecy. * If the state cannot be erased in a timely manner, then it is * safer to set the random_data parameter to &chacha_state->x[4] * so that this function overwrites it before returning. */static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],				  struct chacha_state *chacha_state,				  u8 *random_data, size_t random_data_len){	u8 first_block[CHACHA_BLOCK_SIZE]; 	BUG_ON(random_data_len > 32); 	chacha_init_consts(chacha_state);	memcpy(&chacha_state->x[4], key, CHACHA_KEY_SIZE);	memset(&chacha_state->x[12], 0, sizeof(u32) * 4);	chacha20_block(chacha_state, first_block); 	memcpy(key, first_block, CHACHA_KEY_SIZE);	memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);	memzero_explicit(first_block, sizeof(first_block));} /* * This function returns a ChaCha state that you may use for generating * random data. It also returns up to 32 bytes on its own of random data * that may be used; random_data_len may not be greater than 32. */static void crng_make_state(struct chacha_state *chacha_state,			    u8 *random_data, size_t random_data_len){	unsigned long flags;	struct crng *crng; 	BUG_ON(random_data_len > 32); 	/*	 * For the fast path, we check whether we're ready, unlocked first, and	 * then re-check once locked later. In the case where we're really not	 * ready, we do fast key erasure with the base_crng directly, extracting	 * when crng_init is CRNG_EMPTY.	 */	if (!crng_ready()) {		bool ready; 		spin_lock_irqsave(&base_crng.lock, flags);		ready = crng_ready();		if (!ready) {			if (crng_init == CRNG_EMPTY)				extract_entropy(base_crng.key, sizeof(base_crng.key));			crng_fast_key_erasure(base_crng.key, chacha_state,					      random_data, random_data_len);		}		spin_unlock_irqrestore(&base_crng.lock, flags);		if (!ready)			return;	} 	local_lock_irqsave(&crngs.lock, flags);	crng = raw_cpu_ptr(&crngs); 	/*	 * If our per-cpu crng is older than the base_crng, then it means	 * somebody reseeded the base_crng. In that case, we do fast key	 * erasure on the base_crng, and use its output as the new key	 * for our per-cpu crng. This brings us up to date with base_crng.	 */	if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {		spin_lock(&base_crng.lock);		crng_fast_key_erasure(base_crng.key, chacha_state,				      crng->key, sizeof(crng->key));		crng->generation = base_crng.generation;		spin_unlock(&base_crng.lock);	} 	/*	 * Finally, when we've made it this far, our per-cpu crng has an up	 * to date key, and we can do fast key erasure with it to produce	 * some random data and a ChaCha state for the caller. All other	 * branches of this function are "unlikely", so most of the time we	 * should wind up here immediately.	 */	crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);	local_unlock_irqrestore(&crngs.lock, flags);} static void _get_random_bytes(void *buf, size_t len){	struct chacha_state chacha_state;	u8 tmp[CHACHA_BLOCK_SIZE];	size_t first_block_len; 	if (!len)		return; 	first_block_len = min_t(size_t, 32, len);	crng_make_state(&chacha_state, buf, first_block_len);	len -= first_block_len;	buf += first_block_len; 	while (len) {		if (len < CHACHA_BLOCK_SIZE) {			chacha20_block(&chacha_state, tmp);			memcpy(buf, tmp, len);			memzero_explicit(tmp, sizeof(tmp));			break;		} 		chacha20_block(&chacha_state, buf);		if (unlikely(chacha_state.x[12] == 0))			++chacha_state.x[13];		len -= CHACHA_BLOCK_SIZE;		buf += CHACHA_BLOCK_SIZE;	} 	chacha_zeroize_state(&chacha_state);} /* * This returns random bytes in arbitrary quantities. The quality of the * random bytes is as good as /dev/urandom. In order to ensure that the * randomness provided by this function is okay, the function * wait_for_random_bytes() should be called and return 0 at least once * at any point prior. */void get_random_bytes(void *buf, size_t len){	_get_random_bytes(buf, len);}EXPORT_SYMBOL(get_random_bytes); static ssize_t get_random_bytes_user(struct iov_iter *iter){	struct chacha_state chacha_state;	u8 block[CHACHA_BLOCK_SIZE];	size_t ret = 0, copied; 	if (unlikely(!iov_iter_count(iter)))		return 0; 	/*	 * Immediately overwrite the ChaCha key at index 4 with random	 * bytes, in case userspace causes copy_to_iter() below to sleep	 * forever, so that we still retain forward secrecy in that case.	 */	crng_make_state(&chacha_state, (u8 *)&chacha_state.x[4],			CHACHA_KEY_SIZE);	/*	 * However, if we're doing a read of len <= 32, we don't need to	 * use chacha_state after, so we can simply return those bytes to	 * the user directly.	 */	if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {		ret = copy_to_iter(&chacha_state.x[4], CHACHA_KEY_SIZE, iter);		goto out_zero_chacha;	} 	for (;;) {		chacha20_block(&chacha_state, block);		if (unlikely(chacha_state.x[12] == 0))			++chacha_state.x[13]; 		copied = copy_to_iter(block, sizeof(block), iter);		ret += copied;		if (!iov_iter_count(iter) || copied != sizeof(block))			break; 		BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);		if (ret % PAGE_SIZE == 0) {			if (signal_pending(current))				break;			cond_resched();		}	} 	memzero_explicit(block, sizeof(block));out_zero_chacha:	chacha_zeroize_state(&chacha_state);	return ret ? ret : -EFAULT;} /* * Batched entropy returns random integers. The quality of the random * number is as good as /dev/urandom. In order to ensure that the randomness * provided by this function is okay, the function wait_for_random_bytes() * should be called and return 0 at least once at any point prior. */ #define DEFINE_BATCHED_ENTROPY(type)						\struct batch_ ##type {								\	/*									\	 * We make this 1.5x a ChaCha block, so that we get the			\	 * remaining 32 bytes from fast key erasure, plus one full		\	 * block from the detached ChaCha state. We can increase		\	 * the size of this later if needed so long as we keep the		\	 * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE.		\	 */									\	type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))];		\	local_lock_t lock;							\	unsigned long generation;						\	unsigned int position;							\

Lines 1–500 of 1712.